PageSourceSearch

https://celpippracticetest.com/_next/static/chunks/0cl4wdy6b_-12.js?dpl=dpl_7Vmm7Fcgwd9fqBinFz8R4HoAF1Y6

js celpippracticetest.com collected 2026-09-24 14:40:10 UTC 221,720 bytes, 4 lines download raw bytes

1;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="f9f501bb-a42e-b078-d4b7-0d576c82c9b2")}catch(e){}}();
2(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,909156,(e,t,r)=>{"use strict";let s;Object.defineProperty(r,"__esModule",{value:!0}),r.parseCookie=u,r.parse=u,r.stringifyCookie=function(e,t){let r=(null==t?void 0:t.encode)||encodeURIComponent,s=[];for(let t of Object.keys(e)){let a=e[t];if(void 0===a)continue;if(!n.test(t))throw TypeError("cookie name is invalid: ".concat(t));let o=r(a);if(!i.test(o))throw TypeError("cookie val is invalid: ".concat(a));s.push("".concat(t,"=").concat(o))}return s.join("; ")},r.stringifySetCookie=d,r.serialize=d,r.parseSetCookie=function(e,t){let r=(null==t?void 0:t.decode)||m,s=e.length,n=p(e,0,s),i=f(e,0,n),a=-1===i?{name:"",value:r(g(e,0,n))}:{name:g(e,0,i),value:r(g(e,i+1,n))},o=n+1;for(;o<s;){let t=p(e,o,s),r=f(e,o,t),n=-1===r?g(e,o,t):g(e,o,r),i=-1===r?void 0:g(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&&l.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)}o=t+1}return a},r.stringifySetCookie=d,r.serialize=d;let n=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,i=/^[\u0021-\u003A\u003C-\u007E]*$/,a=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,o=/^[\u0020-\u003A\u003D-\u007E]*$/,l=/^-?\d+$/,c=Object.prototype.toString,h=((s=function(){}).prototype=Object.create(null),s);function u(e,t){let r=new h,s=e.length;if(s<2)return r;let n=(null==t?void 0:t.decode)||m,i=0;do{let t=f(e,i,s);if(-1===t)break;let a=p(e,i,s);if(t>a){i=e.lastIndexOf(";",t-1)+1;continue}let o=g(e,i,t);void 0===r[o]&&(r[o]=n(g(e,t+1,a))),i=a+1}while(i<s)return r}function d(e,t,r){let s="object"==typeof e?e:{...r,name:e,value:String(t)},l="object"==typeof t?t:r,h=(null==l?void 0:l.encode)||encodeURIComponent;if(!n.test(s.name))throw TypeError("argument name is invalid: ".concat(s.name));let u=s.value?h(s.value):"";if(!i.test(u))throw TypeError("argument val is invalid: ".concat(s.value));let d=s.name+"="+u;if(void 0!==s.maxAge){if(!Number.isInteger(s.maxAge))throw TypeError("option maxAge is invalid: ".concat(s.maxAge));d+="; Max-Age="+s.maxAge}if(s.domain){if(!a.test(s.domain))throw TypeError("option domain is invalid: ".concat(s.domain));d+="; Domain="+s.domain}if(s.path){if(!o.test(s.path))throw TypeError("option path is invalid: ".concat(s.path));d+="; Path="+s.path}if(s.expires){var p;if(p=s.expires,"[object Date]"!==c.call(p)||!Number.isFinite(s.expires.valueOf()))throw TypeError("option expires is invali
2d: ".concat(s.expires));d+="; Expires="+s.expires.toUTCString()}if(s.httpOnly&&(d+="; HttpOnly"),s.secure&&(d+="; Secure"),s.partitioned&&(d+="; Partitioned"),s.priority)switch("string"==typeof s.priority?s.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(s.priority))}if(s.sameSite)switch("string"==typeof s.sameSite?s.sameSite.toLowerCase():s.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(s.sameSite))}return d}function p(e,t,r){let s=e.indexOf(";",t);return -1===s?r:s}function f(e,t,r){let s=e.indexOf("=",t);return s<r?s:-1}function g(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 m(e){if(-1===e.indexOf("%"))return e;try{return decodeURIComponent(e)}catch(t){return e}}},536662,e=>{"use strict";let t,r;e.i(247167);class s 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 n extends s{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class i extends s{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class a extends s{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}(d=p||(p={})).Any="any",d.ApNortheast1="ap-northeast-1",d.ApNortheast2="ap-northeast-2",d.ApSouth1="ap-south-1",d.ApSoutheast1="ap-southeast-1",d.ApSoutheast2="ap-southeast-2",d.CaCentral1="ca-central-1",d.EuCentral1="eu-central-1",d.EuWest1="eu-west-1",d.EuWest2="eu-west-2",d.EuWest3="eu-west-3",d.SaEast1="sa-east-1",d.UsEast1="us-east-1",d.UsWest1="us-west-1",d.UsWest2="us-west-2";var o,l,c,h,u,d,p,f,g,m,y,b,w=e.i(290571);class v{setAuth(e){this.headers.Authorization="Bearer ".concat(e)}invoke(e){return(0,w.__awaiter)(this,arguments,void 0,function*(e){var t;let r,s,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{let l,{headers:c,method:h,body:u,signal:d,timeout:p}=o,f={},{region:g}=o;g||(g=this.region);let m=new URL("".concat(this.url,"/").concat(e));g&&"any"!==g&&(f["x-region"]=g,m.searchParams.set("forceFunctionRegion",g)),u&&(c&&!Object.prototype.hasOwnProperty.call(c,"Content-Type")||!c)?"u">typeof Blob&&u instanceof Blob||u instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",l=u):"string"==typeof u?(f["Content-Type"]="text/plain",l=u):"u">typeof FormData&&u instanceof FormData?l=u:(f["Content-Type"]="application/json",l=JSON.stringify(u)):l=!u||"string"==typeof u||"u">typeof Blob&&u instanceof Blob||u instanceof ArrayBuffer||"u">typeof FormData&&u instanceof FormData?u:JSON.stringify(u);let y=d;p&&(s=new AbortController,r=setTimeout(()=>s.abort(),p),d?(y=s.signal,d.addEventListener("abort",()=>s.abort())):y=s.signal);let b=yield this.fetch(m.toString(),{method:h||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),c),body:l,signal:y}).catch(e=>{throw new n(e)}),w=b.headers.get("x-relay-error");if(w&&"true"===w)throw new i(b);if(!b.ok)throw new a(b);let v=(null!=(t=b.headers.get("Content-Type"))?t:"text/plain").split(";")[0].trim();return{data:"application/json"===v?yield b.json():"application/octet-stream"===v||"application/pdf"===v?yield b.blob():"text/event-stream"===v?b:"multipart/form-data"===v?yield b.formData():yield b.text(),error:null,response:b}}catch(e){return{data:null,error:e,response:e instanceof a||e instanceof i?e.context:void 0}}finally{r&&clearTimeout(r)}})}constructor(e,{headers:t={},customFetch:r,region:s=p.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 _=e=>Math.min(1e3*2**e,3e4),k=[520,503],S=["GET","HEAD","OPTIONS"];
2var T=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.code=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 A=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(t instanceof Error&&("AbortError"===t.name||"code"in t&&"ABORT_ERR"===t.code)||!S.includes(r.method))throw t;if(r.retryEnabled&&e<3){let t=_(e);e++,await E(t,r.signal);continue}throw t}if(t=r.method,n=l.status,i=e,r.retryEnabled&&!(i>=3)&&S.includes(t)&&k.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):_(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();""===t||(i="text/csv"===this.headers.get("Accept")||this.headers.get("Accept")&&(null==(s=this.headers.get("Accept"))?void 0:s.includes("application/vnd.pgrst.plan+text"))?t:JSON.parse(t))}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 T(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}},R=class extends A{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;
2let{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 O=RegExp("[,()]");var C=class extends R{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&&O.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&&O.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}}
2,j=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 C({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 C({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 C({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 C({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 C({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 P(e){return(P="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 I(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 x(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?I(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=P(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=P(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==P(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)):I(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var N=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 j(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);
2h?(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 C({method:r,url:l,headers:u,schema:this.schemaName,body:s,fetch:null!=(t=this.fetch)?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}constructor(e,{headers:t={},schema:r,fetch:s,timeout:n,urlLengthLimit:i=8e3,retry:a}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.urlLengthLimit=i;const o=null!=s?s:globalThis.fetch;void 0!==n&&n>0?this.fetch=(e,t)=>{let r=new AbortController,s=setTimeout(()=>r.abort(),n),i=null==t?void 0:t.signal;if(i){if(i.aborted)return clearTimeout(s),o(e,t);let n=()=>{clearTimeout(s),r.abort()};return i.addEventListener("abort",n,{once:!0}),o(e,x(x({},t),{},{signal:r.signal})).finally(()=>{clearTimeout(s),i.removeEventListener("abort",n)})}return o(e,x(x({},t),{},{signal:r.signal})).finally(()=>clearTimeout(s))}:this.fetch=o,this.retry=a}};let U=class{static detectEnvironment(){var t;if("u">typeof WebSocket)return{type:"native",wsConstructor:WebSocket};let r=globalThis;if("u">typeof globalThis&&void 0!==r.WebSocket)return{type:"native",wsConstructor:r.WebSocket};let s=e.g;if(s&&void 0!==s.WebSocket)return{type:"native",wsConstructor:s.WebSocket};if("u">typeof globalThis&&void 0!==r.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("u">typeof globalThis&&r.EdgeRuntime||"u">typeof navigator&&(null==(t=navigator.userAgent)?void 0:t.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let n=globalThis.process;if(n){let e=n.versions;if(e&&e.node){let t=parseInt(e.node.replace(/^v/,"").split(".")[0]);return t>=22?void 0!==globalThis.WebSocket?{type:"native",wsConstructor:globalThis.WebSocket}:{type:"unsupported",error:"Node.js ".concat(t," detected but native WebSocket not found."),workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:"Node.js ".concat(t," detected without native WebSocket support."),workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+="\n\nSuggested solution: ".concat(e.workaround)),Error(t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}},L="realtime-js/".concat("2.105.3"),D="2.0.0",B="errored",q="joined",M={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};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(
2h),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:[]}}(o=f||(f={})).abstime="abstime",o.bool="bool",o.date="date",o.daterange="daterange",o.float4="float4",o.float8="float8",o.int2="int2",o.int4="int4",o.int4range="int4range",o.int8="int8",o.int8range="int8range",o.json="json",o.jsonb="jsonb",o.money="money",o.numeric="numeric",o.oid="oid",o.reltime="reltime",o.text="text",o.time="time",o.timestamp="timestamp",o.timestamptz="timestamptz",o.timetz="timetz",o.tsrange="tsrange",o.tstzrange="tstzrange";let W=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]=K(s,e,t,n),r),{}):{}},K=(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)?J(i,a):F(a)},J=(e,t)=>{if("_"===e.charAt(0))return Y(t,e.slice(1,e.length));switch(e){case f.bool:return z(t);case f.float4:case f.float8:case f.int2:case f.int4:case f.int8:case f.numeric:case f.oid:return G(t);case f.json:case f.jsonb:return V(t);case f.timestamp:return $(t);case f.abstime:case f.date:case f.daterange:case f.int4range:case f.int8range:case f.money:case f.reltime:case f.text:case f.time:case f.timestamptz:case f.timetz:case f.tsrange:case f.tstzrange:default:return F(t)}},F=e=>e,z=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},G=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},V=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){}return e},Y=(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=>J(t,e))}return e},$=e=>"string"==typeof e?e.replace(" ","T"):e,X=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 Q=e=>"function"==typeof e?e:function(){return e},Z="u">typeof window?window:null,ee=("u">typeof self?self:null)||Z||globalThis,et="closed",er="errored",es="joined",en="joining",ei="leaving",ea="phx_close",eo="phx_error",el="phx_reply",ec="phx_leave",eh="websocket",eu="base64url.bearer.phx.",ed=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
2oin_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}},ep=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}},ef=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,this.bindings=[]}onClose(e){this.on(ea,e)}onError(e){return this.on(eo,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 ed(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=ei;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel","leave ".concat(this.topic)),this.trigger(ea,"leave")},r=new ed(this,ec,Q({}),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=en,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}isErrored(){return this.state===er}isJoined(){return this.state===es}isJoining(){return this.state===en}isLeaving(){return this.state===ei}constructor(e,t,r){this.state=et,this.topic=e,this.params=Q(t||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new ed(this,"phx_join",this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new ep(()=>{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=es,this.rejoinTimer.reset(),this.pushBuffer.forEach(e
2=>e.send()),this.pushBuffer=[]}),this.joinPush.receive("error",e=>{this.state=er,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,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=er,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 ed(this,ec,Q({}),this.timeout).send(),this.state=er,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(el,(e,t)=>{this.trigger(this.replyEventName(t),e)})}},eg=class{static request(e,t,r,s,n,i,a){if(ee.XDomainRequest){let r=new ee.XDomainRequest;return this.xdomainRequest(r,e,t,s,n,i,a)}if(ee.XMLHttpRequest){let o=new ee.XMLHttpRequest;return this.xhrRequest(o,e,t,r,s,n,i,a)}if(ee.fetch&&ee.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),ee.fetch(t,o).then(e=>e.text()).then(e=>this.parseJSON(e)).then(e=>a&&a(e)).catch(e=>{"AbortError"===e.name&&i?i():a&&a(null)}),l}static xdomainRequest(e,t,r,s,n,i,a){return e.timeout=n,e.open(t,r),e.onload=()=>{let t=this.parseJSON(e.responseText);a&&a(t)},i&&(e.ontimeout=i),e.onprogress=()=>{},e.send(s),e}static xhrRequest(e,t,r,s,n,i,a,o){for(let[n,a]of(e.open(t,r,!0),e.timeout=i,Object.entries(s)))e.setRequestHeader(n,a);return e.onerror=()=>o&&o(null),e.onreadystatechange=()=>{4===e.readyState&&o&&o(this.parseJSON(e.responseText))},a&&(e.ontimeout=a),e.send(n),e}static parseJSON(e){if(!e||""===e)return null;try{return JSON.parse(e)}catch(t){return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let r=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let n=t?"".concat(t,"[").concat(s,"]"):s,i=e[s];"object"==typeof i?r.push(this.serialize(i,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}return r.join("&")}static appendParams(e,t){if(0===Object.keys(t).length)return e;let r=e.match(/\?/)?"&":"?";return"".concat(e).concat(r).concat(this.serialize(t))}},em=class{normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(RegExp("(.*)/"+eh),"$1/longpoll")}endpointURL(){return eg.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=0}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return 1===this.readyState||0===this.readyState}poll(){let e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:r,messages:s}=e;if(410===t&&null!==this.token){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=r}else t=0;switch(t){case 200:s.forEach(e=>{setTimeout(()=>this.onmessage({data:e}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=1,this.onopen({}),this.poll();break;
2case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw Error("unhandled poll status ".concat(t))}})}send(e){"string"!=typeof e&&(e=(e=>{let t="",r=new Uint8Array(e),s=r.byteLength;for(let e=0;e<s;e++)t+=String.fromCharCode(r[e]);return btoa(t)})(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join("\n"),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,e&&200===e.status?this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]):(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1))})}close(e,t,r){for(let e of this.reqs)e.abort();this.readyState=3;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,"u">typeof CloseEvent?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,r,s,n){let i,a=()=>{this.reqs.delete(i),s()};i=eg.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(eu)&&(this.authToken=atob(t[1].slice(eu.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=0,setTimeout(()=>this.poll(),0)}},ey=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())})}},eb={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);
2case this.KINDS.broadcast:return this.decodeBroadcast(e,t,s)}},decodePush(e,t,r){let s=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(e.slice(a,a+s));a+=s;let l=r.decode(e.slice(a,a+n));a+=n;let c=r.decode(e.slice(a,a+i));return a+=i,{join_ref:o,ref:null,topic:l,event:c,payload:e.slice(a,e.byteLength)}},decodeReply(e,t,r){let s=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(e.slice(o,o+s));o+=s;let c=r.decode(e.slice(o,o+n));o+=n;let h=r.decode(e.slice(o,o+i));o+=i;let u=r.decode(e.slice(o,o+a));return o+=a,{join_ref:l,ref:c,topic:h,event:el,payload:{status:u,response:e.slice(o,e.byteLength)}}},decodeBroadcast(e,t,r){let s=t.getUint8(1),n=t.getUint8(2),i=this.HEADER_LENGTH+2,a=r.decode(e.slice(i,i+s));i+=s;let o=r.decode(e.slice(i,i+n));return i+=n,{join_ref:null,ref:null,topic:a,event:o,payload:e.slice(i,e.byteLength)}}},ew=class{getLongPollTransport(){return em}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=eg.appendParams(eg.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=Q(e)),(!this.conn||this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==em?this.connectWithF
2allback(em,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===em?"LongPoll":e.name}transportConnect(){let e;this.connectClock++,this.closeWasClean=!1,this.authToken&&(e=["phoenix","".concat(eu).concat(btoa(this.authToken).replace(/=/g,""))]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e){let t,r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2500;clearTimeout(this.fallbackTimer);let n=!1,i=!0,a=this.transportName(e),o=s=>{this.log("transport","falling back to ".concat(a,"..."),s),this.off([t,r]),i=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession("phx:fallback:".concat(a)))return o("memorized");this.fallbackTimer=setTimeout(o,s),r=this.onError(e=>{this.log("transport","error",e),i&&!n&&(clearTimeout(this.fallbackTimer),o(e))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(n=!0,!i){let t=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession("phx:fallback:".concat(t),"true"),this.log("transport","established ".concat(t," fallback"))}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,s),this.ping(e=>{this.log("transport","connected to primary after",e),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport","connected to ".concat(this.endPointURL())),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),1e3,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,r){if(!this.conn)return e&&e();let s=this.conn;this.waitForBufferDone(s,()=>{t?s.close(t,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;5!==r&&e.bufferedAmount?setTimeout(()=>{this.waitForBufferDone(e,t,r+1)},150*r):t()}waitForSocketClosed(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;5===r||3===e.readyState?t():setTimeout(()=>{this.waitForSocketClosed(e,t,r+1)},150*r)}
2onConnClose(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(eo,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case 0:return"connecting";case 1:return"open";case 2:return"closing";default:return"closed"}}isConnected(){return"open"===this.connectionState()}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(t=>{let[r]=t;return -1===e.indexOf(r)})}channel(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=new ef(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||ee.WebSocket||em,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||ee&&ee.sessionStorage,this.establishedConnections=0,this.defaultEncoder=eb.encode.bind(eb),this.defaultDecoder=eb.decode.bind(eb),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!==em?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let n=null;Z&&Z.addEventListener&&(Z.addEventListener("pagehide",e=>{this.conn&&(this.disconnect(),n=this.connectClock)}),Z.addEventListener("pageshow",e=>{n===this.connectClock&&(n=null,this.connect())}),Z.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=Q(t.params||{}),this.endPoint="".concat(e,"/").concat(eh),this.vsn=t.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new ep(()=>
2{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 ev{get state(){return ev.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]=e_(s),t},{})}static onJoinPayload(e,t,r){return{event:"join",key:e,currentPresences:ek(t),newPresences:e_(r)}}static onLeavePayload(e,t,r){return{event:"leave",key:e,currentPresences:ek(t),leftPresences:e_(r)}}constructor(e,t){const r=function(e){return(null==e?void 0:e.events)&&{events:e.events}}(t);this.presence=new ey(e.getChannel(),r),this.presence.onJoin((t,r,s)=>{let n=ev.onJoinPayload(t,r,s);e.getChannel().trigger("presence",n)}),this.presence.onLeave((t,r,s)=>{let n=ev.onLeavePayload(t,r,s);e.getChannel().trigger("presence",n)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}}function e_(e){return e.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function ek(e){return(null==e?void 0:e.metas)?e_(e):[]}(l=g||(g={})).SYNC="sync",l.JOIN="join",l.LEAVE="leave";class eS{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new ev(this.channel.channelAdapter,t)}}class eT{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===q}isJoined(){return this.state===q}isJoining(){return"joining"===this.state}isClosed(){return"closed"===this.state}isLeaving(){return"leaving"===this.state}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}constructor(e,t,r){const s=function(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},e.config)}}(r);this.channel=e.getSocket().channel(t,s),this.socket=e}}(c=m||(m={})).ALL="*",c.INSERT="INSERT",c.UPDATE="UPDATE",c.DELETE="DELETE",(h=y||(y={})).BROADCAST="broadcast",h.PRESENCE="presence",h.POSTGRES_CHANGES="postgres_changes",h.SYSTEM="system",(u=b||(b={})).SUBSCRIBED="SUBSCRIBED",u.TIMED_OUT="TIMED_OUT",u.CLOSED="CLOSED",u.CHANNEL_ERROR="CHANNEL_ERROR";class eE{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}subscribe(e){var t,r,s;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.timeout;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:i,presence:a,private:o}}=this.params,l=null!=(r=null==(t=this.bindings.postgres_changes)?void 0:t.map(e=>e.filter))?r:[],c=!!this.bindings[y.PRESENCE]&&this.bindings[y.PRESENCE].length>0||(null==(s=this.params.config.presence)?void 0:s.enabled)===!0,h={},u={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:l,private:o};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(t=>{null==e||e(b.CHANNEL_ERROR,function(e){if(e instanceof Error)return e;if("string"==typeof e)return Error(e);
2if(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(b.CLOSED)),this.updateJoinPayload(Object.assign({config:u},h)),this._updateFilterMessage(),this.channelAdapter.subscribe(n).receive("ok",async t=>{let{postgres_changes:r}=t;if(this.socket._isManualToken()||this.socket.setAuth(),void 0===r){null==e||e(b.SUBSCRIBED);return}this._updatePostgresBindings(r,e)}).receive("error",t=>{this.state=B;let r=Object.values(t).join(", ")||"error";null==e||e(b.CHANNEL_ERROR,Error(r,{cause:t}))}).receive("timeout",()=>{null==e||e(b.TIMED_OUT)})}return this}_updatePostgresBindings(e,t){var r;let s=this.bindings.postgres_changes,n=null!=(r=null==s?void 0:s.length)?r:0,i=[];for(let r=0;r<n;r++){let n=s[r],{filter:{event:a,schema:o,table:l,filter:c}}=n,h=e&&e[r];if(h&&h.event===a&&eE.isFilterValueEqual(h.schema,o)&&eE.isFilterValueEqual(h.table,l)&&eE.isFilterValueEqual(h.filter,c))i.push(Object.assign(Object.assign({},n),{id:h.id}));else{this.unsubscribe(),this.state=B,null==t||t(b.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=B&&t&&t(b.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===y.PRESENCE||e===y.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={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(n.Authorization="Bearer ".concat(this.socket.accessTokenValue));let i={method:"POST",headers:n,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,null!=(r=s.timeout)?r:this.timeout);if(202===a.status)return{success:!0};let o=a.statusText;try{let e=await a.json();o=e.error||e.message||o}catch(e){}return Promise.reject(Error(o))}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 
2in 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}=M;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=W(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=W(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 eT(this.socket.socketAdapter,e,this.params),this.presence=new eS(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=X(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 eA{get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,t,r){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;return new Promise(n=>{setTimeout(()=>n("timeout"),s),this.socket.disconnect(()=>{e(),n("ok")},t,r)})}push(e){this.socket.push(e)}log(e,t,r){this.socket.log(e,t,r)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return"connecting"==this.socket.connectionState()}isDisconnecting(){return"closing"==this.socket.connectionState()}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}constructor(e,t){this.socket=new ew(e,t)}}let eR=[1e3,2e3,5e3,1e4];class eO{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(t){let e=t.message;if(e.includes("Node.js"))throw Error("".concat(e,"\n\n")+'To use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n  npm install ws\n\n  import ws from "ws"\n  const client = new RealtimeClient(url, {\n    ...options,\n    transport: ws\n  })');throw Error("WebSocket not available: ".concat(e))}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,t){return(this._cancelPendingDisconnect(),this.isDisconnecting())?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,t)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return"ok"===t&&e.teardown(),t}async removeAllChannels(){let e=this.channels.map(async e=>{let t=await e.unsubscribe();return e.teardown(),t}),t=await Promise.all(e);return await this.disconnect(),t}log(e,t,r){this.socketAdapter.log(e,t,r)}connectionState(){return this.socketAdapter.connectionState()||"closed"}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{config:{}},r="realtime:".concat(e),s=this.getChannels().find(e=>e.topic===r);if(s)return s;{let r=new eE("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}
2this._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:L};e&&t.updateJoinPayload(r),t.joinedOnce&&t.channelAdapter.isJoined()&&t.channelAdapter.push(M.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;let d,p;this.worker=null!=(t=null==e?void 0:e.worker)&&t,this.accessToken=null!=(r=null==e?void 0:e.accessToken)?r:null;let f={};f.timeout=null!=(s=null==e?void 0:e.timeout)?s:1e4,f.heartbeatIntervalMs=null!=(n=null==e?void 0:e.heartbeatIntervalMs)?n:25e3,this._disconnectOnEmptyChannelsAfterMs=null!=(i=null==e?void 0:e.disconnectOnEmptyChannelsAfterMs)?i:2*(null!=(a=null==e?void 0:e.heartbeatIntervalMs)?a:25e3),f.transport=null!=(o=null==e?void 0:e.transport)?o:U.getWebSocketConstructor(),f.params=null==e?void 0:e.params,f.logger=null==e?void 0:e.logger,f.heartbeatCallback=this._wrapHeartbeatCallback(null==e?void 0:e.heartbeatCallback),f.reconnectAfterMs=null!=(l=null==e?void 0:e.reconnectAfterMs)?l:e=>eR[e-1]||1e4;let g=null!=(c=null==e?void 0:e.vsn)?c:D;switch(g){case"1.0.0":d=(e,t)=>t(JSON.stringify(e)),p=(e,t)=>t(JSON.parse(e));break;case D:d=this.serializer.encode.bind(this.serializer),p=this.serializer.decode.bind(this.serializer);break;default:throw Error("Unsupported serializer version: ".concat(f.vsn))}if(f.vsn=g,f.encode=null!=(h=null==e?void 0:e.encode)?h:d,f.decode=null!=(u=null==e?void 0:e.decode)?u:p,f.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,f.params=Object.assign(Object.assign({},f.params),{log_level:this.logLevel})),this.worker){if("u">typeof window&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl,f.autoSendHeartbeat=!this.worker}return f}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={}
2,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;const s=this._initializeOptions(t);this.socketAdapter=new eA(e,s),this.httpEndpoint=X(e),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}}var eC=e.i(467034),ej=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 eP(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 eI(e){return e.join("\x1f")}var ex=class{async listNamespaces(e){let t=e?{parent:eI(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(eI(e.namespace))})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces/").concat(eI(e.namespace))})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:"".concat(this.prefix,"/namespaces/").concat(eI(e.namespace))}),!0}catch(e){if(e instanceof ej&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof ej&&409===e.status)return;throw e}}constructor(e,t=""){this.client=e,this.prefix=t}};function eN(e){return e.join("\x1f")}var eU=class{async listTables(e){return(await this.client.request({method:"GET",path:"".concat(this.prefix,"/namespaces/").concat(eN(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(eN(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(eN(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(eN(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(eN(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(eN(e.namespace),"/tables/").concat(e.name),headers:t}),!0}catch(e){if(e instanceof ej&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof ej&&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}},eL=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)}
2async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}constructor(e){var t;let r="v1";e.catalogName&&(r+="/".concat(e.catalogName));const s=e.baseUrl.endsWith("/")?e.baseUrl:"".concat(e.baseUrl,"/");this.client=function(e){var t;let r=null!=(t=e.fetchImpl)?t:globalThis.fetch;return{async request(t){let{method:s,path:n,query:i,body:a,headers:o}=t,l=function(e,t,r){let s=new URL(t,e);if(r)for(let[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,n,i),c=await eP(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 ej(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 ex(this.client,r),this.tableOps=new eU(this.client,r,this.accessDelegation)}};function eD(e){return(eD="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 eB(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 eq(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?eB(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=eD(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=eD(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==eD(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)):eB(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var eM=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 eH(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var eW=class extends eM{toJSON(){return eq({},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}},eK=class extends eM{constructor(e,t,r="storage"){super(e,r),this.name="vectors"===r?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};function eJ(e,t,r){let s=eq({},e),n=t.toLowerCase();for(let e of Object.keys(s))e.toLowerCase()===n&&delete s[e];return s[n]=r,s}let eF=e=>{if(Array.isArray(e))return e.map(e=>eF(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,""))]=eF(s)}),t},ez=e=>{if("object"==typeof e&&null!==e){if("string"==typeof e.msg)return e.msg;if("string"==typeof e.message)return e.message;if("string"==typeof e.error_description)return e.error_description;if("string"==typeof e.error)return e.error;if("object"==typeof e.error&&null!==e.error){let t=e.error;if("string"==typeof t.message)return t.message}}return JSON.stringify(e)},eG=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 eW(ez(e),r,n,s))}).catch(()=>{let n=r+"";t(new eW(e.statusText||"HTTP ".concat(r," error"),r,n,s))})}else t(new eK(ez(e),e,s))};async function eV(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 eq(eq({},n),r);
2if((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=eJ(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),eq(eq({},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=>eG(e,l,s,a))})}function eY(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"storage";return{get:async(t,r,s,n)=>eV(t,"GET",r,s,n,void 0,e),post:async(t,r,s,n,i)=>eV(t,"POST",r,n,i,s,e),put:async(t,r,s,n,i)=>eV(t,"PUT",r,n,i,s,e),head:async(t,r,s,n)=>eV(t,"HEAD",r,eq(eq({},s),{},{noResolveJson:!0}),n,void 0,e),remove:async(t,r,s,n,i)=>eV(t,"DELETE",r,n,i,s,e)}}let{get:e$,post:eX,put:eQ,head:eZ,remove:e0}=eY("storage"),e1=eY("vectors");var e2=class{throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=eJ(this.headers,e,t),this}async handleOperation(e){try{return{data:await e(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eH(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}},e5=class{then(e,t){return this.execute().then(e,t)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eH(e))return{data:null,error:e};throw e}}constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}};t=Symbol.toStringTag;var e8=class{asStream(){return new e5(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(eH(e))return{data:null,error:e};throw e}}constructor(e,r){this.downloadFn=e,this.shouldThrowOnError=r,this[t]="BlobDownloadBuilder",this.promise=null}};let e3={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},e6={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var e4=class extends e2{async uploadOrUpdate(e,t,r,s){var n=this;return n.handleOperation(async()=>{let i,a=eq(eq({},e6),s),o=eq(eq({},n.headers),"POST"===e&&{"x-upsert":String(a.upsert)}),l=a.metadata;if("u">typeof Blob&&r instanceof Blob?((i=new FormData).append("cacheControl",a.cacheControl),l&&i.append("metadata",n.encodeMetadata(l)),i.append("",r)):"u">typeof FormData&&r instanceof FormData?((i=r).has("cacheControl")||i.append("cacheControl",a.cacheControl),l&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(l))):(i=r,o["cache-control"]="max-age=".concat(a.cacheControl),o["content-type"]=a.contentType,l&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(l))),("u">typeof ReadableStream&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!a.duplex&&(a.duplex="half")),null==s?void 0:s.headers)for(let[e,t]of Object.entries(s.headers))o=eJ(o,e,t);let c=n._removeEmptyFolders(t),h=n._getFinalPath(c),u=await ("PUT"==e?eQ:eX)(n.fetch,"".concat(n.url,"/object/").concat(h),i,eq({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=eq(eq({},e6),s),a=eq(eq({},n.headers),{"x-upsert":String(t.upsert)}),l=t.metadata;if("u">typeof Blob&&r instanceof Blob?((e=new FormData).append("cacheControl",t.cacheControl),l&&e.append("metadata",n.encodeMetadata(l)),e.append("",r)):"u">typeof FormData&&r instanceof FormData?((e=r).has("cacheControl")||e.append("cacheControl",t.cacheControl),l&&!e.has("metadata")&&e.append("metadata",n.encodeMetadata(l))):(e=r,a["cache-control"]="max-age=".concat(t.cacheControl),a["content-type"]=t.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),("u">typeof ReadableStream&&e instanceof ReadableStream||e&&"object"==typeof e&&"pipe"in e&&"function"==typeof e.pipe)&&!t.duplex&&(t.duplex="half")),null==s?void 0:s.headers)for(let[e,t]of Object.entries(s.headers))a=eJ(a,e,t);
2return{path:i,fullPath:(await eQ(n.fetch,o.toString(),e,eq({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=eq({},r.headers);(null==t?void 0:t.upsert)&&(n["x-upsert"]="true");let i=await eX(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 eM("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 eX(s.fetch,"".concat(s.url,"/object/move"),{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers}))}async copy(e,t,r){var s=this;return s.handleOperation(async()=>({path:(await eX(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 eX(s.fetch,"".concat(s.url,"/object/sign/").concat(n),eq({expires
2In: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 eX(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=>eq(eq({},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 e8(()=>e$(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()=>eF(await e$(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 eZ(this.fetch,"".concat(this.url,"/object/").concat(r),{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eH(e)){let r=e instanceof eW?e.status:e instanceof eK?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 e0(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=eq(eq(eq({},e3),t),{},{prefix:e||""});return await eX(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=eq({},e);return await eX(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!==eC.Buffer?eC.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("quality",t.quality.toString()),e}constructor(e,t={},r,s){super(e,t,s,"storage"),this.bucketId=r}};let e9={"X-Client-Info":"storage-js/".concat("2.105.3")};var e7=class extends e2{async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=t.listBucketOptionsToQueryString(e);return await e$(t.fetch,"".concat(t.url,"/bucket").concat(r),{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await e$(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 eX(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 eQ(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 eX(t.fetch,"".concat(t.url,"/bucket/").concat(e,"/empty"),{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await e0(t.fetch,"".concat(t.url,"/bucket/").concat(e),{},{headers:t.headers}))}listBucketOptionsToQueryString(e){let t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}constructor(e,t={},r,s){const n=new URL(e);(null==s?void 0:s.useNewHostname)&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase.")),super(n.href.replace(/\/$/,""),eq(eq({},e9),t),r,"storage")}},te=class extends e2{async createBucket(e){var t=this;return t.handleOperation(async()=>await eX(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 e$(t.fetch,n,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await e0(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 eM("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 eL({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(/\/$/,""),eq(eq({},e9),t),r,"storage")}},tt=class extends e2{async createIndex(e){var t=this;return t.handleOperation(async()=>await e1.post(t.fetch,"".concat(t.url,"/CreateIndex"),e,{headers:t.headers})||{})}async getIndex(e,t){var r=this;return r.handleOperation(async()=>await e1.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 e1.post(t.fetch,"".concat(t.url,"/ListIndexes"),e,{headers:t.headers}))}async deleteIndex(e,t){var r=this;return r.handleOperation(async()=>await e1.post(r.fetch,"".concat(r.url,"/DeleteIndex"),{vectorBucketName:e,indexName:t},{headers:r.headers})||{})}constructor(e,t={},r){super(e.replace(/\/$/,""),eq(eq({},e9),{},{"Content-Type":"application/json"},t),r,"vectors")}},tr=class extends e2{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 e1.post(t.fetch,"".concat(t.url,"/PutVectors"),e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await e1.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");
2if(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 e1.post(t.fetch,"".concat(t.url,"/ListVectors"),e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await e1.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 e1.post(t.fetch,"".concat(t.url,"/DeleteVectors"),e,{headers:t.headers})||{})}constructor(e,t={},r){super(e.replace(/\/$/,""),eq(eq({},e9),{},{"Content-Type":"application/json"},t),r,"vectors")}},ts=class extends e2{async createBucket(e){var t=this;return t.handleOperation(async()=>await e1.post(t.fetch,"".concat(t.url,"/CreateVectorBucket"),{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await e1.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 e1.post(t.fetch,"".concat(t.url,"/ListVectorBuckets"),e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await e1.post(t.fetch,"".concat(t.url,"/DeleteVectorBucket"),{vectorBucketName:e},{headers:t.headers})||{})}constructor(e,t={},r){super(e.replace(/\/$/,""),eq(eq({},e9),{},{"Content-Type":"application/json"},t),r,"vectors")}},tn=class extends ts{from(e){return new ti(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)}},ti=class extends tt{async createIndex(e){return super.createIndex.call(this,eq(eq({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return super.listIndexes.call(this,eq(eq({},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 ta(this.url,this.headers,this.vectorBucketName,e,this.fetch)}constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}},ta=class extends tr{async putVectors(e){return super.putVectors.call(this,eq(eq({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async getVectors(e){return super.getVectors.call(this,eq(eq({},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,eq(eq({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async queryVectors(e){return super.queryVectors.call(this,eq(eq({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async deleteVectors(e){return super.deleteVectors.call(this,eq(eq({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}constructor(e,t,r,s,n){super(e,t,n),this.vectorBucketName=r,this.indexName=s}},to=class extends e7{from(e){return new e4(this.url,this.headers,e,this.fetch)}get vectors(){return new tn(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new te(this.url+"/iceberg",this.headers,this.fetch)}constructor(e,t={},r,s){super(e,t,r,s)}};let tl="2.105.3",tc="X-Supabase-Api-Version",th={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},tu=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class td 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
2de=r}}function tp(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class tf extends td{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class tg extends td{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class tm extends td{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class ty extends tm{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function tb(e){return tp(e)&&"AuthSessionMissingError"===e.name}class tw extends tm{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class tv extends tm{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class t_ extends tm{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 tk extends tm{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 tS extends tm{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 tT extends tm{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function tE(e){return tp(e)&&"AuthRetryableFetchError"===e.name}class tA extends tm{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 tR extends tm{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}let tO="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),tC=" 	\n\r=".split(""),tj=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<tC.length;t+=1)e[tC[t].charCodeAt(0)]=-2;for(let t=0;t<tO.length;t+=1)e[tO[t].charCodeAt(0)]=t;return e})();function tP(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;)r(tO[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(tO[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function tI(e,t,r){let s=tj[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 tx(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)tI(e.charCodeAt(t),n,i);return t.join("")}function tN(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)tI(e.charCodeAt(t),r,s);return new Uint8Array(t)}function tU(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>tP(e,r,s)),tP(null,r,s),t.join("")}let tL=()=>"u">typeof window&&"u">typeof document,tD={tested:!1,writable:!1},tB=()=>{if(!tL())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(tD.tested)return tD.writable;let e="lswt-".concat(Math.random()).concat(Math.random());try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),tD.tested=!0,tD.writable=!0}catch(e){tD.tested=!0,tD.writable=!1}return tD.writable},tq=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)},tM=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},tH=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},tW=async(e,t)=>{await e.removeItem(t)};class tK{constructor(){this.promise=new tK.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function tJ(e){let t=e.split(".");if(3!==t.length)throw new tR("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!tu.test(t[e]))throw new tR("JWT not in base64url format");return{header:JSON.parse(tx(t[0])),payload:JSON.parse(tx(t[1])),signature:tN(t[2]),raw:{header:t[0],payload:t[1]}}}async function tF(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function tz(e){return("0"+e.toString(16)).substr(-2)}async function tG(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 tV(e){return"u">typeof crypto&&void 0!==crypto.subtle&&"u">typeof TextEncoder?btoa(await tG(e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""):(console.warn("WebCrypto API is not supported. Code 
2challenge method will default to use plain instead of sha256."),e)}async function tY(e,t){let r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=function(){let e=new Uint32Array(56);if("u"<typeof crypto){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length,r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,tz).join("")}(),n=s;r&&(n+="/recovery"),await tM(e,"".concat(t,"-code-verifier"),n);let i=await tV(s),a=s===i?"plain":"s256";return[i,a]}tK.promiseConstructor=Promise;let t$=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i,tX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function tQ(e){if(!tX.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function tZ(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 t0(){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 t1(e){return JSON.parse(JSON.stringify(e))}let t2=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)},t5=[502,503,504,520,521,522,523,524,530];async function t8(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 tT(t2(e),0);if(t5.includes(e.status))throw new tT(t2(e),e.status);try{r=await e.json()}catch(e){throw new tg(t2(e),e)}let n=function(e){let t=e.headers.get(tc);if(!t||!t.match(t$))return null;try{return new Date("".concat(t,"T00:00:00.0Z"))}catch(e){return null}}(e);if(n&&n.getTime()>=th["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 tA(t2(r),e.status,(null==(t=r.weak_password)?void 0:t.reasons)||[]);else if("session_not_found"===s)throw new ty}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 tA(t2(r),e.status,r.weak_password.reasons);throw new tf(t2(r),e.status||500,s)}async function t3(e,t,r,s){var n;let i=Object.assign({},null==s?void 0:s.headers);i[tc]||(i[tc]=th["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 t6(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 t6(e,t,r,s,n,i){let a,o,l=(o={method:t,headers:(null==s?void 0:s.headers)||{}},"GET"===t?o:(o.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"}
2,null==s?void 0:s.headers),o.body=JSON.stringify(i),Object.assign(Object.assign({},o),n)));try{a=await e(r,Object.assign({},l))}catch(e){throw console.error(e),new tT(t2(e),0)}if(a.ok||await t8(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await t8(e)}}function t4(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:e},error:null}}function t9(e){let t=t4(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function t7(e){var t;return{data:{user:null!=(t=e.user)?t:e},error:null}}function re(e){return{data:e,error:null}}function rt(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({},(0,w.__rest)(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]))},error:null}}function rr(e){return e}let rs=["global","local","others"];class rn{async signOut(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rs[0];if(0>rs.indexOf(t))throw Error("@supabase/auth-js: Parameter scope must be one of ".concat(rs.join(", ")));try{return await t3(this.fetch,"POST","".concat(this.url,"/logout?scope=").concat(t),{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tp(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 t3(this.fetch,"POST","".concat(this.url,"/invite"),{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:t7})}catch(e){if(tp(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,r=(0,w.__rest)(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 t3(this.fetch,"POST","".concat(this.url,"/admin/generate_link"),{body:s,headers:this.headers,xform:rt,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(tp(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await t3(this.fetch,"POST","".concat(this.url,"/admin/users"),{body:e,headers:this.headers,xform:t7})}catch(e){if(tp(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 t3(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:rr});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(tp(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){tQ(e);try{return await t3(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(e),{headers:this.headers,xform:t7})}catch(e){if(tp(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){tQ(e);try{return await t3(this.fetch,"PUT","".concat(this.url,"/admin/users/").concat(e),{body:t,headers:this.headers,xform:t7})}catch(e){if(tp(e))return{data:{user:null},error:e};throw e}}async deleteUser(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];tQ(e);try{return await t3(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(e),{headers:this.headers,body:{should_soft_delete:t},xform:t7})}catch(e){if(tp(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){tQ(e.userId);try{let{data:t,error:r}=await t3(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(tp(e))return{data:null,error:e};throw e}}async _deleteFactor(e){tQ(e.userId),tQ(e.id);
2try{return{data:await t3(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(e.userId,"/factors/").concat(e.id),{headers:this.headers}),error:null}}catch(e){if(tp(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 t3(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:rr});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(tp(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await t3(this.fetch,"POST","".concat(this.url,"/admin/oauth/clients"),{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tp(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await t3(this.fetch,"GET","".concat(this.url,"/admin/oauth/clients/").concat(e),{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tp(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await t3(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(tp(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await t3(this.fetch,"DELETE","".concat(this.url,"/admin/oauth/clients/").concat(e),{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tp(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await t3(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(tp(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 t3(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(tp(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await t3(this.fetch,"POST","".concat(this.url,"/admin/custom-providers"),{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tp(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await t3(this.fetch,"GET","".concat(this.url,"/admin/custom-providers/").concat(e),{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tp(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await t3(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(tp(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await t3(this.fetch,"DELETE","".concat(this.url,"/admin/custom-providers/").concat(e),{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tp(e))return{data:null,error:e};throw e}}async _adminListPasskeys(e){tZ(this.experimental),tQ(e.userId);try{return await t3(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(e.userId,"/passkeys"),{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tp(e))return{data:null,error:e};throw e}}async _adminDeletePasskey(e){tZ(this.experimental),tQ(e.userId),tQ(e.passkeyId);try{return await t3(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(tp(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=tq(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 ri(){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]}}}let ra={debug:!!(globalThis&&tB()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};
2class ro extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class rl extends ro{}async function rc(e,t,r){let s;ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let n=new globalThis.AbortController;t>0&&(s=setTimeout(()=>{n.abort(),ra.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t)),await Promise.resolve();try{return await globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async n=>{if(n){clearTimeout(s),ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,n.name);try{return await r()}finally{ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,n.name)}}if(0===t)throw ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new rl('Acquiring an exclusive Navigator LockManager lock "'.concat(e,'" immediately failed'));if(ra.debug)try{let e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null,"  "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(s),await r()})}catch(i){if(t>0&&clearTimeout(s),null!==i&&"object"==typeof i&&"name"in i&&"AbortError"===i.name&&t>0)if(n.signal.aborted)return ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",e),console.warn('@supabase/gotrue-js: Lock "'.concat(e,'" was not released within ').concat(t,"ms. ")+"This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover."),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,{mode:"exclusive",steal:!0},async t=>{if(!t)return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r();ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",e,t.name);try{return await r()}finally{ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",e,t.name)}}));else throw ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",e),new rl('Lock "'.concat(e,'" was released because another request stole it'));throw i}}function rh(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error('@supabase/auth-js: Address "'.concat(e,'" is invalid.'));return e.toLowerCase()}class ru 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 rd extends ru{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}let rp=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 rf(e){if(!e)throw Error("Credential creation options are required");if("u">typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:r,excludeCredentials:s}=e,n=(0,w.__rest)(e,["challenge","user","excludeCredentials"]),i=tN(t).buffer,a=Object.assign(Object.assign({},r),{id:tN(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:tN(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function rg(e){if(!e)throw Error("Credential request options are required");if("u">typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:r}=e,s=(0,w.__rest)(e,["challenge","allowCredentials"]),n=tN(t).buffer,i=Object.assign(Object.assign({}
2,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:tN(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return i}function rm(e){var t;return"toJSON"in e&&"function"==typeof e.toJSON?e.toJSON():{id:e.id,rawId:e.id,response:{attestationObject:tU(new Uint8Array(e.response.attestationObject)),clientDataJSON:tU(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!=(t=e.authenticatorAttachment)?t:void 0}}function ry(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:tU(new Uint8Array(s.authenticatorData)),clientDataJSON:tU(new Uint8Array(s.clientDataJSON)),signature:tU(new Uint8Array(s.signature)),userHandle:s.userHandle?tU(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!=(t=e.authenticatorAttachment)?t:void 0}}function rb(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function rw(){var e,t;return!!(tL()&&"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 rv(e){try{let t=await navigator.credentials.create(e);if(!t)return{data:null,error:new rd("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new rd("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 ru({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 ru({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 ru({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 ru({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 ru({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});else if("NotAllowedError"===n.name)return new ru({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});else if("NotSupportedError"===n.name)return new ru(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(!rb(e))return new ru({message:"".concat(window.location.hostname," is an invalid domain"),code:"ERROR_INVALID_DOMAIN",cause:n});if(a.rp.id!==e)return new ru({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 ru({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 ru({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ER
2ROR",cause:n});return new ru({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}({error:t,options:e})}}}async function r_(e){try{let t=await navigator.credentials.get(e);if(!t)return{data:null,error:new rd("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new rd("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function(e){let{error:t,options: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 ru({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if("NotAllowedError"===t.name)return new ru({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});else if("SecurityError"===t.name){let e=window.location.hostname;if(!rb(e))return new ru({message:"".concat(window.location.hostname," is an invalid domain"),code:"ERROR_INVALID_DOMAIN",cause:t});if(s.rpId!==e)return new ru({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 ru({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 ru({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}({error:t,options:e})}}}let rk={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},rS={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function rT(){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]=rT(e,r):i[t]=rT(r)}else i[t]=r}return i}class rE{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:rp.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,rT(rk,s,n||{})),{data:i,error:a}=await rv({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,rT(rS,i,a||{})),{data:s,error:n}=await r_(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(tp(e))return{data:null,error:e};return{data:null,error:new tg("Unexpected error in challenge",e)}}}async _verify(e){let{challengeId:t,factorId:r,webauthn:s}=e;return this.client.mfa.verify({factorId:r,challengeId:t,webauthn:s})}async _authenticate(e,t){let{factorId:r,webauthn:{rpId:s="u">typeof window?window.location.hostname:void 0,rpOrigins:n="u">typeof window?[window.location.origin]:void 0,signal:i}={}}=e;if(!s)return{data:null,error:new td("rpId is required for WebAuthn authentication")};try{if(!rw())return{data:null,error:new tg("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(tp(e))return{data:null,error:e};return{data:null,error:new tg("Unexpected error in authenticate",e)}}}async _register(e,t){let{friendlyName:r,webauthn:{rpId:s="u">typeof window?window.location.hostname:void 0,rpOrigins:n="u">typeof window?[window.location.origin]:void 0,signal:i}={}}=e;if(!s)return{data:null,error:new td("rpId is required for WebAuthn registration")};try{if(!rw())return{data:null,error:new tg("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(tp(e))return{data:null,error:e};return{data:null,error:new tg("Unexpected error in register",e)}}}constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}}if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"u">typeof self&&(self.globalThis=self)}let rA={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:{"X-Client-Info":"gotrue-js/".concat(tl)},flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function rR(e,t,r){return await r()}let rO={};class rC{get jwks(){var e,t;return null!=(t=null==(e=rO[this.storageKey])?void 0:e.jwks)?t:{keys:[]}}set jwks(e){rO[this.storageKey]=Object.assign(Object.assign({},rO[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!=(t=null==(e=rO[this.storageKey])?void 0:e.cachedAt)?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){rO[this.storageKey]=Object.assign(Object.assign({},rO[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(tl,") ").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()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(tL()&&(t=function(e){let t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEac
2h((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")),tL()&&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),tp(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(tp(e))return this._returnResult({error:e});return this._returnResult({error:new tg("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 t3(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:t4});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(tp(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 tY(this.storage,this.storageKey)),n=await t3(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:t4})}else if("phone"in e){let{phone:t,password:i,options:a}=e;n=await t3(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:t4})}else throw new tv("You must provide either an email or phone number and a password");let{data:i,error:a}=n;if(a||!i)return await tW(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 tW(this.storage,"".concat(this.storageKey,"-code-verifier")),tp(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 t3(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:t9})}else if("phone"in e){let{phone:r,password:s,options:n}=e;t=await t3(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:t9})}else throw new tv("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 tw;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(tp(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,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error('@supabase/auth-js: Unsupported chain "'.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(tL())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 b=new URL(null!=(t=null==y?void 0:y.url)?t:window.location.href),w=await h.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!w||0===w.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let v=rh(w[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=rh(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:b.host,address:v,statement:m,uri:b.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 t3(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:t4});if(r)throw r;if(!t||!t.session||!t.user){let e=new tw;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(tp(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(tL())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
2Message"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 b=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:b.host,uri:b.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(b.host," wants you to sign in with your Solana account:"),u.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1","URI: ".concat(b.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 t3(this.fetch,"POST","".concat(this.url,"/token?grant_type=web3"),{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:tU(f)},(null==(u=e.options)?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null==(d=e.options)?void 0:d.captchaToken}}:null),xform:t4});if(r)throw r;if(!t||!t.session||!t.user){let e=new tw;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(tp(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let t=await tH(this.storage,"".concat(this.storageKey,"-code-verifier")),[r,s]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new tS;let{data:t,error:n}=await t3(this.fetch,"POST","".concat(this.url,"/token?grant_type=pkce"),{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:t4});if(await tW(this.storage,"".concat(this.storageKey,"-code-verifier")),n)throw n;if(!t||!t.session||!t.user){let e=new tw;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 tW(this.storage,"".concat(this.storageKey,"-code-verifier")),tp(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 t3(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:t4});if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!a||!a.session||!a.user){let e=new tw;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(tp(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 tY(this.storage,this.storageKey));let{error:o}=await t3(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 t3(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 tv("You must provide either an email or phone number.")}catch(e){if(await tW(this.storage,"".concat(this.storageKey,"-code-verifier")),tp(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 t3(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:t4});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(tp(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 tY(this.storage,this.storageKey));let l=await t3(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:re});return(null==(n=l.data)?void 0:n.url)&&tL()&&!(null==(i=e.options)?void 0:i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await tW(this.storage,"".concat(this.storageKey,"-code-verifier")),tp(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new ty;let{error:s}=await t3(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(tp(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 t3(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 t3(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 tv("You must provide either an email or phone number and a type")}catch(e){if(tp(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(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"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let t=null,r=await tH(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
2id"),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 tH(this.userStorage,this.storageKey+"-user");(null==e?void 0:e.user)?t.user=e.user:t.user=t0()}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){if(e)return await this._getUser(e);await this.initializePromise;let t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{if(e)return await t3(this.fetch,"GET","".concat(this.url,"/user"),{headers:this.headers,jwt:e,xform:t7});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 t3(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:t7}):{data:{user:null},error:new ty}})}catch(e){if(tp(e))return tb(e)&&(await this._removeSession(),await tW(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,await this._acquireLock(this.lockAcquireTimeout,async()=>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 ty;let i=s.session,a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await tY(this.storage,this.storageKey));let{data:l,error:c}=await t3(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:t7});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 tW(this.storage,"".concat(this.storageKey,"-code-verifier")),tp(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ty;let t=Date.now()/1e3,r=t,s=!0,n=null,{payload:i}=tJ(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(tp(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{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 ty;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(tp(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){var r;try{if(!tL())throw new t_("No browser detected.");
2if(e.error||e.error_description||e.error_code)throw new t_(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 tk("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new t_("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new tk("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 t_("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(tp(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await tH(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,await this._acquireLock(this.lockAcquireTimeout,async()=>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&&!tb(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&&!(tp(t)&&"AuthApiError"===t.name&&(404===t.status||401===t.status||403===t.status)||tb(t)))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await tW(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,await this._acquireLock(this.lockAcquireTimeout,async()=>{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),tb(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 tY(this.storage,this.storageKey,!0));try{return await t3(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 tW(this.storage,"".concat(this.storageKey,"-code-verifier")),tp(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(tp(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 t3(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!tL()||(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(tp(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 t3(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:t4});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 tw});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 tW(this.storage,"".concat(this.storageKey,"-code-verifier")),tp(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;
2return await t3(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(tp(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t="#_refreshAccessToken(".concat(e.substring(0,5),"...)");this._debug(t,"begin");try{var r,s;let n=Date.now();return await (r=async r=>(r>0&&await tF(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await t3(this.fetch,"POST","".concat(this.url,"/token?grant_type=refresh_token"),{body:{refresh_token:e},headers:this.headers,xform:t4})),s=(e,t)=>{let r=200*Math.pow(2,e);return t&&tE(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),tp(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),tL()&&!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 tH(this.storage,this.storageKey);if(s&&this.userStorage){let t=await tH(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!t&&(t={user:s.user},await tM(this.userStorage,this.storageKey+"-user",t)),s.user=null!=(e=null==t?void 0:t.user)?e:t0()}else if(s&&!s.user&&!s.user){let e=await tH(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await tW(this.storage,this.storageKey+"-user"),await tM(this.storage,this.storageKey,s)):s.user=t0()}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&&(console.error(e),tE(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 ty;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s="#_callRefreshToken(".concat(e.substring(0,5),"...)");this._debug(s,"begin");try{this.refreshingDeferred=new tK;let{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new ty;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);let s={data:t.session,error:null};return this.refreshingDeferred.resolve(s),s}catch(e){if(this._debug(s,"error",e),tp(e)){let r={data:null,error:e};return tE(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 tW(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 tM(this.userStorage,this.storageKey+"-user",{user:t.user});let e=Object.assign({},t);delete e.user;let s=t1(e);await tM(this.storage,this.storageKey,s)}else{let e=t1(t);await tM(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await tW(this.storage,this.storageKey),await tW(this.storage,this.storageKey+"-code-verifier"),await tW(this.storage,this.storageKey+"-user"),this.userStorage&&await tW(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&tL()&&(null==window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}
2catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),3e4);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let s=Math.floor((1e3*r.expires_at-e)/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 ro)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!tL()||!(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,")");this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"!==document.visibilityState?this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting"):await this._recoverAndRefresh()}))):"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 tY(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 t3(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(tp(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 t3(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(tp(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{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?rm(e.webauthn.credential_response):ry(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await t3(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(tp(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});let i=await t3(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:rf(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:rg(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(tp(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){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}=tJ(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(tp(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:i},error:a}
2=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}=tJ(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 t3(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 ty})})}catch(e){if(tp(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 ty});let i=await t3(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&&tL()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(tp(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 ty});let i=await t3(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&&tL()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(tp(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 t3(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 ty})})}catch(e){if(tp(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 t3(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 ty})})}catch(e){if(tp(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 t3(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{var r;let s,n=e;if(!n){let{data:e,error:t}
2=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});n=e.session.access_token}let{header:i,payload:a,signature:o,raw:{header:l,payload:c}}=tJ(n);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}(a.exp);let h=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks);if(!h){let{error:e}=await this.getUser(n);if(e)throw e;return{data:{claims:a,header:i,signature:o},error:null}}let u=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")}}(i.alg),d=await crypto.subtle.importKey("jwk",h,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,(r="".concat(l,".").concat(c),s=[],!function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127)return t(e);if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error("Unrecognized Unicode codepoint: ".concat(e.toString(16)))}(s,t)}}(r,e=>s.push(e)),new Uint8Array(s))))throw new tR("Invalid JWT signature");return{data:{claims:a,header:i,signature:o},error:null}}catch(e){if(tp(e))return this._returnResult({data:null,error:e});throw e}}async signInWithPasskey(e){var t,r,s;tZ(this.experimental);try{if(!rw())return this._returnResult({data:null,error:new tg("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=rg(n.options),o=null!=(s=null==(r=null==e?void 0:e.options)?void 0:r.signal)?s:rp.createNewAbortSignal(),{data:l,error:c}=await r_({publicKey:a,signal:o});if(c||!l)return this._returnResult({data:null,error:null!=c?c:new tg("WebAuthn ceremony failed",null)});let h=ry(l);return this._verifyPasskeyAuthentication({challengeId:n.challenge_id,credential:h})}catch(e){if(tp(e))return this._returnResult({data:null,error:e});throw e}}async registerPasskey(e){var t,r;tZ(this.experimental);try{if(!rw())return this._returnResult({data:null,error:new tg("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=rf(s.options),a=null!=(r=null==(t=null==e?void 0:e.options)?void 0:t.signal)?r:rp.createNewAbortSignal(),{data:o,error:l}=await rv({publicKey:i,signal:a});if(l||!o)return this._returnResult({data:null,error:null!=l?l:new tg("WebAuthn ceremony failed",null)});let c=rm(o);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:c})}catch(e){if(tp(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyRegistration(){tZ(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 ty});let{data:s,error:n}=await t3(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(tp(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){tZ(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 ty});let{data:n,error:i}=await t3(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(tp(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyAuthentication(e){var t;tZ(this.experimental);try{let{data:r,error:s}=await t3(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(tp(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyAuthentication(e){tZ(this.experimental);try{let{data:t,error:r}=await t3(this.fetch,"POST","".concat(this.url,"/passkeys/authentication/verify"),{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:t4});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(tp(e))return this._returnResult({data:null,error:e});throw e}}async _listPasskeys(){tZ(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 ty});let{data:s,error:n}=await t3(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(tp(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){tZ(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 ty});let{data:n,error:i}=await t3(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(tp(e))return this._returnResult({data:null,error:e});throw e}}async _deletePasskey(e){tZ(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 ty});let{error:n}
2=await t3(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(tp(e))return this._returnResult({data:null,error:e});throw e}}constructor(e){var t,r,s,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},rA),e);if(this.storageKey=i.storageKey,this.instanceID=null!=(t=rC.nextInstanceID[this.storageKey])?t:0,rC.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,"function"==typeof i.debug&&(this.logger=i.debug),this.instanceID>0&&tL()){const e="".concat(this._logPrefix()," Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=null!=(r=i.experimental)?r:{},this.admin=new rn({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=tq(i.fetch),this.lock=i.lock||rR,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&tL()&&(null==(s=null==globalThis?void 0:globalThis.navigator)?void 0:s.locks)?this.lock=rc:this.lock=rR,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 rE(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?(i.storage?this.storage=i.storage:tB()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=ri(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=ri(this.memoryStorage)),tL()&&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==(n=this.broadcastChannel)||n.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)}})}i.skipAutoInitialize||this.initialize().catch(e=>{this._debug("#initialize()","error",e)})}}rC.nextInstanceID={};let rj=rC,rP="";rP="u">typeof Deno?"deno":"u">typeof document?"web":"u">typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";let rI={headers:{"X-Client-Info":"supabase-js-".concat(rP,"/").concat("2.105.3")}},rx={schema:"public"},rN={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},rU={};function rL(e){return(rL="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 rD(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 rB(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};
2t%2?rD(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=rL(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=rL(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==rL(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)):rD(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var rq=class extends rj{constructor(e){super(e)}},rM=class{get functions(){return new v(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 rq({url:this.authUrl.href,headers:rB(rB({},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 eO(this.realtimeUrl.href,rB(rB({},e),{},{params:rB(rB({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){("TOKEN_REFRESHED"===e||"SIGNED_IN"===e)&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0)}constructor(e,t,r){var s,n,i;this.supabaseUrl=e,this.supabaseKey=t;const a=function(e){let t=null==e?void 0:e.trim();if(!t)throw Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(t.endsWith("/")?t:t+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}(e);if(!t)throw Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const o="sb-".concat(a.hostname.split(".")[0],"-auth-token"),l=function(e,t){var r,s;let{db:n,auth:i,realtime:a,global:o}=e,{db:l,auth:c,realtime:h,global:u}=t,d={db:rB(rB({},l),n),auth:rB(rB({},c),i),realtime:rB(rB({},h),a),storage:{},global:rB(rB(rB({},u),o),{},{headers:rB(rB({},null!=(r=null==u?void 0:u.headers)?r:{}),null!=(s=null==o?void 0:o.headers)?s:{})}),accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(null!=r?r:{},{db:rx,realtime:rU,auth:rB(rB({},rN),{},{storageKey:o}),global:rI});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)=>{let s=r?function(){for(var e=arguments.length,t=Array(e),s=0;s<e;s++)t[s]=arguments[s];return r(...t)}:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return fetch(...t)},n=Headers;return async(r,i)=>{var a;let o=null!=(a=await t())?a:e,l=new n(null==i?void 0:i.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization","Bearer ".concat(o)),s(r,rB(rB({},i),{},{headers:l}))}})(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(rB({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 N(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 to(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}};(function(){if("u">typeof window)return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(null==t)return!1;let r=t.match(/^v(\d+)\./);return!!r&&18>=parseInt(r[1],10)})()&&console.warn("⚠️  Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to N
2ode.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");let rH="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),rW=" 	\n\r=".split(""),rK=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<rW.length;t+=1)e[rW[t].charCodeAt(0)]=-2;for(let t=0;t<rH.length;t+=1)e[rH[t].charCodeAt(0)]=t;return e})();function rJ(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>>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=>{for(r=r<<8|e,s+=8;s>=6;){let e=r>>s-6&63;t.push(rH[e]),s-=6}}),s>0)for(r<<=6-s,s=6;s>=6;){let e=r>>s-6&63;t.push(rH[e]),s-=6}return t.join("")}function rF(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=rK[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("")}var rz=e.i(909156);function rG(){return"u">typeof window&&void 0!==window.document}rz.parse,rz.serialize;let rV={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4},rY=/^(.*)[.](0|[1-9][0-9]*)$/;function r$(e,t){if(e===t)return!0;let r=e.match(rY);return!!r&&r[1]===t}function rX(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 rQ(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 rZ="base64-";async function r0(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=>r$(t,e))),d=Object.keys(i).flatMap(e=>{let t=new Set(h.filter(t=>r$(t,e))),r=i[e];"base64url"===o&&(r=rZ+rJ(r));let s=rX(e,r);return s.forEach(e=>{t.delete(e.name)}),u.push(...t),s}),p={...rV,...l,maxAge:0},f={...rV,...l,maxAge:rV.maxAge};delete p.name,delete f.name,await n([...u.map(e=>({name:e,value:"",options:p})),...d.map(e=>{let{name:t,value:r}=e;return{name:t,value:r,options:f}})])}e.s(["createBrowserSupabaseClient",0,function(){let e="https://birfgggolfqanmsfciqi.supabase.co".trim(),t="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImJpcmZnZ2dvbGZxYW5tc2ZjaXFpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzgwOTQxMDQsImV4cCI6MjA5MzY3MDEwNH0.0_0C1FbGFsJeKruZuT4pbkrhMko3aQ7folE_h8OlCMs".trim();return e&&t?function(e,t){let s=rG();if(s&&r)return r;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:n}=function(e,t){var r;let s,n,i=null!=(r=e.cookies)?r:null,a=e.cookieEncoding,o={},l={};if(i)if("get"in i){let e=async e=>{let t=e.flatMap(e=>[e,...Array.from({length:5}).map((t,r)=>"".concat(e,".").concat(r))]),r=[];for(let e=0;e<t.length;e+=1){let s=await i.get(t[e]);(s||"string"==typeof s)&&r.push({name:t[e],value:s})}return r};if(s=async t=>await e(t),"set"in i&&"remove"in i)n=async e=>{for(let t=0;t<e.length;t+=1){let{name:r,value:s,options:n}=e[t];s?await i.set(r,s,n):await i.remove(r,n)}};else if(t)n=async()=>{console.warn("@supabase/ssr: createServerClient was configured without set and remove cookie methods, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for c
2orrectness. 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 throw Error("@supabase/ssr: ".concat(t?"createServerClient":"createBrowserClient"," requires configuring getAll and setAll cookie methods (deprecated: alternatively use get, set and remove).").concat(rG()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""));else if(!t&&rG())s=()=>{let e;return Object.keys(e=(0,rz.parse)(document.cookie)).map(t=>{var r;return{name:t,value:null!=(r=e[t])?r:""}})},n=e=>{e.forEach(e=>{let{name:t,value:r,options:s}=e;document.cookie=(0,rz.serialize)(t,r,s)})};else if(t)throw Error("@supabase/ssr: createServerClient must be initialized with cookie options that specify getAll and setAll functions (deprecated, not recommended: alternatively use get, set and remove)");else s=()=>[],n=()=>{throw Error("@supabase/ssr: createBrowserClient in non-browser runtimes (including Next.js pre-rendering mode) was not initialized cookie options that specify getAll and setAll functions (deprecated: alternatively use get, set and remove), but they were needed")};return t?{getAll:s,setAll:n,setItems:o,removedItems:l,storage:{isServer:!0,getItem:async e=>{if("string"==typeof o[e])return o[e];if(l[e])return null;let t=await s([e]),r=await rQ(e,async e=>{let r=(null==t?void 0:t.find(t=>{let{name:r}=t;return r===e}))||null;return r?r.value:null});if(!r)return null;let n=r;return"string"==typeof r&&r.startsWith(rZ)&&(n=rF(r.substring(rZ.length))),n},setItem:async(t,r)=>{if(t.endsWith("-code-verifier")){var i;await r0({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 rQ(e,async e=>{let r=(null==t?void 0:t.find(t=>{let{name:r}=t;return r===e}))||null;return r?r.value:null});if(!r)return null;let n=r;return r.startsWith(rZ)&&(n=rF(r.substring(rZ.length))),n},setItem:async(t,r)=>{let i=await s([t]),o=new Set(((null==i?void 0:i.map(e=>{let{name:t}=e;return t}))||[]).filter(e=>r$(e,t))),l=r;"base64url"===a&&(l=rZ+rJ(r));let c=rX(t,l);c.forEach(e=>{let{name:t}=e;o.delete(t)});let h={...rV,...null==e?void 0:e.cookieOptions,maxAge:0},u={...rV,...null==e?void 0:e.cookieOptions,maxAge:rV.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=>r$(e,t)),a={...rV,...null==e?void 0:e.cookieOptions,maxAge:0};delete a.name,i.length>0&&await n(i.map(e=>({name:e,value:"",options:a})))}}}}({...void 0,cookieEncoding:"base64url"},!1),i=new rM(e,t,{...void 0,global:{...void 0,headers:{...void 0,"X-Client-Info":"supabase-ssr/".concat("0.6.1"," createBrowserClient")}},auth:{...void 0,...null,flowType:"pkce",autoRefreshToken:rG(),detectSessionInUrl:rG(),persistSession:!0,storage:n}});return s&&(r=i),i}(e,t):null}],536662)}]);
3
4//# debugId=f9f501bb-a42e-b078-d4b7-0d576c82c9b2

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.