PageSourceSearch

https://devriq.in/_next/static/chunks/5b720416a61a3d3b.js

js devriq.in collected 2026-10-04 22:27:02 UTC 230,357 bytes, 1 lines download raw bytes

1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,909156,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.parseCookie=h,r.parse=h,r.stringifyCookie=function(e,t){let r=(null==t?void 0:t.encode)||encodeURIComponent,i=[];for(let t of Object.keys(e)){let a=e[t];if(void 0===a)continue;if(!s.test(t))throw TypeError("cookie name is invalid: ".concat(t));let o=r(a);if(!n.test(o))throw TypeError("cookie val is invalid: ".concat(a));i.push("".concat(t,"=").concat(o))}return i.join("; ")},r.stringifySetCookie=u,r.serialize=u,r.parseSetCookie=function(e,t){let r=(null==t?void 0:t.decode)||g,s=e.length,n=d(e,0,s),i=p(e,0,n),a=-1===i?{name:"",value:r(f(e,0,n))}:{name:f(e,0,i),value:r(f(e,i+1,n))},l=n+1;for(;l<s;){let t=d(e,l,s),r=p(e,l,t),n=-1===r?f(e,l,t):f(e,l,r),i=-1===r?void 0:f(e,r+1,t);switch(n.toLowerCase()){case"httponly":a.httpOnly=!0;break;case"secure":a.secure=!0;break;case"partitioned":a.partitioned=!0;break;case"domain":a.domain=i;break;case"path":a.path=i;break;case"max-age":i&&o.test(i)&&(a.maxAge=Number(i));break;case"expires":if(!i)break;let c=new Date(i);Number.isFinite(c.valueOf())&&(a.expires=c);break;case"priority":if(!i)break;let h=i.toLowerCase();("low"===h||"medium"===h||"high"===h)&&(a.priority=h);break;case"samesite":if(!i)break;let u=i.toLowerCase();("lax"===u||"strict"===u||"none"===u)&&(a.sameSite=u)}l=t+1}return a},r.stringifySetCookie=u,r.serialize=u;let s=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,n=/^[\u0021-\u003A\u003C-\u007E]*$/,i=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,a=/^[\u0020-\u003A\u003D-\u007E]*$/,o=/^-?\d+$/,l=Object.prototype.toString,c=(()=>{let e=function(){};return e.prototype=Object.create(null),e})();function h(e,t){let r=new c,s=e.length;if(s<2)return r;let n=(null==t?void 0:t.decode)||g,i=0;do{let t=p(e,i,s);if(-1===t)break;let a=d(e,i,s);if(t>a){i=e.lastIndexOf(";",t-1)+1;continue}let o=f(e,i,t);void 0===r[o]&&(r[o]=n(f(e,t+1,a))),i=a+1}while(i<s)return r}function u(e,t,r){let o="object"==typeof e?e:{...r,name:e,value:String(t)},c="object"==typeof t?t:r,h=(null==c?void 0:c.encode)||encodeURIComponent;if(!s.test(o.name))throw TypeError("argument name is invalid: ".concat(o.name));let u=o.value?h(o.value):"";if(!n.test(u))throw TypeError("argument val is invalid: ".concat(o.value));let d=o.name+"="+u;if(void 0!==o.maxAge){if(!Number.isInteger(o.maxAge))throw TypeError("option maxAge is invalid: ".concat(o.maxAge));d+="; Max-Age="+o.maxAge}if(o.domain){if(!i.test(o.domain))throw TypeError("option domain is invalid: ".concat(o.domain));d+="; Domain="+o.domain}if(o.path){if(!a.test(o.path))throw TypeError("option path is invalid: ".concat(o.path));d+="; Path="+o.path}if(o.expires){var p;if(p=o.expires,"[object Date]"!==l.call(p)||!Number.isFinite(o.expires.valueOf()))throw TypeError("option expires is invali
1d: ".concat(o.expires));d+="; Expires="+o.expires.toUTCString()}if(o.httpOnly&&(d+="; HttpOnly"),o.secure&&(d+="; Secure"),o.partitioned&&(d+="; Partitioned"),o.priority)switch("string"==typeof o.priority?o.priority.toLowerCase():void 0){case"low":d+="; Priority=Low";break;case"medium":d+="; Priority=Medium";break;case"high":d+="; Priority=High";break;default:throw TypeError("option priority is invalid: ".concat(o.priority))}if(o.sameSite)switch("string"==typeof o.sameSite?o.sameSite.toLowerCase():o.sameSite){case!0:case"strict":d+="; SameSite=Strict";break;case"lax":d+="; SameSite=Lax";break;case"none":d+="; SameSite=None";break;default:throw TypeError("option sameSite is invalid: ".concat(o.sameSite))}return d}function d(e,t,r){let s=e.indexOf(";",t);return -1===s?r:s}function p(e,t,r){let s=e.indexOf("=",t);return s<r?s:-1}function f(e,t,r){let s=t,n=r;do{let t=e.charCodeAt(s);if(32!==t&&9!==t)break}while(++s<n)for(;n>s;){let t=e.charCodeAt(n-1);if(32!==t&&9!==t)break;n--}return e.slice(s,n)}function g(e){if(-1===e.indexOf("%"))return e;try{return decodeURIComponent(e)}catch(t){return e}}},511795,e=>{"use strict";let t,r,s,n;e.s(["createClient",()=>r0],511795);var i,a,o,l,c,h,u,d,p=e.i(247167);class f 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 g extends f{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class m extends f{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class y extends f{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(i||(i={}));function w(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}Object.create;Object.create,"function"==typeof SuppressedError&&SuppressedError;class b{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)?"undefined"!=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):"undefined"!=typeof FormData&&l instanceof FormData?i=l:(u["Content-Type"]="application/json",i=JSON.stringify(l)):i=!l||"string"==typeof l||"undefined"!=typeof Blob&&l instanceof Blob||l instanceof ArrayBuffer||"undefined"!=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 w=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 g(e)}),b=w.headers.get("x-relay-error");if(b&&"true"===b)throw new m(w);if(!w.ok)throw new y(w);let v=(null!=(t=w.headers.get("Content-Type"))?t:"text/plain").split(";")[0].trim();return{data:"application/json"===v?yield w.json():"application/octet-stream"===v||"application/pdf"===v?yield w.blob():"text/event-stream"
1===v?w:"multipart/form-data"===v?yield w.formData():yield w.text(),error:null,response:w}}catch(e){return{data:null,error:e,response:e instanceof y||e instanceof m?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=i.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 v=e=>Math.min(1e3*2**e,3e4),_=[520,503],k=["GET","HEAD","OPTIONS"];var S=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 E(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 T=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=new Headers(r.headers);e>0&&c.set("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"||!k.includes(r.method))throw t;if(r.retryEnabled&&e<3){let t=v(e);e++,await E(t,r.signal);continue}throw t}if(t=r.method,n=l.status,i=e,r.retryEnabled&&!(i>=3)&&k.includes(t)&&_.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):v(e);await l.text(),e++,await E(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 S({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 S(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}},A=class extends T{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 R=RegExp("[,()]");var O=class extends A{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&&R.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&&R.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,C=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 O({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 O({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 O({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 O({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 O({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 j(e){return(j="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 P(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 I(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?P(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=j(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=j(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==j(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)):P(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var x=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 C(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 O({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;let 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,I(I({},t),{},{signal:r.signal})).finally(()=>{clearTimeout(s),i.removeEventListener("abort",n)})}return o(e,I(I({},t),{},{signal:r.signal})).finally(()=>clearTimeout(s))}:this.fetch=o,this.retry=a}};let N=class{static detectEnvironment(){var t;if("undefined"!=typeof WebSocket)return{type:"native",wsConstructor:WebSocket};let r=globalThis;if("undefined"!=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("undefined"!=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("undefined"!=typeof globalThis&&r.EdgeRuntime||"undefined"!=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}}constructor(){}},U="realtime-js/".concat("2.107.0"),L="2.0.0",D={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},B={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},q={connecting:"connecting",closing:"closing",closed:"closed"};class H{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:[]}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(a||(a={}));let M=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]=W(s,e,t,n),r),{}):{}},W=(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)?K(i,a):J(a)},K=(e,t)=>{if("_"===e.charAt(0))return V(t,e.slice(1,e.length));switch(e){case a.bool:return F(t);case a.float4:case a.float8:case a.int2:case a.int4:case a.int8:case a.numeric:case a.oid:return z(t);case a.json:case a.jsonb:return G(t);case a.timestamp:return Y(t);case a.abstime:case a.date:case a.daterange:case a.int4range:case a.int8range:case a.money:case a.reltime:case a.text:case a.time:case a.timestamptz:case a.timetz:case a.tsrange:case a.tstzrange:default:return J(t)}},J=e=>e,F=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},z=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},G=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){}return e},V=(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=>K(t,e))}return e},Y=e=>"string"==typeof e?e.replace(" ","T"):e,$=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 X=e=>"function"==typeof e?e:function(){return e},Q="undefined"!=typeof window?window:null,Z=("undefined"!=typeof self?self:null)||Q||globalThis,ee={connecting:0,open:1,closing:2,closed:3},et={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},er={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},es={longpoll:"longpoll",websocket:"websocket"},en={complete:4},ei="base64url.bearer.phx.",ea=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}},eo=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}},el=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=et.closed,this.bindings=[]}onClose(e){this.on(er.close,e)}onError(e){return this.on(er.error,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 ea(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=et.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel","leave ".concat(this.topic)),this.trigger(er.close,"leave")},r=new ea(this,er.leave,X({}),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=et.joining,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===et.closed}isErrored(){return this.state===et.errored}isJoined(){return this.state===et.joined}isJoining(){return this.state===et.joining}isLeaving(){return this.state===et.leaving}constructor(e,t,r){this.state=et.closed,this.topic=e,this.params=X(t||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new ea(this,er.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new eo(()=>{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=et.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e
1=>e.send()),this.pushBuffer=[]}),this.joinPush.receive("error",e=>{this.state=et.errored,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=et.closed,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=et.errored,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 ea(this,er.leave,X({}),this.timeout).send(),this.state=et.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(er.reply,(e,t)=>{this.trigger(this.replyEventName(t),e)})}},ec=class{static request(e,t,r,s,n,i,a){if(Z.XDomainRequest){let r=new Z.XDomainRequest;return this.xdomainRequest(r,e,t,s,n,i,a)}if(Z.XMLHttpRequest){let o=new Z.XMLHttpRequest;return this.xhrRequest(o,e,t,r,s,n,i,a)}if(Z.fetch&&Z.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),Z.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=()=>{e.readyState===en.complete&&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))}},eh=class{normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(RegExp("(.*)/"+es.websocket),"$1/"+es.longpoll)}endpointURL(){return ec.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=ee.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===ee.open||this.readyState===ee.connecting}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=ee.open,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=ee.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,"undefined"!=typeof CloseEvent?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,r,s,n){let i,a=()=>{this.reqs.delete(i),s()};i=ec.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(ei)&&(this.authToken=atob(t[1].slice(ei.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=ee.connecting,setTimeout(()=>this.poll(),0)}},eu=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())})}},ed={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));o+=a;let d=e.slice(o,e.byteLength);return{join_ref:l,ref:c,topic:h,event:er.reply,payload:{status:u,response:d}}},decodeBroadcast(e,t,r){let s=t.getUint8(1),n=t.getUint8(2),i=this.HEADER_LENGTH+2,a=r.decode(e.slice(i,i+s));i+=s;let o=r.decode(e.slice(i,i+n));return i+=n,{join_ref:null,ref:null,topic:a,event:o,payload:e.slice(i,e.byteLength)}}},ep=class{getLongPollTransport(){return eh}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=ec.appendParams(ec.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=X(e)),(!this.conn||this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==eh?this.connectWithF
1allback(eh,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===eh?"LongPoll":e.name}transportConnect(){let e;this.connectClock++,this.closeWasClean=!1,this.authToken&&(e=["phoenix","".concat(ei).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;if(5===r||!e.bufferedAmount)return void t();setTimeout(()=>{this.waitForBufferDone(e,t,r+1)},150*r)}waitForSocketClosed(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;if(5===r||e.readyState===ee.closed)return void 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(er.error,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case ee.connecting:return"connecting";case ee.open:return"open";case ee.closing: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 el(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||Z.WebSocket||eh,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let n=null;try{n=Z&&Z.sessionStorage}catch(e){}this.sessionStore=t.sessionStorage||n,this.establishedConnections=0,this.defaultEncoder=ed.encode.bind(ed),this.defaultDecoder=ed.decode.bind(ed),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!==eh?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let i=null;Q&&Q.addEventListener&&(Q.addEventListener("pagehide",e=>{this.conn&&(this.disconnect(),i=this.connectClock)}),Q.addEventListener("pageshow",e=>{i===this.connectClock&&(i=null,this.connect())}),Q.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=X(t.params||{}),this.endPoint="".concat(e,"/").concat(es.websocket),this.vsn=t.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new eo(()=>
1{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 ef{get state(){return ef.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]=eg(s),t},{})}static onJoinPayload(e,t,r){return{event:"join",key:e,currentPresences:em(t),newPresences:eg(r)}}static onLeavePayload(e,t,r){return{event:"leave",key:e,currentPresences:em(t),leftPresences:eg(r)}}constructor(e,t){let r=function(e){return(null==e?void 0:e.events)&&{events:e.events}}(t);this.presence=new eu(e.getChannel(),r),this.presence.onJoin((t,r,s)=>{let n=ef.onJoinPayload(t,r,s);e.getChannel().trigger("presence",n)}),this.presence.onLeave((t,r,s)=>{let n=ef.onLeavePayload(t,r,s);e.getChannel().trigger("presence",n)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}}function eg(e){return e.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function em(e){return(null==e?void 0:e.metas)?eg(e):[]}!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(o||(o={}));class ey{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new ef(this.channel.channelAdapter,t)}}class ew{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===D.joined}isJoined(){return this.state===D.joined}isJoining(){return this.state===D.joining}isClosed(){return this.state===D.closed}isLeaving(){return this.state===D.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}constructor(e,t,r){let s={config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config)};this.channel=e.getSocket().channel(t,s),this.socket=e}}!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(l||(l={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(c||(c={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(h||(h={}));class eb{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:[],u=!!this.bindings[c.PRESENCE]&&this.bindings[c.PRESENCE].length>0||(null==(s=this.params.config.presence)?void 0:s.enabled)===!0,d={},p={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:l,private:o};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(t=>{null==e||e(h.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(h.CLOSED)),this.updateJoinPayload(Object.assign({config:p},d)),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(h.SUBSCRIBED);return}this._updatePostgresBindings(r,e)}).receive("error",t=>{this.state=D.errored;let r=Object.values(t).join(", ")||"error";null==e||e(h.CHANNEL_ERROR,Error(r,{cause:t}))}).receive("timeout",()=>{null==e||e(h.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,u=e&&e[r];if(u&&u.event===a&&eb.isFilterValueEqual(u.schema,o)&&eb.isFilterValueEqual(u.table,l)&&eb.isFilterValueEqual(u.filter,c))i.push(Object.assign(Object.assign({},n),{id:u.id}));else{this.unsubscribe(),this.state=D.errored,null==t||t(h.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=D.errored&&t&&t(h.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===c.PRESENCE||e===c.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}=B;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=M(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=M(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 ew(this.socket.socketAdapter,e,this.params),this.presence=new ey(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=$(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 ev{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 this.socket.connectionState()==q.connecting}isDisconnecting(){return this.socket.connectionState()==q.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}constructor(e,t){this.socket=new ep(e,t)}}let e_={HEARTBEAT_INTERVAL:25e3},ek=[1e3,2e3,5e3,1e4];class eS{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()||q.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 eb("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:U};e&&t.updateJoinPayload(r),t.joinedOnce&&t.channelAdapter.isJoined()&&t.channelAdapter.push(B.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:e_.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=null!=(i=null==e?void 0:e.disconnectOnEmptyChannelsAfterMs)?i:2*(null!=(a=null==e?void 0:e.heartbeatIntervalMs)?a:e_.HEARTBEAT_INTERVAL),g.transport=null!=(o=null==e?void 0:e.transport)?o:N.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(){try{if("undefined"!=typeof globalThis&&globalThis.sessionStorage)return globalThis.sessionStorage}catch(e){}let e=new Map;return{get length(){return e.size},clear(){e.clear()},getItem:t=>e.has(t)?e.get(t):null,key(t){var r;return null!=(r=Array.from(e.keys())[t])?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=>ek[e-1]||1e4;let m=null!=(h=null==e?void 0:e.vsn)?h:L;switch(m){case"1.0.0":p=(e,t)=>t(JSON.stringify(e)),f=(e,t)=>t(JSON.parse(e));break;case L: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("undefined"!=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={}
1,this.ref=0,this.serializer=new H,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;let s=this._initializeOptions(t);this.socketAdapter=new ev(e,s),this.httpEndpoint=$(e),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}}var eE=e.i(467034),eT=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 eA(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 eR(e){return e.join("\x1f")}var eO=class{async listNamespaces(e){let t=e?{parent:eR(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(eR(e.namespace))})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces/").concat(eR(e.namespace))})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:"".concat(this.prefix,"/namespaces/").concat(eR(e.namespace))}),!0}catch(e){if(e instanceof eT&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof eT&&409===e.status)return;throw e}}constructor(e,t=""){this.client=e,this.prefix=t}};function eC(e){return e.join("\x1f")}var ej=class{async listTables(e){return(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces/").concat(eC(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(eC(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(eC(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(eC(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(eC(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(eC(e.namespace),"/tables/").concat(e.name),headers:t}),!0}catch(e){if(e instanceof eT&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof eT&&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}},eP=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));let 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 eA(e.auth),h=await r(l,{method:s,headers:{...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 eT(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 eO(this.client,r),this.tableOps=new ej(this.client,r,this.accessDelegation)}};function eI(e){return(eI="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 ex(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 eN(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ex(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=eI(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=eI(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==eI(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)):ex(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var eU=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 eL(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var eD=class extends eU{toJSON(){return eN({},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}},eB=class extends eU{constructor(e,t,r="storage"){super(e,r),this.name="vectors"===r?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};function eq(e,t,r){let s=eN({},e),n=t.toLowerCase();for(let e of Object.keys(s))e.toLowerCase()===n&&delete s[e];return s[n]=r,s}let eH=e=>{if(Array.isArray(e))return e.map(e=>eH(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,""))]=eH(s)}),t},eM=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)},eW=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 eD(eM(e),r,n,s))}).catch(()=>{let n=r+"";t(new eD(e.statusText||"HTTP ".concat(r," error"),r,n,s))})}else t(new eB(eM(e),e,s))};async function eK(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 eN(eN({},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=eq(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),eN(eN({},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=>eW(e,l,s,a))})}function eJ(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"storage";return{get:async(t,r,s,n)=>eK(t,"GET",r,s,n,void 0,e),post:async(t,r,s,n,i)=>eK(t,"POST",r,n,i,s,e),put:async(t,r,s,n,i)=>eK(t,"PUT",r,n,i,s,e),head:async(t,r,s,n)=>eK(t,"HEAD",r,eN(eN({},s),{},{noResolveJson:!0}),n,void 0,e),remove:async(t,r,s,n,i)=>eK(t,"DELETE",r,n,i,s,e)}}let{get:eF,post:ez,put:eG,head:eV,remove:eY}=eJ("storage"),e$=eJ("vectors");var eX=class{throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=eq(this.headers,e,t),this}async handleOperation(e){try{return{data:await e(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eL(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 eQ=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(eL(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 eZ=class{asStream(){return new eQ(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(eL(e))return{data:null,error:e};throw e}}constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[r]="BlobDownloadBuilder",this.promise=null}};let e0={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},e1={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var e2=class extends eX{async uploadOrUpdate(e,t,r,s){var n=this;return n.handleOperation(async()=>{let i,a=eN(eN({},e1),s),o=eN(eN({},n.headers),"POST"===e&&{"x-upsert":String(a.upsert)}),l=a.metadata;if("undefined"!=typeof Blob&&r instanceof Blob?((i=new FormData).append("cacheControl",a.cacheControl),l&&i.append("metadata",n.encodeMetadata(l)),i.append("",r)):"undefined"!=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))),("undefined"!=typeof ReadableStream&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!a.duplex&&(a.duplex="half")),null==s?void 0:s.headers)for(let[e,t]of Object.entries(s.headers))o=eq(o,e,t);let c=n._removeEmptyFolders(t),h=n._getFinalPath(c),u=await ("PUT"==e?eG:ez)(n.fetch,"".concat(n.url,"/object/").concat(h),i,eN({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=eN(eN({},e1),s),a=eN(eN({},n.headers),{"x-upsert":String(t.upsert)}),l=t.metadata;if("undefined"!=typeof Blob&&r instanceof Blob?((e=new FormData).append("cacheControl",t.cacheControl),l&&e.append("metadata",n.encodeMetadata(l)),e.append("",r)):"undefined"!=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))),("undefined"!=typeof ReadableStream&&e instanceof ReadableStream||e&&"object"==typeof e&&"pipe"in e&&"function"==typeof e.pipe)&&!t.duplex&&(t.duplex="half")),null==s?void 0:s.headers)for(let[e,t]of Object.entries(s.headers))a=eq(a,e,t);return{path:i,fullPath:(await eG(n.fetch,o.toString(),e,eN({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=eN({},r.headers);(null==t?void 0:t.upsert)&&(n["x-upsert"]="true");let i=await ez(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 eU("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 ez(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 ez(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 ez(s.fetch,"".concat(s.url,"/object/sign/").concat(n),eN({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 ez(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=>eN(eN({},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 eZ(()=>eF(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()=>eH(await eF(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 eV(this.fetch,"".concat(this.url,"/object/").concat(r),{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eL(e)){let r=e instanceof eD?e.status:e instanceof eB?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 eY(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=eN(eN(eN({},e0),t),{},{prefix:e||""});return await ez(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=eN({},e);return await ez(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!==eE.Buffer?eE.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 e8={"X-Client-Info":"storage-js/".concat("2.107.0")};var e5=class extends eX{async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=t.listBucketOptionsToQueryString(e);return await eF(t.fetch,"".concat(t.url,"/bucket").concat(r),{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await eF(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 ez(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 eG(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 ez(t.fetch,"".concat(t.url,"/bucket/").concat(e,"/empty"),{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await eY(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){let 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(/\/$/,""),eN(eN({},e8),t),r,"storage")}},e3=class extends eX{async createBucket(e){var t=this;return t.handleOperation(async()=>await ez(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 eF(t.fetch,n,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await eY(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 eU("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 eP({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(/\/$/,""),eN(eN({},e8),t),r,"storage")}},e4=class extends eX{async createIndex(e){var t=this;return t.handleOperation(async()=>await e$.post(t.fetch,"".concat(t.url,"/CreateIndex"),e,{headers:t.headers})||{})}async getIndex(e,t){var r=this;return r.handleOperation(async()=>await e$.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 e$.post(t.fetch,"".concat(t.url,"/ListIndexes"),e,{headers:t.headers}))}async deleteIndex(e,t){var r=this;return r.handleOperation(async()=>await e$.post(r.fetch,"".concat(r.url,"/DeleteIndex"),{vectorBucketName:e,indexName:t},{headers:r.headers})||{})}constructor(e,t={},r){super(e.replace(/\/$/,""),eN(eN({},e8),{},{"Content-Type":"application/json"},t),r,"vectors")}},e6=class extends eX{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 e$.post(t.fetch,"".concat(t.url,"/PutVectors"),e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await e$.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 e$.post(t.fetch,"".concat(t.url,"/ListVectors"),e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await e$.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 e$.post(t.fetch,"".concat(t.url,"/DeleteVectors"),e,{headers:t.headers})||{})}constructor(e,t={},r){super(e.replace(/\/$/,""),eN(eN({},e8),{},{"Content-Type":"application/json"},t),r,"vectors")}},e9=class extends eX{async createBucket(e){var t=this;return t.handleOperation(async()=>await e$.post(t.fetch,"".concat(t.url,"/CreateVectorBucket"),{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await e$.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 e$.post(t.fetch,"".concat(t.url,"/ListVectorBuckets"),e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await e$.post(t.fetch,"".concat(t.url,"/DeleteVectorBucket"),{vectorBucketName:e},{headers:t.headers})||{})}constructor(e,t={},r){super(e.replace(/\/$/,""),eN(eN({},e8),{},{"Content-Type":"application/json"},t),r,"vectors")}},e7=class extends e9{from(e){return new te(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)}},te=class extends e4{async createIndex(e){return super.createIndex.call(this,eN(eN({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.listIndexes.call(this,eN(eN({},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 tt(this.url,this.headers,this.vectorBucketName,e,this.fetch)}constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}},tt=class extends e6{async putVectors(e){return super.putVectors.call(this,eN(eN({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async getVectors(e){return super.getVectors.call(this,eN(eN({},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,eN(eN({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async queryVectors(e){return super.queryVectors.call(this,eN(eN({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async deleteVectors(e){return super.deleteVectors.call(this,eN(eN({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}constructor(e,t,r,s,n){super(e,t,n),this.vectorBucketName=r,this.indexName=s}},tr=class extends e5{from(e){return new e2(this.url,this.headers,e,this.fetch)}get vectors(){return new e7(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new e3(this.url+"/iceberg",this.headers,this.fetch)}constructor(e,t={},r,s){super(e,t,r,s)}};let ts="2.107.0",tn="X-Supabase-Api-Version",ti={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},ta=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class to 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 tl(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class tc extends to{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class th extends to{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class tu extends to{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class td extends tu{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function tp(e){return tl(e)&&"AuthSessionMissingError"===e.name}class tf extends tu{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class tg extends tu{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class tm extends tu{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 ty extends tu{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 tw extends tu{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 tb extends tu{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function tv(e){return tl(e)&&"AuthRetryableFetchError"===e.name}class t_ extends tu{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}}class tk extends tu{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 tS extends tu{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}let tE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),tT=" 	\n\r=".split(""),tA=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<tT.length;t+=1)e[tT[t].charCodeAt(0)]=-2;for(let t=0;t<tE.length;t+=1)e[tE[t].charCodeAt(0)]=t;return e})();function tR(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;)r(tE[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(tE[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function tO(e,t,r){let s=tA[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 tC(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)tO(e.charCodeAt(t),n,i);return t.join("")}function tj(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)tO(e.charCodeAt(t),r,s);return new Uint8Array(t)}function tP(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>tR(e,r,s)),tR(null,r,s),t.join("")}let tI=()=>"undefined"!=typeof window&&"undefined"!=typeof document,tx={tested:!1,writable:!1},tN=()=>{if(!tI())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(tx.tested)return tx.writable;let e="lswt-".concat(Math.random()).concat(Math.random());try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),tx.tested=!0,tx.writable=!0}catch(e){tx.tested=!0,tx.writable=!1}return tx.writable},tU=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)},tL=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},tD=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return null}},tB=async(e,t)=>{await e.removeItem(t)};class tq{constructor(){this.promise=new tq.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function tH(e){let t=e.split(".");if(3!==t.length)throw new tS("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!ta.test(t[e]))throw new tS("JWT not in base64url format");return{header:JSON.parse(tC(t[0])),payload:JSON.parse(tC(t[1])),signature:tj(t[2]),raw:{header:t[0],payload:t[1]}}}async function tM(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function tW(e){return("0"+e.toString(16)).substr(-2)}async function tK(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 tJ(e){return"undefined"==typeof crypto||void 0===crypto.subtle||"undefined"==typeof TextEncoder?(console.warn("WebCrypto API is not supported. Code 
1challenge method will default to use plain instead of sha256."),e):btoa(await tK(e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function tF(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=function(){let e=new Uint32Array(56);if("undefined"==typeof crypto){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length,r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,tW).join("")}(),n=s;r&&(n+="/recovery"),await tL(e,"".concat(t,"-code-verifier"),n);let i=await tJ(s),a=s===i?"plain":"s256";return[i,a]}tq.promiseConstructor=Promise;let tz=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i,tG=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function tV(e){if(!tG.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function tY(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 t$(){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 tX(e){return JSON.parse(JSON.stringify(e))}let tQ=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)},tZ=[502,503,504,520,521,522,523,524,530];async function t0(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 tb(tQ(e),0);if(tZ.includes(e.status))throw new tb(tQ(e),e.status);try{r=await e.json()}catch(e){throw new th(tQ(e),e)}let n=function(e){let t=e.headers.get(tn);if(!t||!t.match(tz))return null;try{return new Date("".concat(t,"T00:00:00.0Z"))}catch(e){return null}}(e);if(n&&n.getTime()>=ti["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 tk(tQ(r),e.status,(null==(t=r.weak_password)?void 0:t.reasons)||[]);else if("session_not_found"===s)throw new td}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 tk(tQ(r),e.status,r.weak_password.reasons);throw new tc(tQ(r),e.status||500,s)}async function t1(e,t,r,s){var n;let i=Object.assign({},null==s?void 0:s.headers);i[tn]||(i[tn]=ti["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 t2(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 t2(e,t,r,s,n,i){let a,o=((e,t,r,s)=>{let n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))})(t,s,n,i);try{a=await e(r,Object.assign({},o))}catch(e){throw console.error(e),new tb(tQ(e),0)}if(a.ok||await t0(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await t0(e)}}function t8(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 t5(e){let t=t8(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)=>
1e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function t3(e){var t;return{data:{user:null!=(t=e.user)?t:e},error:null}}function t4(e){return{data:e,error:null}}function t6(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({},w(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]))},error:null}}function t9(e){return e}let t7=["global","local","others"];class re{async signOut(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t7[0];if(0>t7.indexOf(t))throw Error("@supabase/auth-js: Parameter scope must be one of ".concat(t7.join(", ")));try{return await t1(this.fetch,"POST","".concat(this.url,"/logout?scope=").concat(t),{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tl(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 t1(this.fetch,"POST","".concat(this.url,"/invite"),{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:t3})}catch(e){if(tl(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,r=w(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 t1(this.fetch,"POST","".concat(this.url,"/admin/generate_link"),{body:s,headers:this.headers,xform:t6,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(tl(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await t1(this.fetch,"POST","".concat(this.url,"/admin/users"),{body:e,headers:this.headers,xform:t3})}catch(e){if(tl(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 t1(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:t9});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(tl(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){tV(e);try{return await t1(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(e),{headers:this.headers,xform:t3})}catch(e){if(tl(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){tV(e);try{return await t1(this.fetch,"PUT","".concat(this.url,"/admin/users/").concat(e),{body:t,headers:this.headers,xform:t3})}catch(e){if(tl(e))return{data:{user:null},error:e};throw e}}async deleteUser(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];tV(e);try{return await t1(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(e),{headers:this.headers,body:{should_soft_delete:t},xform:t3})}catch(e){if(tl(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){tV(e.userId);try{let{data:t,error:r}=await t1(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(tl(e))return{data:null,error:e};throw e}}async _deleteFactor(e){tV(e.userId),tV(e.id);try{return{data:await t1(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(e.userId,"/factors/").concat(e.id),{headers:this.headers}),error:null}}catch(e){if(tl(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 t1(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:t9});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>
10&&(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(tl(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await t1(this.fetch,"POST","".concat(this.url,"/admin/oauth/clients"),{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tl(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await t1(this.fetch,"GET","".concat(this.url,"/admin/oauth/clients/").concat(e),{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tl(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await t1(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(tl(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await t1(this.fetch,"DELETE","".concat(this.url,"/admin/oauth/clients/").concat(e),{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tl(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await t1(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(tl(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 t1(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(tl(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await t1(this.fetch,"POST","".concat(this.url,"/admin/custom-providers"),{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tl(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await t1(this.fetch,"GET","".concat(this.url,"/admin/custom-providers/").concat(e),{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tl(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await t1(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(tl(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await t1(this.fetch,"DELETE","".concat(this.url,"/admin/custom-providers/").concat(e),{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tl(e))return{data:null,error:e};throw e}}async _adminListPasskeys(e){tY(this.experimental),tV(e.userId);try{return await t1(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(e.userId,"/passkeys"),{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tl(e))return{data:null,error:e};throw e}}async _adminDeletePasskey(e){tY(this.experimental),tV(e.userId),tV(e.passkeyId);try{return await t1(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(tl(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=tU(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 rt(){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&&tN()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");
1class rr extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}function rs(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error('@supabase/auth-js: Address "'.concat(e,'" is invalid.'));return e.toLowerCase()}class rn 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 ri extends rn{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}let ra=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 ro(e){if(!e)throw Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:r,excludeCredentials:s}=e,n=w(e,["challenge","user","excludeCredentials"]),i=tj(t).buffer,a=Object.assign(Object.assign({},r),{id:tj(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:tj(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function rl(e){if(!e)throw Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:r}=e,s=w(e,["challenge","allowCredentials"]),n=tj(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:tj(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return i}function rc(e){var t;return"toJSON"in e&&"function"==typeof e.toJSON?e.toJSON():{id:e.id,rawId:e.id,response:{attestationObject:tP(new Uint8Array(e.response.attestationObject)),clientDataJSON:tP(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!=(t=e.authenticatorAttachment)?t:void 0}}function rh(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:tP(new Uint8Array(s.authenticatorData)),clientDataJSON:tP(new Uint8Array(s.clientDataJSON)),signature:tP(new Uint8Array(s.signature)),userHandle:s.userHandle?tP(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!=(t=e.authenticatorAttachment)?t:void 0}}function ru(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function rd(){var e,t;return!!(tI()&&"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 rp(e){try{let t=await navigator.credentials.create(e);if(!t)return{data:null,error:new ri("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new ri("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 rn({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 rn({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 rn({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 rn({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 rn({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});else if("NotAllowedError"===n.name)return new rn({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});else if("NotSupportedError"===n.name)return new rn(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(!ru(e))return new rn({message:"".concat(window.location.hostname," is an invali
1d domain"),code:"ERROR_INVALID_DOMAIN",cause:n});if(a.rp.id!==e)return new rn({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 rn({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 rn({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 rn({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}({error:t,options:e})}}}async function rf(e){try{let t=await navigator.credentials.get(e);if(!t)return{data:null,error:new ri("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new ri("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 rn({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if("NotAllowedError"===t.name)return new rn({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});else if("SecurityError"===t.name){let e=window.location.hostname;if(!ru(e))return new rn({message:"".concat(window.location.hostname," is an invalid domain"),code:"ERROR_INVALID_DOMAIN",cause:t});if(s.rpId!==e)return new rn({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 rn({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 rn({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}({error:t,options:e})}}}let rg={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},rm={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function ry(){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]=ry(e,r):i[t]=ry(r)}else i[t]=r}return i}class rw{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:ra.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,ry(rg,s,n||{})),{data:i,error:a}=await rp({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,ry(rm,i,a||{})),{data:s,error:n}=await rf(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(tl(e))return{data:null,error:e};return{data:null,error:new th("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="undefined"!=typeof window?window.location.hostname:void 0,rpOrigins:n="undefined"!=typeof window?[window.location.origin]:void 0,signal:i}={}}=e;if(!s)return{data:null,error:new to("rpId is required for WebAuthn authentication")};try{if(!rd())return{data:null,error:new th("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(tl(e))return{data:null,error:e};return{data:null,error:new th("Unexpected error in authenticate",e)}}}async _register(e,t){let{friendlyName:r,webauthn:{rpId:s="undefined"!=typeof window?window.location.hostname:void 0,rpOrigins:n="undefined"!=typeof window?[window.location.origin]:void 0,signal:i}={}}=e;if(!s)return{data:null,error:new to("rpId is required for WebAuthn registration")};try{if(!rd())return{data:null,error:new th("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(tl(e))return{data:null,error:e};return{data:null,error:new th("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){"undefined"!=typeof self&&(self.globalThis=self)}let rb={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:{"X-Client-Info":"gotrue-js/".concat(ts)},flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},rv={};class r_{get jwks(){var e,t;return null!=(t=null==(e=rv[this.storageKey])?void 0:e.jwks)?t:{keys:[]}}set jwks(e){rv[this.storageKey]=Object.assign(Object.assign({},rv[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!=(t=null==(e=rv[this.storageKey])?void 0:e.cachedAt)?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){rv[this.storageKey]=Object.assign(Object.assign({},rv[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(ts,") ").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(tI()&&(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")),tI()&&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),tl(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(tl(e))return this._returnResult({error:e});return this._returnResult({error:new th("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 t1(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:t8});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(tl(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 tF(this.storage,this.storageKey)),n=await t1(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:t8})}else if("phone"in e){let{phone:t,password:i,options:a}=e;n=await t1(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:t8})}else throw new tg("You must provide either an email or phone number and a password");let{data:i,error:a}=n;if(a||!i)return await tB(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 tB(this.storage,"".concat(this.storageKey,"-code-verifier")),tl(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 t1(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:t5})}else if("phone"in e){let{phone:r,password:s,options:n}=e;t=await t1(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:t5})}else throw new tg("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 tf;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(tl(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(tI())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=rs(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=rs(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 t1(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:t8});if(r)throw r;if(!t||!t.session||!t.user){let e=new tf;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(tl(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(tI())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 t1(this.fetch,"POST","".concat(this.url,"/token?grant_type=web3"),{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:tP(f)},(null==(u=e.options)?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null==(d=e.options)?void 0:d.captchaToken}}:null),xform:t8});if(r)throw r;if(!t||!t.session||!t.user){let e=new tf;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(tl(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let t=await tD(this.storage,"".concat(this.storageKey,"-code-verifier")),[r,s]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new tw;let{data:t,error:n}=await t1(this.fetch,"POST","".concat(this.url,"/token?grant_type=pkce"),{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:t8});if(await tB(this.storage,"".concat(this.storageKey,"-code-verifier")),n)throw n;if(!t||!t.session||!t.user){let e=new tf;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 tB(this.storage,"".concat(this.storageKey,"-code-verifier")),tl(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 t1(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:t8});if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!a||!a.session||!a.user){let e=new tf;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(tl(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 tF(this.storage,this.storageKey));let{error:o}=await t1(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 t1(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 tg("You must provide either an email or phone number.")}catch(e){if(await tB(this.storage,"".concat(this.storageKey,"-code-verifier")),tl(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 t1(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:t8});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(tl(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 tF(this.storage,this.storageKey));let l=await t1(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:t4});return(null==(n=l.data)?void 0:n.url)&&tI()&&!(null==(i=e.options)?void 0:i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await tB(this.storage,"".concat(this.storageKey,"-code-verifier")),tl(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 td;let{error:s}=await t1(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(tl(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,{error:i}=await t1(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},redirectTo:null==n?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}if("phone"in e){let{phone:r,type:s,options:n}=e,{data:i,error:a}=await t1(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 tg("You must provide either an email or phone number and a type")}catch(e){if(tl(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 tD(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 val
1id"),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 tD(this.userStorage,this.storageKey+"-user");(null==e?void 0:e.user)?t.user=e.user:t.user=t$()}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;if("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 t1(this.fetch,"GET","".concat(this.url,"/user"),{headers:this.headers,jwt:e,xform:t3});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 t1(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:t3}):{data:{user:null},error:new td}})}catch(e){if(tl(e))return tp(e)&&(await this._removeSession(),await tB(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 td;let i=s.session,a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await tF(this.storage,this.storageKey));let{data:l,error:c}=await t1(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:t3});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 tB(this.storage,"".concat(this.storageKey,"-code-verifier")),tl(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 td;let t=Date.now()/1e3,r=t,s=!0,n=null,{payload:i}=tH(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(tl(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 td;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(tl(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){var r;try{if(!tI())throw new tm("No browser detected.");
1if(e.error||e.error_description||e.error_code)throw new tm(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 ty("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new tm("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new ty("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 tm("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(tl(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 tD(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&&!tp(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&&!(tl(t)&&"AuthApiError"===t.name&&(404===t.status||401===t.status||403===t.status)||tp(t)))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await tB(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),tp(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 tF(this.storage,this.storageKey,!0));try{return await t1(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 tB(this.storage,"".concat(this.storageKey,"-code-verifier")),tl(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(tl(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 t1(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!tI()||(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(tl(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 t1(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:t8});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 tf});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 tB(this.storage,"".concat(this.storageKey,"-code-verifier")),tl(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 t1(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(tl(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 tM(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await t1(this.fetch,"POST","".concat(this.url,"/token?grant_type=refresh_token"),{body:{refresh_token:e},headers:this.headers,xform:t8})),s=(e,t)=>{let r=200*Math.pow(2,e);return t&&tv(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),tl(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),tI()&&!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 tD(this.storage,this.storageKey);if(s&&this.userStorage){let t=await tD(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!t&&(t={user:s.user},await tL(this.userStorage,this.storageKey+"-user",t)),s.user=null!=(e=null==t?void 0:t.user)?e:t$()}else if(s&&!s.user&&!s.user){let e=await tD(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await tB(this.storage,this.storageKey+"-user"),await tL(this.storage,this.storageKey,s)):s.user=t$()}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&&(tl(e)&&"AuthRefreshDiscardedError"===e.name?this._debug(r,"refresh discarded by commit guard",e):(console.error(e),tv(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 td;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s="#_callRefreshToken()";this._debug(s,"begin");try{this.refreshingDeferred=new tq;let t=await tD(this.storage,this.storageKey),{data:r,error:n}=await this._refreshAccessToken(e);if(n)throw n;if(!r.session)throw new td;let i=await tD(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 t_};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 tB(this.storage,this.storageKey),this.userStorage&&await tB(this.userStorage,this.storageKey+"-user");let e={data:null,error:new t_};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),tl(e)){let r={data:null,error:e};return tv(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 tB(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 tL(this.userStorage,this.storageKey+"-user",{user:t.user});let e=Object.assign({},t);delete e.user;let s=tX(e);await tL(this.storage,this.storageKey,s)}else{let e=tX(t);await tL(this.storage,this.storageKey,e)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await tB(this.storage,this.storageKey),await tB(this.storage,this.storageKey+"-code-verifier"),await tB(this.storage,this.storageKey+"-user"),this.userStorage&&await tB(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&tI()&&(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():"undefined"!=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():"undefined"!=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 rr)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()"),!tI()||!(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()=>
1{if("visible"!==document.visibilityState)return void 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 tF(this.storage,this.storageKey),r=new URLSearchParams({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 t1(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(tl(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 t1(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(tl(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?rc(e.webauthn.credential_response):rh(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await t1(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(tl(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 t1(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:ro(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:rl(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(tl(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}=tH(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(tl(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}=tH(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 t1(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 td})})}catch(e){if(tl(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 td});let i=await t1(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&&tI()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(tl(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 td});let i=await t1(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&&tI()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(tl(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 t1(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 td})})}catch(e){if(tl(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 t1(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 td})})}catch(e){if(tl(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 t1(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 s=e;if(!s){let{data:e,error:t}
1=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});s=e.session.access_token}let{header:n,payload:i,signature:a,raw:{header:o,payload:l}}=tH(s);if(!(null==t?void 0:t.allowExpired))try{var r=i.exp;if(!r)throw Error("Missing exp claim");if(r<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}catch(e){throw new tS(e instanceof Error?e.message:"JWT validation failed")}let c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks);if(!c){let{error:e}=await this.getUser(s);if(e)throw e;return{data:{claims:i,header:n,signature:a},error:null}}let h=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw Error("Invalid alg claim")}}(n.alg),u=await crypto.subtle.importKey("jwk",c,h,!0,["verify"]);if(!await crypto.subtle.verify(h,u,a,function(e){let t=[];return!function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127)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)}}(e,e=>t.push(e)),new Uint8Array(t)}("".concat(o,".").concat(l))))throw new tS("Invalid JWT signature");return{data:{claims:i,header:n,signature:a},error:null}}catch(e){if(tl(e))return this._returnResult({data:null,error:e});throw e}}async signInWithPasskey(e){var t,r,s;tY(this.experimental);try{if(!rd())return this._returnResult({data:null,error:new th("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=rl(n.options),o=null!=(s=null==(r=null==e?void 0:e.options)?void 0:r.signal)?s:ra.createNewAbortSignal(),{data:l,error:c}=await rf({publicKey:a,signal:o});if(c||!l)return this._returnResult({data:null,error:null!=c?c:new th("WebAuthn ceremony failed",null)});let h=rh(l);return this._verifyPasskeyAuthentication({challengeId:n.challenge_id,credential:h})}catch(e){if(tl(e))return this._returnResult({data:null,error:e});throw e}}async registerPasskey(e){var t,r;tY(this.experimental);try{if(!rd())return this._returnResult({data:null,error:new th("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=ro(s.options),a=null!=(r=null==(t=null==e?void 0:e.options)?void 0:t.signal)?r:ra.createNewAbortSignal(),{data:o,error:l}=await rp({publicKey:i,signal:a});if(l||!o)return this._returnResult({data:null,error:null!=l?l:new th("WebAuthn ceremony failed",null)});let c=rc(o);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:c})}catch(e){if(tl(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyRegistration(){tY(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 td});let{data:s,error:n}=await t1(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(tl(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){tY(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 td});let{data:n,error:i}=await t1(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(tl(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyAuthentication(e){var t;tY(this.experimental);try{let{data:r,error:s}=await t1(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(tl(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyAuthentication(e){tY(this.experimental);try{let{data:t,error:r}=await t1(this.fetch,"POST","".concat(this.url,"/passkeys/authentication/verify"),{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:t8});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(tl(e))return this._returnResult({data:null,error:e});throw e}}async _listPasskeys(){tY(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 td});let{data:s,error:n}=await t1(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(tl(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){tY(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 td});let{data:n,error:i}=await t1(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(tl(e))return this._returnResult({data:null,error:e});throw e}}async _deletePasskey(e){tY(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 td});let{error:n}
1=await t1(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(tl(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;let n=Object.assign(Object.assign({},rb),e);if(this.storageKey=n.storageKey,this.instanceID=null!=(t=r_.nextInstanceID[this.storageKey])?t:0,r_.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!n.debug,"function"==typeof n.debug&&(this.logger=n.debug),this.instanceID>0&&tI()){let 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 re({url:n.url,headers:n.headers,fetch:n.fetch,experimental:this.experimental}),this.url=n.url,this.headers=n.headers,this.fetch=tU(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 rw(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:tN()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=rt(this.memoryStorage)),n.userStorage&&(this.userStorage=n.userStorage)):(this.memoryStorage={},this.storage=rt(this.memoryStorage)),tI()&&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)})}}r_.nextInstanceID={};let rk=r_,rS="";"undefined"!=typeof Deno?(rS="deno",s=null==(u=Deno.version)?void 0:u.deno):"undefined"!=typeof document?rS="web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?rS="react-native":(rS="node",s=void 0!==p.default?null==(d=p.default.version)?void 0:d.replace(/^v/,""):void 0);let rE=["runtime=".concat(rS)];s&&rE.push("runtime-version=".concat(s));let rT={headers:{"X-Client-Info":"supabase-js/".concat("2.107.0","; ").concat(rE.join("; "))}},rA={schema:"public"},rR={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},rO={},rC={enabled:!1,respectSamplingDecision:!0},rj=null;function rP(e){return(rP="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 rI(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 rx(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};
1t%2?rI(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=rP(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=rP(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==rP(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)):rI(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}async function rN(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===rj&&(rj=import("@opentelemetry/api").catch(()=>null)),rj);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 rU(e){return"boolean"==typeof e?{enabled:e}:e}var rL=class extends rk{constructor(e){super(e)}},rD=class{get functions(){return new b(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 rL({url:this.authUrl.href,headers:rx(rx({},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 eS(this.realtimeUrl.href,rx(rx({},e),{},{params:rx(rx({},{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;let 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);let 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=rU(e.tracePropagation),y=rU(t.tracePropagation),w={db:rx(rx({},d),l),auth:rx(rx({},p),c),realtime:rx(rx({},f),h),storage:{},global:rx(rx(rx({},g),u),{},{headers:rx(rx({},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:rA,realtime:rO,auth:rx(rx({},rR),{},{storageKey:o}),global:rT,tracePropagation:rC});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=(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)})(s),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 rN(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,rx(rx({},s),{},{headers:h}))}})(t,e,this._getAccessToken.bind(this),l.global.fetch,l.tracePropagation),this.realtime=this._initRealtimeClient(rx({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 x(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 tr(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}};(function(){if("undefined"!=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 rB=e.i(909156);function rq(){return"undefined"!=typeof window&&void 0!==window.document}rB.parse,rB.serialize;let rH={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4},rM=/^(.*)[.](0|[1-9][0-9]*)$/;function rW(e,t){if(e===t)return!0;let r=e.match(rM);return!!r&&r[1]===t}function rK(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 rJ(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 rF="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),rz=" 	\n\r=".split(""),rG=(()=>{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<rF.length;t+=1)e[rF[t].charCodeAt(0)]=t;return e})();function rV(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(rF[e]),s-=6}}),s>0)for(r<<=6-s,s=6;s>=6;){let e=r>>s-6&63;t.push(rF[e]),s-=6}return t.join("")}let rY="base64-";function r$(e){let t;if(!e.startsWith(rY))return e;try{t=function(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=rG[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("")}(e.substring(rY.length))}catch(e){return console.warn("@supabase/ssr: could not base64url-decode chunked cookie value, treating as absent. Cookie chunks may have been written partially across responses.",e),null}try{JSON.parse(t)}catch(e){return console.warn("@supabase/ssr: chunked cookie decoded to invalid JSON, treating as absent. This usually indicates that cookie chunks from different writes were combined (e.g. response committed before all Set-Cookie headers were sent)."),null}return t}async function rX(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=>rW(t,e))),d=Object.keys(i).flatMap(e=>{let t=new Set(h.filter(t=>rW(t,e))),r=i[e];"base64url"===o&&(r=rY+rV(r));let s=rK(e,r);return s.forEach(e=>{t.delete(e.name)}),u.push(...t),s}),p={...rH,...l,maxAge:0},f={...rH,...l,maxAge:rH.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}})],{"Cache-Control":"private, no-cache, no-store, must-revalidate, max-age=0",Expires:"0",Pragma:"no-cache"})}let rQ=!1,rZ=["@supabase/auth-helpers-nextjs","@supabase/auth-helpers-react","@supabase/auth-helpers-remix","@supabase/auth-helpers-sveltekit"];function r0(){return function(e,t,r){var s,i,a,o,l,c,h,u,d,f,g;let m;!function(){var e;if(rQ||void 0===p.default||!(null==(e=p.default.env)?void 0:e.npm_package_name))return;let t=p.default.env.npm_package_name;rZ.includes(t)&&(rQ=!0,console.warn("\n╔════════════════════════════════════════════════════════════════════════════╗\n║ ⚠️  IMPORTANT: Package Consolidation Notice                                ║\n║                                                                            ║\n║ The ".concat(t.padEnd(35)," package name is deprecated.  ║\n║                                                                            ║\n║ You are now using @supabase/ssr - a unified solution for all frameworks.  ║\n║                                                                            ║\n║ The auth-helpers packages have been consolidated into @supabase/ssr       ║\n║ to provide better maintenance and consistent APIs across frameworks.      ║\n║                                                                            ║\n║ Please update your package.json to use @supabase/ssr directly:            ║\n║   npm uninstall ").concat(t.padEnd(42)," ║\n║   npm install @supabase/ssr                                               ║\n║                                                                            ║\n║ For more information, visit:                                              ║\n║ https://supabase.com/docs/guides/auth/server-side                         ║\n╚════════════════════════════════════════════════════════════════════════════╝\n    ")))}();let y=(null==r?void 0:r.isSingleton)===!0||(!r||!("isSingleton"in r))&&rq();if(y&&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:w}=function(e,t){var r;let s,n,i=null!=(r=e.cookies)?r:null,a=e.cookieEncoding,o={},l={},c=()=>{let e=(0,rB.parse)(document.cookie);return Object.keys(e).map(t=>{var r;return{name:t,value:null!=(r=e[t])?r:""}})},h=e=>
1{e.forEach(e=>{let{name:t,value:r,options:s}=e;document.cookie=(0,rB.serialize)(t,r,s)})};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 correctness.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring both getAll and setAll cookie methods (deprecated: alternatively both get, set and remove can be used)");else if(!t&&rq())s=()=>c(),n=h;else throw Error("@supabase/ssr: ".concat(t?"createServerClient":"createBrowserClient"," requires configuring getAll and setAll cookie methods (deprecated: alternatively use get, set and remove).").concat(rq()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""));else if(!t&&rq())s=()=>c(),n=h;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 rJ(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});return r?"string"!=typeof r?r:r$(r):null},setItem:async(t,r)=>{if(t.endsWith("-code-verifier")){var i;await rX({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 rJ(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});return r?r$(r):null},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=>rW(e,t))),l=r;"base64url"===a&&(l=rY+rV(r));let c=rK(t,l);c.forEach(e=>{let{name:t}=e;o.delete(t)});let h={...rH,...null==e?void 0:e.cookieOptions,maxAge:0},u={...rH,...null==e?void 0:e.cookieOptions,maxAge:rH.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=>rW(e,t)),a={...rH,...null==e?void 0:e.cookieOptions,maxAge:0};delete a.name,i.length>0&&await n(i.map(e=>({name:e,value:"",options:a})),{})}}}}({...r,cookieEncoding:null!=(h=null==r?void 0:r.cookieEncoding)?h:"base64url"},!1),b=(m={...r,global:{...null==r?void 0:r.global,headers:{...null==r||null==(s=r.global)?void 0:s.headers,"X-Client-Info":"supabase-ssr/".concat("0.10.3"," createBrowserClient")}},auth:{...null==r?void 0:r.auth,...(null==r||null==(i=r.cookieOptions)?void 0:i.name)?{storageKey:r.cookieOptions.name}:null,flowType:"pkce",autoRefreshToken:null!=(u=null==r||null==(a=r.auth)?void 0:a.autoRefreshToken)?u:rq(),detectSessionInUrl:null!=(d=null==r||null==(o=r.auth)?void 0:o.detectSessionInUrl)?d:rq(),persistSession:null==(f=null==r||null==(l=r.auth)?void 0:l.persistSession)||f,storage:w,...(null==r?void 0:r.cookies)&&"encode"in r.cookies&&"tokens-only"===r.cookies.encode?{userStorage:null!=(g=null==r||null==(c=r.auth)?void 0:c.userStorage)?g:window.localStorage}:null}},new rD(e,t,m));return y&&(n=b),b}("https://ehkowqktzcjklmnezvgo.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImVoa293cWt0emNqa2xtbmV6dmdvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODA4MzYyNDQsImV4cCI6MjA5NjQxMjI0NH0.8z_z6UsAlLDGe_FEIR7Or6sa7GOBaXXVa8uNgHs7mCE",{cookieOptions:{maxAge:259200}})}}]);

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.