59 lines
218 KiB
JavaScript
59 lines
218 KiB
JavaScript
"use strict";exports.id=21,exports.ids=[21],exports.modules={14230:(a,b,c)=>{Object.defineProperty(b,"U",{enumerable:!0,get:function(){return n}});let d=c(28706),e=c(33675),f=c(29294),g=c(63033),h=c(26906),i=c(11938),j=c(82831),k=c(30787),l=c(31716),m=c(49290);function n(){let a="cookies",b=f.workAsyncStorage.getStore(),c=g.workUnitAsyncStorage.getStore();if(b){if(c&&"after"===c.phase&&!(0,l.isRequestAPICallableInsideAfter)())throw Object.defineProperty(Error(`Route ${b.route} used "cookies" inside "after(...)". This is not supported. If you need this data inside an "after" callback, use "cookies" outside of the callback. See more info here: https://nextjs.org/docs/canary/app/api-reference/functions/after`),"__NEXT_ERROR_CODE",{value:"E88",enumerable:!1,configurable:!0});if(b.forceStatic)return p(d.RequestCookiesAdapter.seal(new e.RequestCookies(new Headers({}))));if(b.dynamicShouldError)throw Object.defineProperty(new i.StaticGenBailoutError(`Route ${b.route} with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`),"__NEXT_ERROR_CODE",{value:"E549",enumerable:!1,configurable:!0});if(c)switch(c.type){case"cache":let f=Object.defineProperty(Error(`Route ${b.route} used "cookies" inside "use cache". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`),"__NEXT_ERROR_CODE",{value:"E398",enumerable:!1,configurable:!0});throw Error.captureStackTrace(f,n),b.invalidDynamicUsageError??=f,f;case"unstable-cache":throw Object.defineProperty(Error(`Route ${b.route} used "cookies" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "cookies" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`),"__NEXT_ERROR_CODE",{value:"E157",enumerable:!1,configurable:!0});case"prerender":var k=b,q=c;let g=o.get(q);if(g)return g;let r=(0,j.makeHangingPromise)(q.renderSignal,k.route,"`cookies()`");return o.set(q,r),r;case"prerender-client":let s="`cookies`";throw Object.defineProperty(new m.InvariantError(`${s} must not be used within a client component. Next.js should be preventing ${s} from being included in client components statically, but did not in this case.`),"__NEXT_ERROR_CODE",{value:"E693",enumerable:!1,configurable:!0});case"prerender-ppr":return(0,h.postponeWithTracking)(b.route,a,c.dynamicTracking);case"prerender-legacy":return(0,h.throwToInterruptStaticGeneration)(a,b,c);case"prerender-runtime":return(0,h.delayUntilRuntimeStage)(c,function(a){let b=o.get(a);if(b)return b;let c=Promise.resolve(a);return o.set(a,c),c}(c.cookies));case"private-cache":return p(c.cookies);case"request":return(0,h.trackDynamicDataInDynamicRender)(c),p((0,d.areCookiesMutableInCurrentPhase)(c)?c.userspaceMutableCookies:c.cookies)}}(0,g.throwForMissingRequestStore)(a)}c(63036);let o=new WeakMap;function p(a){let b=o.get(a);if(b)return b;let c=Promise.resolve(a);return o.set(a,c),Object.defineProperties(c,{[Symbol.iterator]:{value:a[Symbol.iterator]?a[Symbol.iterator].bind(a):q.bind(a)},size:{get:()=>a.size},get:{value:a.get.bind(a)},getAll:{value:a.getAll.bind(a)},has:{value:a.has.bind(a)},set:{value:a.set.bind(a)},delete:{value:a.delete.bind(a)},clear:{value:"function"==typeof a.clear?a.clear.bind(a):r.bind(a,c)},toString:{value:a.toString.bind(a)}}),c}function q(){return this.getAll().map(a=>[a.name,a]).values()}function r(a){for(let a of this.getAll())this.delete(a.name);return a}(0,k.createDedupedByCallsiteServerErrorLoggerDev)(function(a,b){let c=a?`Route "${a}" `:"This route ";return Object.defineProperty(Error(`${c}used ${b}. \`cookies()\` should be awaited before using its value. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`),"__NEXT_ERROR_CODE",{value:"E223",enumerable:!1,configurable:!0})})},28706:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0}),!function(a,b){for(var c in b)Object.defineProperty(a,c,{enumerable:!0,get:b[c]})}(b,{MutableRequestCookiesAdapter:function(){return l},ReadonlyRequestCookiesError:function(){return g},RequestCookiesAdapter:function(){return h},appendMutableCookies:function(){return k},areCookiesMutableInCurrentPhase:function(){return n},createCookiesWithMutableAccessCheck:function(){return m},getModifiedCookieValues:function(){return j},responseCookiesToRequestCookies:function(){return p}});let d=c(33675),e=c(63036),f=c(29294);class g extends Error{constructor(){super("Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options")}static callable(){throw new g}}class h{static seal(a){return new Proxy(a,{get(a,b,c){switch(b){case"clear":case"delete":case"set":return g.callable;default:return e.ReflectAdapter.get(a,b,c)}}})}}let i=Symbol.for("next.mutated.cookies");function j(a){let b=a[i];return b&&Array.isArray(b)&&0!==b.length?b:[]}function k(a,b){let c=j(b);if(0===c.length)return!1;let e=new d.ResponseCookies(a),f=e.getAll();for(let a of c)e.set(a);for(let a of f)e.set(a);return!0}class l{static wrap(a,b){let c=new d.ResponseCookies(new Headers);for(let b of a.getAll())c.set(b);let g=[],h=new Set,j=()=>{let a=f.workAsyncStorage.getStore();if(a&&(a.pathWasRevalidated=!0),g=c.getAll().filter(a=>h.has(a.name)),b){let a=[];for(let b of g){let c=new d.ResponseCookies(new Headers);c.set(b),a.push(c.toString())}b(a)}},k=new Proxy(c,{get(a,b,c){switch(b){case i:return g;case"delete":return function(...b){h.add("string"==typeof b[0]?b[0]:b[0].name);try{return a.delete(...b),k}finally{j()}};case"set":return function(...b){h.add("string"==typeof b[0]?b[0]:b[0].name);try{return a.set(...b),k}finally{j()}};default:return e.ReflectAdapter.get(a,b,c)}}});return k}}function m(a){let b=new Proxy(a.mutableCookies,{get(c,d,f){switch(d){case"delete":return function(...d){return o(a,"cookies().delete"),c.delete(...d),b};case"set":return function(...d){return o(a,"cookies().set"),c.set(...d),b};default:return e.ReflectAdapter.get(c,d,f)}}});return b}function n(a){return"action"===a.phase}function o(a,b){if(!n(a))throw new g}function p(a){let b=new d.RequestCookies(new Headers);for(let c of a.getAll())b.set(c);return b}},34603:(a,b,c)=>{let d=c(67675),e=c(29294),f=c(63033),g=c(26906),h=c(11938),i=c(82831),j=c(30787),k=c(31716),l=c(49290);c(63036);new WeakMap;(0,j.createDedupedByCallsiteServerErrorLoggerDev)(function(a,b){let c=a?`Route "${a}" `:"This route ";return Object.defineProperty(Error(`${c}used ${b}. \`headers()\` should be awaited before using its value. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`),"__NEXT_ERROR_CODE",{value:"E277",enumerable:!1,configurable:!0})})},35916:(a,b,c)=>{let d=c(63033),e=c(29294),f=c(26906),g=c(30787),h=c(11938),i=c(69168),j=c(49290);c(63036);new WeakMap;(0,g.createDedupedByCallsiteServerErrorLoggerDev)(function(a,b){let c=a?`Route "${a}" `:"This route ";return Object.defineProperty(Error(`${c}used ${b}. \`draftMode()\` should be awaited before using its value. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`),"__NEXT_ERROR_CODE",{value:"E377",enumerable:!1,configurable:!0})})},67596:(a,b,c)=>{let d;c.d(b,{createServerClient:()=>cV});var e,f,g,h,i,j,k=c(94134);function l(){return"undefined"!=typeof window&&void 0!==window.document}k.qg,k.lK;let m={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4},n=/^(.*)[.](0|[1-9][0-9]*)$/;function o(a,b){if(a===b)return!0;let c=a.match(n);return!!c&&c[1]===b}function p(a,b,c){let d=c??3180,e=encodeURIComponent(b);if(e.length<=d)return[{name:a,value:b}];let f=[];for(;e.length>0;){let a=e.slice(0,d),b=a.lastIndexOf("%");b>d-3&&(a=a.slice(0,b));let c="";for(;a.length>0;)try{c=decodeURIComponent(a);break}catch(b){if(b instanceof URIError&&"%"===a.at(-3)&&a.length>3)a=a.slice(0,a.length-3);else throw b}f.push(c),e=e.slice(a.length)}return f.map((b,c)=>({name:`${a}.${c}`,value:b}))}async function q(a,b){let c=await b(a);if(c)return c;let d=[];for(let c=0;;c++){let e=`${a}.${c}`,f=await b(e);if(!f)break;d.push(f)}return d.length>0?d.join(""):null}let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),s=" \n\r=".split(""),t=(()=>{let a=Array(128);for(let b=0;b<a.length;b+=1)a[b]=-1;for(let b=0;b<s.length;b+=1)a[s[b].charCodeAt(0)]=-2;for(let b=0;b<r.length;b+=1)a[r[b].charCodeAt(0)]=b;return a})();function u(a){let b=[],c=0,d=0;if(function(a,b){for(let c=0;c<a.length;c+=1){let d=a.charCodeAt(c);if(d>55295&&d<=56319){let b=(d-55296)*1024&65535;d=(a.charCodeAt(c+1)-56320&65535|b)+65536,c+=1}!function(a,b){if(a<=127)return b(a);if(a<=2047){b(192|a>>6),b(128|63&a);return}if(a<=65535){b(224|a>>12),b(128|a>>6&63),b(128|63&a);return}if(a<=1114111){b(240|a>>18),b(128|a>>12&63),b(128|a>>6&63),b(128|63&a);return}throw Error(`Unrecognized Unicode codepoint: ${a.toString(16)}`)}(d,b)}}(a,a=>{for(c=c<<8|a,d+=8;d>=6;){let a=c>>d-6&63;b.push(r[a]),d-=6}}),d>0)for(c<<=6-d,d=6;d>=6;){let a=c>>d-6&63;b.push(r[a]),d-=6}return b.join("")}function v(a){let b=[],c=a=>{b.push(String.fromCodePoint(a))},d={utf8seq:0,codepoint:0},e=0,f=0;for(let b=0;b<a.length;b+=1){let g=t[a.charCodeAt(b)];if(g>-1)for(e=e<<6|g,f+=6;f>=8;)(function(a,b,c){if(0===b.utf8seq){if(a<=127)return c(a);for(let c=1;c<6;c+=1)if((a>>7-c&1)==0){b.utf8seq=c;break}if(2===b.utf8seq)b.codepoint=31&a;else if(3===b.utf8seq)b.codepoint=15&a;else if(4===b.utf8seq)b.codepoint=7&a;else throw Error("Invalid UTF-8 sequence");b.utf8seq-=1}else if(b.utf8seq>0){if(a<=127)throw Error("Invalid UTF-8 sequence");b.codepoint=b.codepoint<<6|63&a,b.utf8seq-=1,0===b.utf8seq&&c(b.codepoint)}})(e>>f-8&255,d,c),f-=8;else if(-2===g)continue;else throw Error(`Invalid Base64-URL character "${a.at(b)}" at position ${b}`)}return b.join("")}let w="base64-";async function x({getAll:a,setAll:b,setItems:c,removedItems:d},e){let f=e.cookieEncoding,g=e.cookieOptions??null,h=await a([...c?Object.keys(c):[],...d?Object.keys(d):[]]),i=h?.map(({name:a})=>a)||[],j=Object.keys(d).flatMap(a=>i.filter(b=>o(b,a))),k=Object.keys(c).flatMap(a=>{let b=new Set(i.filter(b=>o(b,a))),d=c[a];"base64url"===f&&(d=w+u(d));let e=p(a,d);return e.forEach(a=>{b.delete(a.name)}),j.push(...b),e}),l={...m,...g,maxAge:0},n={...m,...g,maxAge:m.maxAge};delete l.name,delete n.name,await b([...j.map(a=>({name:a,value:"",options:l})),...k.map(({name:a,value:b})=>({name:a,value:b,options:n}))],{"Cache-Control":"private, no-cache, no-store, must-revalidate, max-age=0",Expires:"0",Pragma:"no-cache"})}function y(a,b){var c={};for(var d in a)Object.prototype.hasOwnProperty.call(a,d)&&0>b.indexOf(d)&&(c[d]=a[d]);if(null!=a&&"function"==typeof Object.getOwnPropertySymbols)for(var e=0,d=Object.getOwnPropertySymbols(a);e<d.length;e++)0>b.indexOf(d[e])&&Object.prototype.propertyIsEnumerable.call(a,d[e])&&(c[d[e]]=a[d[e]]);return c}Object.create;Object.create,"function"==typeof SuppressedError&&SuppressedError;class z extends Error{constructor(a,b="FunctionsError",c){super(a),this.name=b,this.context=c}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class A extends z{constructor(a){super("Failed to send a request to the Edge Function","FunctionsFetchError",a)}}class B extends z{constructor(a){super("Relay Error invoking the Edge Function","FunctionsRelayError",a)}}class C extends z{constructor(a){super("Edge Function returned a non-2xx status code","FunctionsHttpError",a)}}!function(a){a.Any="any",a.ApNortheast1="ap-northeast-1",a.ApNortheast2="ap-northeast-2",a.ApSouth1="ap-south-1",a.ApSoutheast1="ap-southeast-1",a.ApSoutheast2="ap-southeast-2",a.CaCentral1="ca-central-1",a.EuCentral1="eu-central-1",a.EuWest1="eu-west-1",a.EuWest2="eu-west-2",a.EuWest3="eu-west-3",a.SaEast1="sa-east-1",a.UsEast1="us-east-1",a.UsWest1="us-west-1",a.UsWest2="us-west-2"}(e||(e={}));class D{constructor(a,{headers:b={},customFetch:c,region:d=e.Any}={}){this.url=a,this.headers=b,this.region=d,this.fetch=(a=>a?(...b)=>a(...b):(...a)=>fetch(...a))(c)}setAuth(a){this.headers.Authorization=`Bearer ${a}`}invoke(a){var b,c,d,e;return b=this,c=arguments,d=void 0,e=function*(a,b={}){var c;let d,e;try{let f,{headers:g,method:h,body:i,signal:j,timeout:k}=b,l={},{region:m}=b;m||(m=this.region);let n=new URL(`${this.url}/${a}`);m&&"any"!==m&&(l["x-region"]=m,n.searchParams.set("forceFunctionRegion",m)),i&&(g&&!Object.prototype.hasOwnProperty.call(g,"Content-Type")||!g)?"undefined"!=typeof Blob&&i instanceof Blob||i instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",f=i):"string"==typeof i?(l["Content-Type"]="text/plain",f=i):"undefined"!=typeof FormData&&i instanceof FormData?f=i:(l["Content-Type"]="application/json",f=JSON.stringify(i)):f=!i||"string"==typeof i||"undefined"!=typeof Blob&&i instanceof Blob||i instanceof ArrayBuffer||"undefined"!=typeof FormData&&i instanceof FormData?i:JSON.stringify(i);let o=j;k&&(e=new AbortController,d=setTimeout(()=>e.abort(),k),j?(o=e.signal,j.addEventListener("abort",()=>e.abort())):o=e.signal);let p=yield this.fetch(n.toString(),{method:h||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),g),body:f,signal:o}).catch(a=>{throw new A(a)}),q=p.headers.get("x-relay-error");if(q&&"true"===q)throw new B(p);if(!p.ok)throw new C(p);let r=(null!=(c=p.headers.get("Content-Type"))?c:"text/plain").split(";")[0].trim();return{data:"application/json"===r?yield p.json():"application/octet-stream"===r||"application/pdf"===r?yield p.blob():"text/event-stream"===r?p:"multipart/form-data"===r?yield p.formData():yield p.text(),error:null,response:p}}catch(a){return{data:null,error:a,response:a instanceof C||a instanceof B?a.context:void 0}}finally{d&&clearTimeout(d)}},new(d||(d=Promise))(function(a,f){function g(a){try{i(e.next(a))}catch(a){f(a)}}function h(a){try{i(e.throw(a))}catch(a){f(a)}}function i(b){var c;b.done?a(b.value):((c=b.value)instanceof d?c:new d(function(a){a(c)})).then(g,h)}i((e=e.apply(b,c||[])).next())})}}let E=a=>Math.min(1e3*2**a,3e4),F=[520,503],G=["GET","HEAD","OPTIONS"];var H=class extends Error{constructor(a){super(a.message),this.name="PostgrestError",this.details=a.details,this.hint=a.hint,this.code=a.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function I(a,b){return new Promise(c=>{if(null==b?void 0:b.aborted)return void c();let d=setTimeout(()=>{null==b||b.removeEventListener("abort",e),c()},a);function e(){clearTimeout(d),c()}null==b||b.addEventListener("abort",e)})}var J=class{constructor(a){var b,c,d,e,f;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=a.method,this.url=a.url,this.headers=new Headers(a.headers),this.schema=a.schema,this.body=a.body,this.shouldThrowOnError=null!=(b=a.shouldThrowOnError)&&b,this.signal=a.signal,this.isMaybeSingle=null!=(c=a.isMaybeSingle)&&c,this.shouldStripNulls=null!=(d=a.shouldStripNulls)&&d,this.urlLengthLimit=null!=(e=a.urlLengthLimit)?e:8e3,this.retryEnabled=null==(f=a.retry)||f,a.fetch?this.fetch=a.fetch:this.fetch=fetch}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(a,b){return this.headers=new Headers(this.headers),this.headers.set(a,b),this}retry(a){return this.retryEnabled=a,this}then(a,b){var c=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 a=this.headers.get("Accept");"application/vnd.pgrst.object+json"===a?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):a&&"application/json"!==a||this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let d=this.fetch,e=(async()=>{let a=0;for(;;){var b,e,f,g,h;let i,j=new Headers(c.headers);a>0&&j.set("X-Retry-Count",String(a));try{i=await d(c.url.toString(),{method:c.method,headers:j,body:JSON.stringify(c.body,(a,b)=>"bigint"==typeof b?b.toString():b),signal:c.signal})}catch(b){if(b instanceof Error&&("AbortError"===b.name||"code"in b&&"ABORT_ERR"===b.code)||!G.includes(c.method))throw b;if(c.retryEnabled&&a<3){let b=E(a);a++,await I(b,c.signal);continue}throw b}if(b=c.method,e=i.status,f=a,c.retryEnabled&&!(f>=3)&&G.includes(b)&&F.includes(e)&&1){let b=null!=(g=null==(h=i.headers)?void 0:h.get("Retry-After"))?g:null,d=null!==b?1e3*Math.max(0,parseInt(b,10)||0):E(a);await i.text(),a++,await I(d,c.signal);continue}return await c.processResponse(i)}})();return this.shouldThrowOnError||(e=e.catch(a=>{var b,c,d,e,f,g;let h="",i="",j="",k=null==a?void 0:a.cause;if(k){let b=null!=(c=null==k?void 0:k.message)?c:"",g=null!=(d=null==k?void 0:k.code)?d:"";h=`${null!=(e=null==a?void 0:a.name)?e:"FetchError"}: ${null==a?void 0:a.message}
|
|
|
|
Caused by: ${null!=(f=null==k?void 0:k.name)?f:"Error"}: ${b}`,g&&(h+=` (${g})`),(null==k?void 0:k.stack)&&(h+=`
|
|
${k.stack}`)}else h=null!=(g=null==a?void 0:a.stack)?g:"";let l=this.url.toString().length;return(null==a?void 0:a.name)==="AbortError"||(null==a?void 0:a.code)==="ABORT_ERR"?(j="",i="Request was aborted (timeout or manual cancellation)",l>this.urlLengthLimit&&(i+=`. Note: Your request URL is ${l} 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==k?void 0:k.name)==="HeadersOverflowError"||(null==k?void 0:k.code)==="UND_ERR_HEADERS_OVERFLOW")&&(j="",i="HTTP headers exceeded server limits (typically 16KB)",l>this.urlLengthLimit&&(i+=`. Your request URL is ${l} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${null!=(b=null==a?void 0:a.name)?b:"FetchError"}: ${null==a?void 0:a.message}`,details:h,hint:i,code:j},data:null,count:null,status:0,statusText:""}})),e.then(a,b)}async processResponse(a){var b,c,d;let e=null,f=null,g=null,h=a.status,i=a.statusText;if(a.ok){if("HEAD"!==this.method){let b=await a.text();""===b||(f="text/csv"===this.headers.get("Accept")||this.headers.get("Accept")&&(null==(d=this.headers.get("Accept"))?void 0:d.includes("application/vnd.pgrst.plan+text"))?b:JSON.parse(b))}let j=null==(b=this.headers.get("Prefer"))?void 0:b.match(/count=(exact|planned|estimated)/),k=null==(c=a.headers.get("content-range"))?void 0:c.split("/");j&&k&&k.length>1&&(g=parseInt(k[1])),this.isMaybeSingle&&Array.isArray(f)&&(f.length>1?(e={code:"PGRST116",details:`Results contain ${f.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},f=null,g=null,h=406,i="Not Acceptable"):f=1===f.length?f[0]:null)}else{let b=await a.text();try{e=JSON.parse(b),Array.isArray(e)&&404===a.status&&(f=[],e=null,h=200,i="OK")}catch(c){404===a.status&&""===b?(h=204,i="No Content"):e={message:b}}if(e&&this.shouldThrowOnError)throw new H(e)}return{success:null===e,error:e,data:f,count:g,status:h,statusText:i}}returns(){return this}overrideTypes(){return this}},K=class extends J{select(a){let b=!1,c=(null!=a?a:"*").split("").map(a=>/\s/.test(a)&&!b?"":('"'===a&&(b=!b),a)).join("");return this.url.searchParams.set("select",c),this.headers.append("Prefer","return=representation"),this}order(a,{ascending:b=!0,nullsFirst:c,foreignTable:d,referencedTable:e=d}={}){let f=e?`${e}.order`:"order",g=this.url.searchParams.get(f);return this.url.searchParams.set(f,`${g?`${g},`:""}${a}.${b?"asc":"desc"}${void 0===c?"":c?".nullsfirst":".nullslast"}`),this}limit(a,{foreignTable:b,referencedTable:c=b}={}){let d=void 0===c?"limit":`${c}.limit`;return this.url.searchParams.set(d,`${a}`),this}range(a,b,{foreignTable:c,referencedTable:d=c}={}){let e=void 0===d?"offset":`${d}.offset`,f=void 0===d?"limit":`${d}.limit`;return this.url.searchParams.set(e,`${a}`),this.url.searchParams.set(f,`${b-a+1}`),this}abortSignal(a){return this.signal=a,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:a=!1,verbose:b=!1,settings:c=!1,buffers:d=!1,wal:e=!1,format:f="text"}={}){var g;let h=[a?"analyze":null,b?"verbose":null,c?"settings":null,d?"buffers":null,e?"wal":null].filter(Boolean).join("|"),i=null!=(g=this.headers.get("Accept"))?g:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${f}; for="${i}"; options=${h};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(a){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${a}`),this}};let L=RegExp("[,()]");var M=class extends K{eq(a,b){return this.url.searchParams.append(a,`eq.${b}`),this}neq(a,b){return this.url.searchParams.append(a,`neq.${b}`),this}gt(a,b){return this.url.searchParams.append(a,`gt.${b}`),this}gte(a,b){return this.url.searchParams.append(a,`gte.${b}`),this}lt(a,b){return this.url.searchParams.append(a,`lt.${b}`),this}lte(a,b){return this.url.searchParams.append(a,`lte.${b}`),this}like(a,b){return this.url.searchParams.append(a,`like.${b}`),this}likeAllOf(a,b){return this.url.searchParams.append(a,`like(all).{${b.join(",")}}`),this}likeAnyOf(a,b){return this.url.searchParams.append(a,`like(any).{${b.join(",")}}`),this}ilike(a,b){return this.url.searchParams.append(a,`ilike.${b}`),this}ilikeAllOf(a,b){return this.url.searchParams.append(a,`ilike(all).{${b.join(",")}}`),this}ilikeAnyOf(a,b){return this.url.searchParams.append(a,`ilike(any).{${b.join(",")}}`),this}regexMatch(a,b){return this.url.searchParams.append(a,`match.${b}`),this}regexIMatch(a,b){return this.url.searchParams.append(a,`imatch.${b}`),this}is(a,b){return this.url.searchParams.append(a,`is.${b}`),this}isDistinct(a,b){return this.url.searchParams.append(a,`isdistinct.${b}`),this}in(a,b){let c=Array.from(new Set(b)).map(a=>"string"==typeof a&&L.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(a,`in.(${c})`),this}notIn(a,b){let c=Array.from(new Set(b)).map(a=>"string"==typeof a&&L.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(a,`not.in.(${c})`),this}contains(a,b){return"string"==typeof b?this.url.searchParams.append(a,`cs.${b}`):Array.isArray(b)?this.url.searchParams.append(a,`cs.{${b.join(",")}}`):this.url.searchParams.append(a,`cs.${JSON.stringify(b)}`),this}containedBy(a,b){return"string"==typeof b?this.url.searchParams.append(a,`cd.${b}`):Array.isArray(b)?this.url.searchParams.append(a,`cd.{${b.join(",")}}`):this.url.searchParams.append(a,`cd.${JSON.stringify(b)}`),this}rangeGt(a,b){return this.url.searchParams.append(a,`sr.${b}`),this}rangeGte(a,b){return this.url.searchParams.append(a,`nxl.${b}`),this}rangeLt(a,b){return this.url.searchParams.append(a,`sl.${b}`),this}rangeLte(a,b){return this.url.searchParams.append(a,`nxr.${b}`),this}rangeAdjacent(a,b){return this.url.searchParams.append(a,`adj.${b}`),this}overlaps(a,b){return"string"==typeof b?this.url.searchParams.append(a,`ov.${b}`):this.url.searchParams.append(a,`ov.{${b.join(",")}}`),this}textSearch(a,b,{config:c,type:d}={}){let e="";"plain"===d?e="pl":"phrase"===d?e="ph":"websearch"===d&&(e="w");let f=void 0===c?"":`(${c})`;return this.url.searchParams.append(a,`${e}fts${f}.${b}`),this}match(a){return Object.entries(a).filter(([a,b])=>void 0!==b).forEach(([a,b])=>{this.url.searchParams.append(a,`eq.${b}`)}),this}not(a,b,c){return this.url.searchParams.append(a,`not.${b}.${c}`),this}or(a,{foreignTable:b,referencedTable:c=b}={}){let d=c?`${c}.or`:"or";return this.url.searchParams.append(d,`(${a})`),this}filter(a,b,c){return this.url.searchParams.append(a,`${b}.${c}`),this}},N=class{constructor(a,{headers:b={},schema:c,fetch:d,urlLengthLimit:e=8e3,retry:f}){this.url=a,this.headers=new Headers(b),this.schema=c,this.fetch=d,this.urlLengthLimit=e,this.retry=f}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(a,b){let{head:c=!1,count:d}=null!=b?b:{},e=!1,f=(null!=a?a:"*").split("").map(a=>/\s/.test(a)&&!e?"":('"'===a&&(e=!e),a)).join(""),{url:g,headers:h}=this.cloneRequestState();return g.searchParams.set("select",f),d&&h.append("Prefer",`count=${d}`),new M({method:c?"HEAD":"GET",url:g,headers:h,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(a,{count:b,defaultToNull:c=!0}={}){var d;let{url:e,headers:f}=this.cloneRequestState();if(b&&f.append("Prefer",`count=${b}`),c||f.append("Prefer","missing=default"),Array.isArray(a)){let b=a.reduce((a,b)=>a.concat(Object.keys(b)),[]);if(b.length>0){let a=[...new Set(b)].map(a=>`"${a}"`);e.searchParams.set("columns",a.join(","))}}return new M({method:"POST",url:e,headers:f,schema:this.schema,body:a,fetch:null!=(d=this.fetch)?d:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(a,{onConflict:b,ignoreDuplicates:c=!1,count:d,defaultToNull:e=!0}={}){var f;let{url:g,headers:h}=this.cloneRequestState();if(h.append("Prefer",`resolution=${c?"ignore":"merge"}-duplicates`),void 0!==b&&g.searchParams.set("on_conflict",b),d&&h.append("Prefer",`count=${d}`),e||h.append("Prefer","missing=default"),Array.isArray(a)){let b=a.reduce((a,b)=>a.concat(Object.keys(b)),[]);if(b.length>0){let a=[...new Set(b)].map(a=>`"${a}"`);g.searchParams.set("columns",a.join(","))}}return new M({method:"POST",url:g,headers:h,schema:this.schema,body:a,fetch:null!=(f=this.fetch)?f:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(a,{count:b}={}){var c;let{url:d,headers:e}=this.cloneRequestState();return b&&e.append("Prefer",`count=${b}`),new M({method:"PATCH",url:d,headers:e,schema:this.schema,body:a,fetch:null!=(c=this.fetch)?c:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:a}={}){var b;let{url:c,headers:d}=this.cloneRequestState();return a&&d.append("Prefer",`count=${a}`),new M({method:"DELETE",url:c,headers:d,schema:this.schema,fetch:null!=(b=this.fetch)?b:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function O(a){return(O="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a})(a)}function P(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d)}return c}function Q(a){for(var b=1;b<arguments.length;b++){var c=null!=arguments[b]?arguments[b]:{};b%2?P(Object(c),!0).forEach(function(b){!function(a,b,c){var d;(d=function(a,b){if("object"!=O(a)||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=O(d))return d;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}(b,"string"),(b="symbol"==O(d)?d:d+"")in a)?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c}(a,b,c[b])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(c)):P(Object(c)).forEach(function(b){Object.defineProperty(a,b,Object.getOwnPropertyDescriptor(c,b))})}return a}var R=class a{constructor(a,{headers:b={},schema:c,fetch:d,timeout:e,urlLengthLimit:f=8e3,retry:g}={}){this.url=a,this.headers=new Headers(b),this.schemaName=c,this.urlLengthLimit=f;let h=null!=d?d:globalThis.fetch;void 0!==e&&e>0?this.fetch=(a,b)=>{let c=new AbortController,d=setTimeout(()=>c.abort(),e),f=null==b?void 0:b.signal;if(f){if(f.aborted)return clearTimeout(d),h(a,b);let e=()=>{clearTimeout(d),c.abort()};return f.addEventListener("abort",e,{once:!0}),h(a,Q(Q({},b),{},{signal:c.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",e)})}return h(a,Q(Q({},b),{},{signal:c.signal})).finally(()=>clearTimeout(d))}:this.fetch=h,this.retry=g}from(a){if(!a||"string"!=typeof a||""===a.trim())throw Error("Invalid relation name: relation must be a non-empty string.");return new N(new URL(`${this.url}/${a}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(b){return new a(this.url,{headers:this.headers,schema:b,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(a,b={},{head:c=!1,get:d=!1,count:e}={}){var f;let g,h,i=new URL(`${this.url}/rpc/${a}`),j=a=>null!==a&&"object"==typeof a&&(!Array.isArray(a)||a.some(j)),k=c&&Object.values(b).some(j);k?(g="POST",h=b):c||d?(g=c?"HEAD":"GET",Object.entries(b).filter(([a,b])=>void 0!==b).map(([a,b])=>[a,Array.isArray(b)?`{${b.join(",")}}`:`${b}`]).forEach(([a,b])=>{i.searchParams.append(a,b)})):(g="POST",h=b);let l=new Headers(this.headers);return k?l.set("Prefer",e?`count=${e},return=minimal`:"return=minimal"):e&&l.set("Prefer",`count=${e}`),new M({method:g,url:i,headers:l,schema:this.schemaName,body:h,fetch:null!=(f=this.fetch)?f:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class S{constructor(){}static detectEnvironment(){var a;if("undefined"!=typeof WebSocket)return{type:"native",wsConstructor:WebSocket};let b=globalThis;if("undefined"!=typeof globalThis&&void 0!==b.WebSocket)return{type:"native",wsConstructor:b.WebSocket};let c="undefined"!=typeof global?global:void 0;if(c&&void 0!==c.WebSocket)return{type:"native",wsConstructor:c.WebSocket};if("undefined"!=typeof globalThis&&void 0!==b.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&b.EdgeRuntime||"undefined"!=typeof navigator&&(null==(a=navigator.userAgent)?void 0:a.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 d=globalThis.process;if(d){let a=d.versions;if(a&&a.node){let b=parseInt(a.node.replace(/^v/,"").split(".")[0]);return b>=22?void 0!==globalThis.WebSocket?{type:"native",wsConstructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${b} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${b} 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 a=this.detectEnvironment();if(a.wsConstructor)return a.wsConstructor;let b=a.error||"WebSocket not supported in this environment.";throw a.workaround&&(b+=`
|
|
|
|
Suggested solution: ${a.workaround}`),Error(b)}static isWebSocketSupported(){try{let a=this.detectEnvironment();return"native"===a.type||"ws"===a.type}catch(a){return!1}}}let T="2.0.0",U={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},V={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},W={connecting:"connecting",closing:"closing",closed:"closed"};class X{constructor(a){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!=a?a:[]}encode(a,b){return a.event!==this.BROADCAST_EVENT||a.payload instanceof ArrayBuffer||"string"!=typeof a.payload.event?b(JSON.stringify([a.join_ref,a.ref,a.topic,a.event,a.payload])):b(this._binaryEncodeUserBroadcastPush(a))}_binaryEncodeUserBroadcastPush(a){var b;return this._isArrayBuffer(null==(b=a.payload)?void 0:b.payload)?this._encodeBinaryUserBroadcastPush(a):this._encodeJsonUserBroadcastPush(a)}_encodeBinaryUserBroadcastPush(a){var b,c;let d=null!=(c=null==(b=a.payload)?void 0:b.payload)?c:new ArrayBuffer(0);return this._encodeUserBroadcastPush(a,this.BINARY_ENCODING,d)}_encodeJsonUserBroadcastPush(a){var b,c;let d=null!=(c=null==(b=a.payload)?void 0:b.payload)?c:{},e=new TextEncoder().encode(JSON.stringify(d)).buffer;return this._encodeUserBroadcastPush(a,this.JSON_ENCODING,e)}_encodeUserBroadcastPush(a,b,c){let d=a.topic,e=null!=(n=a.ref)?n:"",f=null!=(o=a.join_ref)?o:"",g=a.payload.event,h=this.allowedMetadataKeys?this._pick(a.payload,this.allowedMetadataKeys):{},i=0===Object.keys(h).length?"":JSON.stringify(h);if(f.length>255)throw Error(`joinRef length ${f.length} exceeds maximum of 255`);if(e.length>255)throw Error(`ref length ${e.length} exceeds maximum of 255`);if(d.length>255)throw Error(`topic length ${d.length} exceeds maximum of 255`);if(g.length>255)throw Error(`userEvent length ${g.length} exceeds maximum of 255`);if(i.length>255)throw Error(`metadata length ${i.length} exceeds maximum of 255`);let j=this.USER_BROADCAST_PUSH_META_LENGTH+f.length+e.length+d.length+g.length+i.length,k=new ArrayBuffer(this.HEADER_LENGTH+j),l=new DataView(k),m=0;l.setUint8(m++,this.KINDS.userBroadcastPush),l.setUint8(m++,f.length),l.setUint8(m++,e.length),l.setUint8(m++,d.length),l.setUint8(m++,g.length),l.setUint8(m++,i.length),l.setUint8(m++,b),Array.from(f,a=>l.setUint8(m++,a.charCodeAt(0))),Array.from(e,a=>l.setUint8(m++,a.charCodeAt(0))),Array.from(d,a=>l.setUint8(m++,a.charCodeAt(0))),Array.from(g,a=>l.setUint8(m++,a.charCodeAt(0))),Array.from(i,a=>l.setUint8(m++,a.charCodeAt(0)));var n,o,p=new Uint8Array(k.byteLength+c.byteLength);return p.set(new Uint8Array(k),0),p.set(new Uint8Array(c),k.byteLength),p.buffer}decode(a,b){if(this._isArrayBuffer(a))return b(this._binaryDecode(a));if("string"==typeof a){let[c,d,e,f,g]=JSON.parse(a);return b({join_ref:c,ref:d,topic:e,event:f,payload:g})}return b({})}_binaryDecode(a){let b=new DataView(a),c=b.getUint8(0),d=new TextDecoder;if(c===this.KINDS.userBroadcast)return this._decodeUserBroadcast(a,b,d)}_decodeUserBroadcast(a,b,c){let d=b.getUint8(1),e=b.getUint8(2),f=b.getUint8(3),g=b.getUint8(4),h=this.HEADER_LENGTH+4,i=c.decode(a.slice(h,h+d));h+=d;let j=c.decode(a.slice(h,h+e));h+=e;let k=c.decode(a.slice(h,h+f));h+=f;let l=a.slice(h,a.byteLength),m=g===this.JSON_ENCODING?JSON.parse(c.decode(l)):l,n={type:this.BROADCAST_EVENT,event:j,payload:m};return f>0&&(n.meta=JSON.parse(k)),{join_ref:null,ref:null,topic:i,event:this.BROADCAST_EVENT,payload:n}}_isArrayBuffer(a){var b;return a instanceof ArrayBuffer||(null==(b=null==a?void 0:a.constructor)?void 0:b.name)==="ArrayBuffer"}_pick(a,b){return a&&"object"==typeof a?Object.fromEntries(Object.entries(a).filter(([a])=>b.includes(a))):{}}}!function(a){a.abstime="abstime",a.bool="bool",a.date="date",a.daterange="daterange",a.float4="float4",a.float8="float8",a.int2="int2",a.int4="int4",a.int4range="int4range",a.int8="int8",a.int8range="int8range",a.json="json",a.jsonb="jsonb",a.money="money",a.numeric="numeric",a.oid="oid",a.reltime="reltime",a.text="text",a.time="time",a.timestamp="timestamp",a.timestamptz="timestamptz",a.timetz="timetz",a.tsrange="tsrange",a.tstzrange="tstzrange"}(f||(f={}));let Y=(a,b,c={})=>{var d;let e=null!=(d=c.skipTypes)?d:[];return b?Object.keys(b).reduce((c,d)=>(c[d]=Z(d,a,b,e),c),{}):{}},Z=(a,b,c,d)=>{let e=b.find(b=>b.name===a),f=null==e?void 0:e.type,g=c[a];return f&&!d.includes(f)?$(f,g):_(g)},$=(a,b)=>{if("_"===a.charAt(0))return ad(b,a.slice(1,a.length));switch(a){case f.bool:return aa(b);case f.float4:case f.float8:case f.int2:case f.int4:case f.int8:case f.numeric:case f.oid:return ab(b);case f.json:case f.jsonb:return ac(b);case f.timestamp:return ae(b);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 _(b)}},_=a=>a,aa=a=>{switch(a){case"t":return!0;case"f":return!1;default:return a}},ab=a=>{if("string"==typeof a){let b=parseFloat(a);if(!Number.isNaN(b))return b}return a},ac=a=>{if("string"==typeof a)try{return JSON.parse(a)}catch(a){}return a},ad=(a,b)=>{if("string"!=typeof a)return a;let c=a.length-1,d=a[c];if("{"===a[0]&&"}"===d){let d,e=a.slice(1,c);try{d=JSON.parse("["+e+"]")}catch(a){d=e?e.split(","):[]}return d.map(a=>$(b,a))}return a},ae=a=>"string"==typeof a?a.replace(" ","T"):a,af=a=>{let b=new URL(a);return b.protocol=b.protocol.replace(/^ws/i,"http"),b.pathname=b.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===b.pathname||"/"===b.pathname?b.pathname="/api/broadcast":b.pathname=b.pathname+"/api/broadcast",b.href};var ag=a=>"function"==typeof a?a:function(){return a},ah="undefined"!=typeof window?window:null,ai=("undefined"!=typeof self?self:null)||ah||globalThis,aj={connecting:0,open:1,closing:2,closed:3},ak={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},al={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},am={longpoll:"longpoll",websocket:"websocket"},an={complete:4},ao="base64url.bearer.phx.",ap=class{constructor(a,b,c,d){this.channel=a,this.event=b,this.payload=c||function(){return{}},this.receivedResp=null,this.timeout=d,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(a){this.timeout=a,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(a,b){return this.hasReceived(a)&&b(this.receivedResp.response),this.recHooks.push({status:a,callback:b}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:a,response:b,_ref:c}){this.recHooks.filter(b=>b.status===a).forEach(a=>a.callback(b))}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,a=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=a,this.matchReceive(a)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(a){return this.receivedResp&&this.receivedResp.status===a}trigger(a,b){this.channel.trigger(this.refEvent,{status:a,response:b})}},aq=class{constructor(a,b){this.callback=a,this.timerCalc=b,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},ar=class{constructor(a,b,c){this.state=ak.closed,this.topic=a,this.params=ag(b||{}),this.socket=c,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new ap(this,al.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new aq(()=>{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=ak.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this.joinPush.receive("error",a=>{this.state=ak.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,a),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=ak.closed,this.socket.remove(this)}),this.onError(a=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,a),this.isJoining()&&this.joinPush.reset(),this.state=ak.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new ap(this,al.leave,ag({}),this.timeout).send(),this.state=ak.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(al.reply,(a,b)=>{this.trigger(this.replyEventName(b),a)})}join(a=this.timeout){if(!this.joinedOnce)return this.timeout=a,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(a=>a.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=ak.closed,this.bindings=[]}onClose(a){this.on(al.close,a)}onError(a){return this.on(al.error,b=>a(b))}on(a,b){let c=this.bindingRef++;return this.bindings.push({event:a,ref:c,callback:b}),c}off(a,b){this.bindings=this.bindings.filter(c=>c.event!==a||void 0!==b&&b!==c.ref)}canPush(){return this.socket.isConnected()&&this.isJoined()}push(a,b,c=this.timeout){if(b=b||{},!this.joinedOnce)throw Error(`tried to push '${a}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let d=new ap(this,a,function(){return b},c);return this.canPush()?d.send():(d.startTimeout(),this.pushBuffer.push(d)),d}leave(a=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=ak.leaving;let b=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(al.close,"leave")},c=new ap(this,al.leave,ag({}),a);return c.receive("ok",()=>b()).receive("timeout",()=>b()),c.send(),this.canPush()||c.trigger("ok",{}),c}onMessage(a,b,c){return b}filterBindings(a,b,c){return!0}isMember(a,b,c,d){return this.topic===a&&(!d||d===this.joinRef()||(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:a,event:b,payload:c,joinRef:d}),!1))}joinRef(){return this.joinPush.ref}rejoin(a=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=ak.joining,this.joinPush.resend(a))}trigger(a,b,c,d){let e=this.onMessage(a,b,c,d);if(b&&!e)throw Error("channel onMessage callbacks must return the payload, modified or unmodified");let f=this.bindings.filter(d=>d.event===a&&this.filterBindings(d,b,c));for(let a=0;a<f.length;a++)f[a].callback(e,c,d||this.joinRef())}replyEventName(a){return`chan_reply_${a}`}isClosed(){return this.state===ak.closed}isErrored(){return this.state===ak.errored}isJoined(){return this.state===ak.joined}isJoining(){return this.state===ak.joining}isLeaving(){return this.state===ak.leaving}},as=class{static request(a,b,c,d,e,f,g){if(ai.XDomainRequest){let c=new ai.XDomainRequest;return this.xdomainRequest(c,a,b,d,e,f,g)}if(ai.XMLHttpRequest){let h=new ai.XMLHttpRequest;return this.xhrRequest(h,a,b,c,d,e,f,g)}if(ai.fetch&&ai.AbortController)return this.fetchRequest(a,b,c,d,e,f,g);throw Error("No suitable XMLHttpRequest implementation found")}static fetchRequest(a,b,c,d,e,f,g){let h={method:a,headers:c,body:d},i=null;return e&&(i=new AbortController,setTimeout(()=>i.abort(),e),h.signal=i.signal),ai.fetch(b,h).then(a=>a.text()).then(a=>this.parseJSON(a)).then(a=>g&&g(a)).catch(a=>{"AbortError"===a.name&&f?f():g&&g(null)}),i}static xdomainRequest(a,b,c,d,e,f,g){return a.timeout=e,a.open(b,c),a.onload=()=>{let b=this.parseJSON(a.responseText);g&&g(b)},f&&(a.ontimeout=f),a.onprogress=()=>{},a.send(d),a}static xhrRequest(a,b,c,d,e,f,g,h){for(let[e,g]of(a.open(b,c,!0),a.timeout=f,Object.entries(d)))a.setRequestHeader(e,g);return a.onerror=()=>h&&h(null),a.onreadystatechange=()=>{a.readyState===an.complete&&h&&h(this.parseJSON(a.responseText))},g&&(a.ontimeout=g),a.send(e),a}static parseJSON(a){if(!a||""===a)return null;try{return JSON.parse(a)}catch{return console&&console.log("failed to parse JSON response",a),null}}static serialize(a,b){let c=[];for(var d in a){if(!Object.prototype.hasOwnProperty.call(a,d))continue;let e=b?`${b}[${d}]`:d,f=a[d];"object"==typeof f?c.push(this.serialize(f,e)):c.push(encodeURIComponent(e)+"="+encodeURIComponent(f))}return c.join("&")}static appendParams(a,b){if(0===Object.keys(b).length)return a;let c=a.match(/\?/)?"&":"?";return`${a}${c}${this.serialize(b)}`}},at=class{constructor(a,b){b&&2===b.length&&b[1].startsWith(ao)&&(this.authToken=atob(b[1].slice(ao.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(a),this.readyState=aj.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(a){return a.replace("ws://","http://").replace("wss://","https://").replace(RegExp("(.*)/"+am.websocket),"$1/"+am.longpoll)}endpointURL(){return as.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(a,b,c){this.close(a,b,c),this.readyState=aj.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===aj.open||this.readyState===aj.connecting}poll(){let a={Accept:"application/json"};this.authToken&&(a["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",a,null,()=>this.ontimeout(),a=>{if(a){var{status:b,token:c,messages:d}=a;if(410===b&&null!==this.token){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=c}else b=0;switch(b){case 200:d.forEach(a=>{setTimeout(()=>this.onmessage({data:a}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=aj.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw Error(`unhandled poll status ${b}`)}})}send(a){"string"!=typeof a&&(a=(a=>{let b="",c=new Uint8Array(a),d=c.byteLength;for(let a=0;a<d;a++)b+=String.fromCharCode(c[a]);return btoa(b)})(a)),this.currentBatch?this.currentBatch.push(a):this.awaitingBatchAck?this.batchBuffer.push(a):(this.currentBatch=[a],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(a){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},a.join("\n"),()=>this.onerror("timeout"),a=>{this.awaitingBatchAck=!1,a&&200===a.status?this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]):(this.onerror(a&&a.status),this.closeAndRetry(1011,"internal server error",!1))})}close(a,b,c){for(let a of this.reqs)a.abort();this.readyState=aj.closed;let d=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:a,reason:b,wasClean:c});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,"undefined"!=typeof CloseEvent?this.onclose(new CloseEvent("close",d)):this.onclose(d)}ajax(a,b,c,d,e){let f,g=()=>{this.reqs.delete(f),d()};f=as.request(a,this.endpointURL(),b,c,this.timeout,g,a=>{this.reqs.delete(f),this.isActive()&&e(a)}),this.reqs.add(f)}},au=class a{constructor(b,c={}){let d=c.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=b,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(d.state,b=>{let{onJoin:c,onLeave:d,onSync:e}=this.caller;this.joinRef=this.channel.joinRef(),this.state=a.syncState(this.state,b,c,d),this.pendingDiffs.forEach(b=>{this.state=a.syncDiff(this.state,b,c,d)}),this.pendingDiffs=[],e()}),this.channel.on(d.diff,b=>{let{onJoin:c,onLeave:d,onSync:e}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(b):(this.state=a.syncDiff(this.state,b,c,d),e())})}onJoin(a){this.caller.onJoin=a}onLeave(a){this.caller.onLeave=a}onSync(a){this.caller.onSync=a}list(b){return a.list(this.state,b)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(a,b,c,d){let e=this.clone(a),f={},g={};return this.map(e,(a,c)=>{b[a]||(g[a]=c)}),this.map(b,(a,b)=>{let c=e[a];if(c){let d=b.metas.map(a=>a.phx_ref),e=c.metas.map(a=>a.phx_ref),h=b.metas.filter(a=>0>e.indexOf(a.phx_ref)),i=c.metas.filter(a=>0>d.indexOf(a.phx_ref));h.length>0&&(f[a]=b,f[a].metas=h),i.length>0&&(g[a]=this.clone(c),g[a].metas=i)}else f[a]=b}),this.syncDiff(e,{joins:f,leaves:g},c,d)}static syncDiff(a,b,c,d){let{joins:e,leaves:f}=this.clone(b);return c||(c=function(){}),d||(d=function(){}),this.map(e,(b,d)=>{let e=a[b];if(a[b]=this.clone(d),e){let c=a[b].metas.map(a=>a.phx_ref),d=e.metas.filter(a=>0>c.indexOf(a.phx_ref));a[b].metas.unshift(...d)}c(b,e,d)}),this.map(f,(b,c)=>{let e=a[b];if(!e)return;let f=c.metas.map(a=>a.phx_ref);e.metas=e.metas.filter(a=>0>f.indexOf(a.phx_ref)),d(b,e,c),0===e.metas.length&&delete a[b]}),a}static list(a,b){return b||(b=function(a,b){return b}),this.map(a,(a,c)=>b(a,c))}static map(a,b){return Object.getOwnPropertyNames(a).map(c=>b(c,a[c]))}static clone(a){return JSON.parse(JSON.stringify(a))}},av={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(a,b){return a.payload.constructor===ArrayBuffer?b(this.binaryEncode(a)):b(JSON.stringify([a.join_ref,a.ref,a.topic,a.event,a.payload]))},decode(a,b){if(a.constructor===ArrayBuffer)return b(this.binaryDecode(a));{let[c,d,e,f,g]=JSON.parse(a);return b({join_ref:c,ref:d,topic:e,event:f,payload:g})}},binaryEncode(a){let{join_ref:b,ref:c,event:d,topic:e,payload:f}=a,g=this.META_LENGTH+b.length+c.length+e.length+d.length,h=new ArrayBuffer(this.HEADER_LENGTH+g),i=new DataView(h),j=0;i.setUint8(j++,this.KINDS.push),i.setUint8(j++,b.length),i.setUint8(j++,c.length),i.setUint8(j++,e.length),i.setUint8(j++,d.length),Array.from(b,a=>i.setUint8(j++,a.charCodeAt(0))),Array.from(c,a=>i.setUint8(j++,a.charCodeAt(0))),Array.from(e,a=>i.setUint8(j++,a.charCodeAt(0))),Array.from(d,a=>i.setUint8(j++,a.charCodeAt(0)));var k=new Uint8Array(h.byteLength+f.byteLength);return k.set(new Uint8Array(h),0),k.set(new Uint8Array(f),h.byteLength),k.buffer},binaryDecode(a){let b=new DataView(a),c=b.getUint8(0),d=new TextDecoder;switch(c){case this.KINDS.push:return this.decodePush(a,b,d);case this.KINDS.reply:return this.decodeReply(a,b,d);case this.KINDS.broadcast:return this.decodeBroadcast(a,b,d)}},decodePush(a,b,c){let d=b.getUint8(1),e=b.getUint8(2),f=b.getUint8(3),g=this.HEADER_LENGTH+this.META_LENGTH-1,h=c.decode(a.slice(g,g+d));g+=d;let i=c.decode(a.slice(g,g+e));g+=e;let j=c.decode(a.slice(g,g+f));return g+=f,{join_ref:h,ref:null,topic:i,event:j,payload:a.slice(g,a.byteLength)}},decodeReply(a,b,c){let d=b.getUint8(1),e=b.getUint8(2),f=b.getUint8(3),g=b.getUint8(4),h=this.HEADER_LENGTH+this.META_LENGTH,i=c.decode(a.slice(h,h+d));h+=d;let j=c.decode(a.slice(h,h+e));h+=e;let k=c.decode(a.slice(h,h+f));h+=f;let l=c.decode(a.slice(h,h+g));h+=g;let m=a.slice(h,a.byteLength);return{join_ref:i,ref:j,topic:k,event:al.reply,payload:{status:l,response:m}}},decodeBroadcast(a,b,c){let d=b.getUint8(1),e=b.getUint8(2),f=this.HEADER_LENGTH+2,g=c.decode(a.slice(f,f+d));f+=d;let h=c.decode(a.slice(f,f+e));return f+=e,{join_ref:null,ref:null,topic:g,event:h,payload:a.slice(f,a.byteLength)}}},aw=class{constructor(a,b={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=b.timeout||1e4,this.transport=b.transport||ai.WebSocket||at,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=b.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=b.sessionStorage||ai&&ai.sessionStorage,this.establishedConnections=0,this.defaultEncoder=av.encode.bind(av),this.defaultDecoder=av.decode.bind(av),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=b.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==at?(this.encode=b.encode||this.defaultEncoder,this.decode=b.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let c=null;ah&&ah.addEventListener&&(ah.addEventListener("pagehide",a=>{this.conn&&(this.disconnect(),c=this.connectClock)}),ah.addEventListener("pageshow",a=>{c===this.connectClock&&(c=null,this.connect())}),ah.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this.pageHidden=!0:(this.pageHidden=!1,this.isConnected()||this.closeWasClean||this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=b.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=b.autoSendHeartbeat??!0,this.heartbeatCallback=b.heartbeatCallback??(()=>{}),this.rejoinAfterMs=a=>b.rejoinAfterMs?b.rejoinAfterMs(a):[1e3,2e3,5e3][a-1]||1e4,this.reconnectAfterMs=a=>b.reconnectAfterMs?b.reconnectAfterMs(a):[10,50,100,150,200,250,500,1e3,2e3][a-1]||5e3,this.logger=b.logger||null,!this.logger&&b.debug&&(this.logger=(a,b,c)=>{console.log(`${a}: ${b}`,c)}),this.longpollerTimeout=b.longpollerTimeout||2e4,this.params=ag(b.params||{}),this.endPoint=`${a}/${am.websocket}`,this.vsn=b.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new aq(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{b.beforeReconnect&&await b.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=b.authToken}getLongPollTransport(){return at}replaceTransport(a){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=a}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let a=as.appendParams(as.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"!==a.charAt(0)?a:"/"===a.charAt(1)?`${this.protocol()}:${a}`:`${this.protocol()}://${location.host}${a}`}disconnect(a,b,c){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,a&&a()},b,c)}connect(a){a&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=ag(a)),(!this.conn||this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==at?this.connectWithFallback(at,this.longPollFallbackMs):this.transportConnect())}log(a,b,c){this.logger&&this.logger(a,b,c)}hasLogger(){return null!==this.logger}onOpen(a){let b=this.makeRef();return this.stateChangeCallbacks.open.push([b,a]),b}onClose(a){let b=this.makeRef();return this.stateChangeCallbacks.close.push([b,a]),b}onError(a){let b=this.makeRef();return this.stateChangeCallbacks.error.push([b,a]),b}onMessage(a){let b=this.makeRef();return this.stateChangeCallbacks.message.push([b,a]),b}onHeartbeat(a){this.heartbeatCallback=a}ping(a){if(!this.isConnected())return!1;let b=this.makeRef(),c=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:b});let d=this.onMessage(e=>{e.ref===b&&(this.off([d]),a(Date.now()-c))});return!0}transportName(a){return a===at?"LongPoll":a.name}transportConnect(){let a;this.connectClock++,this.closeWasClean=!1,this.authToken&&(a=["phoenix",`${ao}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),a),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=a=>this.onConnError(a),this.conn.onmessage=a=>this.onConnMessage(a),this.conn.onclose=a=>this.onConnClose(a)}getSession(a){return this.sessionStore&&this.sessionStore.getItem(a)}storeSession(a,b){this.sessionStore&&this.sessionStore.setItem(a,b)}connectWithFallback(a,b=2500){let c,d;clearTimeout(this.fallbackTimer);let e=!1,f=!0,g=this.transportName(a),h=b=>{this.log("transport",`falling back to ${g}...`,b),this.off([c,d]),f=!1,this.replaceTransport(a),this.transportConnect()};if(this.getSession(`phx:fallback:${g}`))return h("memorized");this.fallbackTimer=setTimeout(h,b),d=this.onError(a=>{this.log("transport","error",a),f&&!e&&(clearTimeout(this.fallbackTimer),h(a))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(e=!0,!f){let b=this.transportName(a);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${b}`,"true"),this.log("transport",`established ${b} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(h,b),this.ping(a=>{this.log("transport","connected to primary after",a),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(a){this.log("error","error in heartbeat callback",a)}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(a,b,c){if(!this.conn)return a&&a();let d=this.conn;this.waitForBufferDone(d,()=>{b?d.close(b,c||""):d.close(),this.waitForSocketClosed(d,()=>{this.conn===d&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),a&&a()})})}waitForBufferDone(a,b,c=1){if(5===c||!a.bufferedAmount)return void b();setTimeout(()=>{this.waitForBufferDone(a,b,c+1)},150*c)}waitForSocketClosed(a,b,c=1){if(5===c||a.readyState===aj.closed)return void b();setTimeout(()=>{this.waitForSocketClosed(a,b,c+1)},150*c)}onConnClose(a){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",a),this.triggerChanError(a),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",a)}onConnError(a){this.hasLogger()&&this.log("transport","error",a);let b=this.transport,c=this.establishedConnections;this.triggerStateCallbacks("error",a,b,c),(b===this.transport||c>0)&&this.triggerChanError(a)}triggerChanError(a){this.channels.forEach(b=>{b.isErrored()||b.isLeaving()||b.isClosed()||b.trigger(al.error,a)})}connectionState(){switch(this.conn&&this.conn.readyState){case aj.connecting:return"connecting";case aj.open:return"open";case aj.closing:return"closing";default:return"closed"}}isConnected(){return"open"===this.connectionState()}remove(a){this.off(a.stateChangeRefs),this.channels=this.channels.filter(b=>b!==a)}off(a){for(let b in this.stateChangeCallbacks)this.stateChangeCallbacks[b]=this.stateChangeCallbacks[b].filter(([b])=>-1===a.indexOf(b))}channel(a,b={}){let c=new ar(a,b,this);return this.channels.push(c),c}push(a){if(this.hasLogger()){let{topic:b,event:c,payload:d,ref:e,join_ref:f}=a;this.log("push",`${b} ${c} (${f}, ${e})`,d)}this.isConnected()?this.encode(a,a=>this.conn.send(a)):this.sendBuffer.push(()=>this.encode(a,a=>this.conn.send(a)))}makeRef(){let a=this.ref+1;return a===this.ref?this.ref=0:this.ref=a,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(a){this.log("error","error in heartbeat callback",a)}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(a){this.log("error","error in heartbeat callback",a)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(a=>a()),this.sendBuffer=[])}onConnMessage(a){this.decode(a.data,a=>{let{topic:b,event:c,payload:d,ref:e,join_ref:f}=a;if(e&&e===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback("ok"===d.status?"ok":"error",a)}catch(a){this.log("error","error in heartbeat callback",a)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${d.status||""} ${b} ${c} ${e&&"("+e+")"||""}`.trim(),d);for(let a=0;a<this.channels.length;a++){let g=this.channels[a];g.isMember(b,c,d,f)&&g.trigger(c,d,e,f)}this.triggerStateCallbacks("message",a)})}triggerStateCallbacks(a,...b){try{this.stateChangeCallbacks[a].forEach(([c,d])=>{try{d(...b)}catch(b){this.log("error",`error in ${a} callback`,b)}})}catch(b){this.log("error",`error triggering ${a} callbacks`,b)}}leaveOpenTopic(a){let b=this.channels.find(b=>b.topic===a&&(b.isJoined()||b.isJoining()));b&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${a}"`),b.leave())}};class ax{constructor(a,b){let c=function(a){return(null==a?void 0:a.events)&&{events:a.events}}(b);this.presence=new au(a.getChannel(),c),this.presence.onJoin((b,c,d)=>{let e=ax.onJoinPayload(b,c,d);a.getChannel().trigger("presence",e)}),this.presence.onLeave((b,c,d)=>{let e=ax.onLeavePayload(b,c,d);a.getChannel().trigger("presence",e)}),this.presence.onSync(()=>{a.getChannel().trigger("presence",{event:"sync"})})}get state(){return ax.transformState(this.presence.state)}static transformState(a){return Object.getOwnPropertyNames(a=JSON.parse(JSON.stringify(a))).reduce((b,c)=>{let d=a[c];return b[c]=ay(d),b},{})}static onJoinPayload(a,b,c){return{event:"join",key:a,currentPresences:az(b),newPresences:ay(c)}}static onLeavePayload(a,b,c){return{event:"leave",key:a,currentPresences:az(b),leftPresences:ay(c)}}}function ay(a){return a.metas.map(a=>(a.presence_ref=a.phx_ref,delete a.phx_ref,delete a.phx_ref_prev,a))}function az(a){return(null==a?void 0:a.metas)?ay(a):[]}!function(a){a.SYNC="sync",a.JOIN="join",a.LEAVE="leave"}(g||(g={}));class aA{get state(){return this.presenceAdapter.state}constructor(a,b){this.channel=a,this.presenceAdapter=new ax(this.channel.channelAdapter,b)}}class aB{constructor(a,b,c){let d={config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},c.config)};this.channel=a.getSocket().channel(b,d),this.socket=a}get state(){return this.channel.state}set state(a){this.channel.state=a}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(a,b){return this.channel.on(a,b)}off(a,b){this.channel.off(a,b)}subscribe(a){return this.channel.join(a)}unsubscribe(a){return this.channel.leave(a)}teardown(){this.channel.teardown()}onClose(a){this.channel.onClose(a)}onError(a){return this.channel.onError(a)}push(a,b,c){let d;try{d=this.channel.push(a,b,c)}catch(b){throw Error(`tried to push '${a}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>100){let a=this.channel.pushBuffer.shift();a.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${a.event}`,a.payload())}return d}updateJoinPayload(a){let b=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},b),a)}canPush(){return this.socket.isConnected()&&this.state===U.joined}isJoined(){return this.state===U.joined}isJoining(){return this.state===U.joining}isClosed(){return this.state===U.closed}isLeaving(){return this.state===U.leaving}updateFilterBindings(a){this.channel.filterBindings=a}updatePayloadTransform(a){this.channel.onMessage=a}getChannel(){return this.channel}}!function(a){a.ALL="*",a.INSERT="INSERT",a.UPDATE="UPDATE",a.DELETE="DELETE"}(h||(h={})),function(a){a.BROADCAST="broadcast",a.PRESENCE="presence",a.POSTGRES_CHANGES="postgres_changes",a.SYSTEM="system"}(i||(i={})),function(a){a.SUBSCRIBED="SUBSCRIBED",a.TIMED_OUT="TIMED_OUT",a.CLOSED="CLOSED",a.CHANNEL_ERROR="CHANNEL_ERROR"}(j||(j={}));class aC{get state(){return this.channelAdapter.state}set state(a){this.channelAdapter.state=a}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(a,b={config:{}},c){var d,e;if(this.topic=a,this.params=b,this.socket=c,this.bindings={},this.subTopic=a.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},b.config),this.channelAdapter=new aB(this.socket.socketAdapter,a,this.params),this.presence=new aA(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=af(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(null==(e=null==(d=this.params.config)?void 0:d.broadcast)?void 0:e.replay))throw Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(a,b=this.timeout){var c,d,e;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:f,presence:g,private:h}}=this.params,k=null!=(d=null==(c=this.bindings.postgres_changes)?void 0:c.map(a=>a.filter))?d:[],l=!!this.bindings[i.PRESENCE]&&this.bindings[i.PRESENCE].length>0||(null==(e=this.params.config.presence)?void 0:e.enabled)===!0,m={},n={broadcast:f,presence:Object.assign(Object.assign({},g),{enabled:l}),postgres_changes:k,private:h};this.socket.accessTokenValue&&(m.access_token=this.socket.accessTokenValue),this._onError(b=>{null==a||a(j.CHANNEL_ERROR,function(a){if(a instanceof Error)return a;if("string"==typeof a)return Error(a);if(a&&"object"==typeof a){if("number"==typeof a.code){let b="string"==typeof a.reason&&a.reason?` (${a.reason})`:"";return Error(`socket closed: ${a.code}${b}`,{cause:a})}return Error("channel error: transport failure",{cause:a})}return Error("channel error: connection lost")}(b))}),this._onClose(()=>null==a?void 0:a(j.CLOSED)),this.updateJoinPayload(Object.assign({config:n},m)),this._updateFilterMessage(),this.channelAdapter.subscribe(b).receive("ok",async({postgres_changes:b})=>{if(this.socket._isManualToken()||this.socket.setAuth(),void 0===b){null==a||a(j.SUBSCRIBED);return}this._updatePostgresBindings(b,a)}).receive("error",b=>{this.state=U.errored;let c=Object.values(b).join(", ")||"error";null==a||a(j.CHANNEL_ERROR,Error(c,{cause:b}))}).receive("timeout",()=>{null==a||a(j.TIMED_OUT)})}return this}_updatePostgresBindings(a,b){var c;let d=this.bindings.postgres_changes,e=null!=(c=null==d?void 0:d.length)?c:0,f=[];for(let c=0;c<e;c++){let e=d[c],{filter:{event:g,schema:h,table:i,filter:k}}=e,l=a&&a[c];if(l&&l.event===g&&aC.isFilterValueEqual(l.schema,h)&&aC.isFilterValueEqual(l.table,i)&&aC.isFilterValueEqual(l.filter,k))f.push(Object.assign(Object.assign({},e),{id:l.id}));else{this.unsubscribe(),this.state=U.errored,null==b||b(j.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=f,this.state!=U.errored&&b&&b(j.SUBSCRIBED)}presenceState(){return this.presence.state}async track(a,b={}){return await this.send({type:"presence",event:"track",payload:a},b.timeout||this.timeout)}async untrack(a={}){return await this.send({type:"presence",event:"untrack"},a)}on(a,b,c){let d=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),e=a===i.PRESENCE||a===i.POSTGRES_CHANGES;if(d&&e)throw this.socket.log("channel",`cannot add \`${a}\` callbacks for ${this.topic} after \`subscribe()\`.`),Error(`cannot add \`${a}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(a,b,c)}async httpSend(a,b,c={}){var d;if(null==b)return Promise.reject(Error("Payload is required for httpSend()"));let e={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(e.Authorization=`Bearer ${this.socket.accessTokenValue}`);let f={method:"POST",headers:e,body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:b,private:this.private}]})},g=await this._fetchWithTimeout(this.broadcastEndpointURL,f,null!=(d=c.timeout)?d:this.timeout);if(202===g.status)return{success:!0};let h=g.statusText;try{let a=await g.json();h=a.error||a.message||h}catch(a){}return Promise.reject(Error(h))}async send(a,b={}){var c,d;if(this.channelAdapter.canPush()||"broadcast"!==a.type)return new Promise(c=>{var d,e,f;let g=this.channelAdapter.push(a.type,a,b.timeout||this.timeout);"broadcast"!==a.type||(null==(f=null==(e=null==(d=this.params)?void 0:d.config)?void 0:e.broadcast)?void 0:f.ack)||c("ok"),g.receive("ok",()=>c("ok")),g.receive("error",()=>c("error")),g.receive("timeout",()=>c("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:e,payload:f}=a,g={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(g.Authorization=`Bearer ${this.socket.accessTokenValue}`);let h={method:"POST",headers:g,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:f,private:this.private}]})};try{let a=await this._fetchWithTimeout(this.broadcastEndpointURL,h,null!=(c=b.timeout)?c:this.timeout);return await (null==(d=a.body)?void 0:d.cancel()),a.ok?"ok":"error"}catch(a){if(a instanceof Error&&"AbortError"===a.name)return"timed out";return"error"}}}updateJoinPayload(a){this.channelAdapter.updateJoinPayload(a)}async unsubscribe(a=this.timeout){return new Promise(b=>{this.channelAdapter.unsubscribe(a).receive("ok",()=>b("ok")).receive("timeout",()=>b("timed out")).receive("error",()=>b("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(a,b,c){let d=new AbortController,e=setTimeout(()=>d.abort(),c),f=await this.socket.fetch(a,Object.assign(Object.assign({},b),{signal:d.signal}));return clearTimeout(e),f}_on(a,b,c){let d=a.toLocaleLowerCase(),e=this.channelAdapter.on(a,c),f={type:d,filter:b,callback:c,ref:e};return this.bindings[d]?this.bindings[d].push(f):this.bindings[d]=[f],this._updateFilterMessage(),this}_onClose(a){this.channelAdapter.onClose(a)}_onError(a){this.channelAdapter.onError(a)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((a,b,c)=>{var d,e,f,g,h,i,j;let k=a.event.toLocaleLowerCase();if(this._notThisChannelEvent(k,c))return!1;let l=null==(d=this.bindings[k])?void 0:d.find(b=>b.ref===a.ref);if(!l)return!0;if(!["broadcast","presence","postgres_changes"].includes(k))return l.type.toLocaleLowerCase()===k;if("id"in l){let a=l.id,c=null==(e=l.filter)?void 0:e.event;return a&&(null==(f=b.ids)?void 0:f.includes(a))&&("*"===c||(null==c?void 0:c.toLocaleLowerCase())===(null==(g=b.data)?void 0:g.type.toLocaleLowerCase()))}{let a=null==(i=null==(h=null==l?void 0:l.filter)?void 0:h.event)?void 0:i.toLocaleLowerCase();return"*"===a||a===(null==(j=null==b?void 0:b.event)?void 0:j.toLocaleLowerCase())}})}_notThisChannelEvent(a,b){let{close:c,error:d,leave:e,join:f}=V;return b&&[c,d,e,f].includes(a)&&b!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((a,b,c)=>{if("object"==typeof b&&"ids"in b){let a=b.data,{schema:c,table:d,commit_timestamp:e,type:f,errors:g}=a;return Object.assign(Object.assign({},{schema:c,table:d,commit_timestamp:e,eventType:f,new:{},old:{},errors:g}),this._getPayloadRecords(a))}return b})}copyBindings(a){if(this.joinedOnce)throw Error("cannot copy bindings into joined channel");for(let b in a.bindings)for(let c of a.bindings[b])this._on(c.type,c.filter,c.callback)}static isFilterValueEqual(a,b){return(null!=a?a:void 0)===(null!=b?b:void 0)}_getPayloadRecords(a){let b={new:{},old:{}};return("INSERT"===a.type||"UPDATE"===a.type)&&(b.new=Y(a.columns,a.record)),("UPDATE"===a.type||"DELETE"===a.type)&&(b.old=Y(a.columns,a.old_record)),b}}class aD{constructor(a,b){this.socket=new aw(a,b)}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(a){this.socket.heartbeatCallback=a}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(a,b,c,d=1e4){return new Promise(e=>{setTimeout(()=>e("timeout"),d),this.socket.disconnect(()=>{a(),e("ok")},b,c)})}push(a){this.socket.push(a)}log(a,b,c){this.socket.log(a,b,c)}makeRef(){return this.socket.makeRef()}onOpen(a){this.socket.onOpen(a)}onClose(a){this.socket.onClose(a)}onError(a){this.socket.onError(a)}onMessage(a){this.socket.onMessage(a)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==W.connecting}isDisconnecting(){return this.socket.connectionState()==W.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}let aE={HEARTBEAT_INTERVAL:25e3},aF=[1e3,2e3,5e3,1e4],aG=`
|
|
addEventListener("message", (e) => {
|
|
if (e.data.event === "start") {
|
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
}
|
|
});`;class aH{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(a,b){var c;if(this.channels=[],this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new X,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=a=>a?(...b)=>a(...b):(...a)=>fetch(...a),!(null==(c=null==b?void 0:b.params)?void 0:c.apikey))throw Error("API key is required to connect to Realtime");this.apiKey=b.params.apikey;let d=this._initializeOptions(b);this.socketAdapter=new aD(a,d),this.httpEndpoint=af(a),this.fetch=this._resolveFetch(null==b?void 0:b.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(b){let a=b.message;if(a.includes("Node.js"))throw Error(`${a}
|
|
|
|
To use Realtime in Node.js, you need to provide a WebSocket implementation:
|
|
|
|
Option 1: Use Node.js 22+ which has native WebSocket support
|
|
Option 2: Install and provide the "ws" package:
|
|
|
|
npm install ws
|
|
|
|
import ws from "ws"
|
|
const client = new RealtimeClient(url, {
|
|
...options,
|
|
transport: ws
|
|
})`);throw Error(`WebSocket not available: ${a}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(a,b){return(this._cancelPendingDisconnect(),this.isDisconnecting())?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},a,b)}getChannels(){return this.channels}async removeChannel(a){let b=await a.unsubscribe();return"ok"===b&&a.teardown(),b}async removeAllChannels(){let a=this.channels.map(async a=>{let b=await a.unsubscribe();return a.teardown(),b}),b=await Promise.all(a);return await this.disconnect(),b}log(a,b,c){this.socketAdapter.log(a,b,c)}connectionState(){return this.socketAdapter.connectionState()||W.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(a,b={config:{}}){let c=`realtime:${a}`,d=this.getChannels().find(a=>a.topic===c);if(d)return d;{let c=new aC(`realtime:${a}`,b,this);return this._cancelPendingDisconnect(),this.channels.push(c),c}}push(a){this.socketAdapter.push(a)}async setAuth(a=null){this._authPromise=this._performAuth(a);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(a){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(a)}_makeRef(){return this.socketAdapter.makeRef()}_remove(a){this.channels=this.channels.filter(b=>b.topic!==a.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}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,0===this.channels.length&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){null!==this._pendingDisconnectTimer&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(a=null){let b,c=!1;if(a)b=a,c=!0;else if(this.accessToken)try{b=await this.accessToken()}catch(a){this.log("error","Error fetching access token from callback",a),b=this.accessTokenValue}else b=this.accessTokenValue;c?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=b&&(this.accessTokenValue=b,this.channels.forEach(a=>{let c={access_token:b,version:"realtime-js/2.105.3"};b&&a.updateJoinPayload(c),a.joinedOnce&&a.channelAdapter.isJoined()&&a.channelAdapter.push(V.access_token,{access_token:b})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(a="general"){this._isManualToken()||this.setAuth().catch(b=>{this.log("error",`Error setting auth in ${a}`,b)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(a=>{this.log("error","error waiting for auth on connect",a)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(a=>{a.ref&&a.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(a){return(b,c)=>{"sent"==b&&this._setAuthSafely(),a&&a(b,c)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let a=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(a),this.workerRef.onerror=a=>{this.log("worker","worker error",a.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=a=>{"keepAlive"===a.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(a){let b;if(a)b=a;else{let a=new Blob([aG],{type:"application/javascript"});b=URL.createObjectURL(a)}return b}_initializeOptions(a){var b,c,d,e,f,g,h,i,j,k,l;let m,n;this.worker=null!=(b=null==a?void 0:a.worker)&&b,this.accessToken=null!=(c=null==a?void 0:a.accessToken)?c:null;let o={};o.timeout=null!=(d=null==a?void 0:a.timeout)?d:1e4,o.heartbeatIntervalMs=null!=(e=null==a?void 0:a.heartbeatIntervalMs)?e:aE.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=null!=(f=null==a?void 0:a.disconnectOnEmptyChannelsAfterMs)?f:2*(null!=(g=null==a?void 0:a.heartbeatIntervalMs)?g:aE.HEARTBEAT_INTERVAL),o.transport=null!=(h=null==a?void 0:a.transport)?h:S.getWebSocketConstructor(),o.params=null==a?void 0:a.params,o.logger=null==a?void 0:a.logger,o.heartbeatCallback=this._wrapHeartbeatCallback(null==a?void 0:a.heartbeatCallback),o.reconnectAfterMs=null!=(i=null==a?void 0:a.reconnectAfterMs)?i:a=>aF[a-1]||1e4;let p=null!=(j=null==a?void 0:a.vsn)?j:T;switch(p){case"1.0.0":m=(a,b)=>b(JSON.stringify(a)),n=(a,b)=>b(JSON.parse(a));break;case T:m=this.serializer.encode.bind(this.serializer),n=this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${o.vsn}`)}if(o.vsn=p,o.encode=null!=(k=null==a?void 0:a.encode)?k:m,o.decode=null!=(l=null==a?void 0:a.decode)?l:n,o.beforeReconnect=this._reconnectAuth.bind(this),((null==a?void 0:a.logLevel)||(null==a?void 0:a.log_level))&&(this.logLevel=a.logLevel||a.log_level,o.params=Object.assign(Object.assign({},o.params),{log_level:this.logLevel})),this.worker){if("undefined"!=typeof window&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=null==a?void 0:a.workerUrl,o.autoSendHeartbeat=!this.worker}return o}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var aI=class extends Error{constructor(a,b){super(a),this.name="IcebergError",this.status=b.status,this.icebergType=b.icebergType,this.icebergCode=b.icebergCode,this.details=b.details,this.isCommitStateUnknown="CommitStateUnknownException"===b.icebergType||[500,502,504].includes(b.status)&&b.icebergType?.includes("CommitState")===!0}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};async function aJ(a){return a&&"none"!==a.type?"bearer"===a.type?{Authorization:`Bearer ${a.token}`}:"header"===a.type?{[a.name]:a.value}:"custom"===a.type?await a.getHeaders():{}:{}}function aK(a){return a.join("\x1f")}var aL=class{constructor(a,b=""){this.client=a,this.prefix=b}async listNamespaces(a){let b=a?{parent:aK(a.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:b})).data.namespaces.map(a=>({namespace:a}))}async createNamespace(a,b){let c={namespace:a.namespace,properties:b?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:c})).data}async dropNamespace(a){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${aK(a.namespace)}`})}async loadNamespaceMetadata(a){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${aK(a.namespace)}`})).data.properties}}async namespaceExists(a){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${aK(a.namespace)}`}),!0}catch(a){if(a instanceof aI&&404===a.status)return!1;throw a}}async createNamespaceIfNotExists(a,b){try{return await this.createNamespace(a,b)}catch(a){if(a instanceof aI&&409===a.status)return;throw a}}};function aM(a){return a.join("\x1f")}var aN=class{constructor(a,b="",c){this.client=a,this.prefix=b,this.accessDelegation=c}async listTables(a){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${aM(a.namespace)}/tables`})).data.identifiers}async createTable(a,b){let c={};return this.accessDelegation&&(c["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${aM(a.namespace)}/tables`,body:b,headers:c})).data.metadata}async updateTable(a,b){let c=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${aM(a.namespace)}/tables/${a.name}`,body:b});return{"metadata-location":c.data["metadata-location"],metadata:c.data.metadata}}async dropTable(a,b){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${aM(a.namespace)}/tables/${a.name}`,query:{purgeRequested:String(b?.purge??!1)}})}async loadTable(a){let b={};return this.accessDelegation&&(b["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${aM(a.namespace)}/tables/${a.name}`,headers:b})).data.metadata}async tableExists(a){let b={};this.accessDelegation&&(b["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${aM(a.namespace)}/tables/${a.name}`,headers:b}),!0}catch(a){if(a instanceof aI&&404===a.status)return!1;throw a}}async createTableIfNotExists(a,b){try{return await this.createTable(a,b)}catch(c){if(c instanceof aI&&409===c.status)return await this.loadTable({namespace:a.namespace,name:b.name});throw c}}},aO=class{constructor(a){let b="v1";a.catalogName&&(b+=`/${a.catalogName}`);let c=a.baseUrl.endsWith("/")?a.baseUrl:`${a.baseUrl}/`;this.client=function(a){let b=a.fetchImpl??globalThis.fetch;return{async request({method:c,path:d,query:e,body:f,headers:g}){let h=function(a,b,c){let d=new URL(b,a);if(c)for(let[a,b]of Object.entries(c))void 0!==b&&d.searchParams.set(a,b);return d.toString()}(a.baseUrl,d,e),i=await aJ(a.auth),j=await b(h,{method:c,headers:{...f?{"Content-Type":"application/json"}:{},...i,...g},body:f?JSON.stringify(f):void 0}),k=await j.text(),l=(j.headers.get("content-type")||"").includes("application/json"),m=l&&k?JSON.parse(k):k;if(!j.ok){let a=l?m:void 0,b=a?.error;throw new aI(b?.message??`Request failed with status ${j.status}`,{status:j.status,icebergType:b?.type,icebergCode:b?.code,details:a})}return{status:j.status,headers:j.headers,data:m}}}}({baseUrl:c,auth:a.auth,fetchImpl:a.fetch}),this.accessDelegation=a.accessDelegation?.join(","),this.namespaceOps=new aL(this.client,b),this.tableOps=new aN(this.client,b,this.accessDelegation)}async listNamespaces(a){return this.namespaceOps.listNamespaces(a)}async createNamespace(a,b){return this.namespaceOps.createNamespace(a,b)}async dropNamespace(a){await this.namespaceOps.dropNamespace(a)}async loadNamespaceMetadata(a){return this.namespaceOps.loadNamespaceMetadata(a)}async listTables(a){return this.tableOps.listTables(a)}async createTable(a,b){return this.tableOps.createTable(a,b)}async updateTable(a,b){return this.tableOps.updateTable(a,b)}async dropTable(a,b){await this.tableOps.dropTable(a,b)}async loadTable(a){return this.tableOps.loadTable(a)}async namespaceExists(a){return this.namespaceOps.namespaceExists(a)}async tableExists(a){return this.tableOps.tableExists(a)}async createNamespaceIfNotExists(a,b){return this.namespaceOps.createNamespaceIfNotExists(a,b)}async createTableIfNotExists(a,b){return this.tableOps.createTableIfNotExists(a,b)}};function aP(a){return(aP="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a})(a)}function aQ(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d)}return c}function aR(a){for(var b=1;b<arguments.length;b++){var c=null!=arguments[b]?arguments[b]:{};b%2?aQ(Object(c),!0).forEach(function(b){!function(a,b,c){var d;(d=function(a,b){if("object"!=aP(a)||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=aP(d))return d;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}(b,"string"),(b="symbol"==aP(d)?d:d+"")in a)?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c}(a,b,c[b])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(c)):aQ(Object(c)).forEach(function(b){Object.defineProperty(a,b,Object.getOwnPropertyDescriptor(c,b))})}return a}var aS=class extends Error{constructor(a,b="storage",c,d){super(a),this.__isStorageError=!0,this.namespace=b,this.name="vectors"===b?"StorageVectorsError":"StorageError",this.status=c,this.statusCode=d}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function aT(a){return"object"==typeof a&&null!==a&&"__isStorageError"in a}var aU=class extends aS{constructor(a,b,c,d="storage"){super(a,d,b,c),this.name="vectors"===d?"StorageVectorsApiError":"StorageApiError",this.status=b,this.statusCode=c}toJSON(){return aR({},super.toJSON())}},aV=class extends aS{constructor(a,b,c="storage"){super(a,c),this.name="vectors"===c?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=b}};function aW(a,b,c){let d=aR({},a),e=b.toLowerCase();for(let a of Object.keys(d))a.toLowerCase()===e&&delete d[a];return d[e]=c,d}let aX=a=>{if(Array.isArray(a))return a.map(a=>aX(a));if("function"==typeof a||a!==Object(a))return a;let b={};return Object.entries(a).forEach(([a,c])=>{b[a.replace(/([-_][a-z])/gi,a=>a.toUpperCase().replace(/[-_]/g,""))]=aX(c)}),b},aY=a=>{if("object"==typeof a&&null!==a){if("string"==typeof a.msg)return a.msg;if("string"==typeof a.message)return a.message;if("string"==typeof a.error_description)return a.error_description;if("string"==typeof a.error)return a.error;if("object"==typeof a.error&&null!==a.error){let b=a.error;if("string"==typeof b.message)return b.message}}return JSON.stringify(a)},aZ=async(a,b,c,d)=>{if(null!==a&&"object"==typeof a&&"json"in a&&"function"==typeof a.json){let c=parseInt(String(a.status),10);Number.isFinite(c)||(c=500),a.json().then(a=>{let e=(null==a?void 0:a.statusCode)||(null==a?void 0:a.code)||c+"";b(new aU(aY(a),c,e,d))}).catch(()=>{let e=c+"";b(new aU(a.statusText||`HTTP ${c} error`,c,e,d))})}else b(new aV(aY(a),a,d))};async function a$(a,b,c,d,e,f,g){return new Promise((h,i)=>{a(c,((a,b,c,d)=>{let e={method:a,headers:(null==b?void 0:b.headers)||{}};if("GET"===a||"HEAD"===a||!d)return aR(aR({},e),c);if((a=>{if("object"!=typeof a||null===a)return!1;let b=Object.getPrototypeOf(a);return(null===b||b===Object.prototype||null===Object.getPrototypeOf(b))&&!(Symbol.toStringTag in a)&&!(Symbol.iterator in a)})(d)){var f;let a,c=(null==b?void 0:b.headers)||{};for(let[b,d]of Object.entries(c))"content-type"===b.toLowerCase()&&(a=d);e.headers=aW(c,"Content-Type",null!=(f=a)?f:"application/json"),e.body=JSON.stringify(d)}else e.body=d;return(null==b?void 0:b.duplex)&&(e.duplex=b.duplex),aR(aR({},e),c)})(b,d,e,f)).then(a=>{if(!a.ok)throw a;if(null==d?void 0:d.noResolveJson)return a;if("vectors"===g){let b=a.headers.get("content-type");if("0"===a.headers.get("content-length")||204===a.status||!b||!b.includes("application/json"))return{}}return a.json()}).then(a=>h(a)).catch(a=>aZ(a,i,d,g))})}function a_(a="storage"){return{get:async(b,c,d,e)=>a$(b,"GET",c,d,e,void 0,a),post:async(b,c,d,e,f)=>a$(b,"POST",c,e,f,d,a),put:async(b,c,d,e,f)=>a$(b,"PUT",c,e,f,d,a),head:async(b,c,d,e)=>a$(b,"HEAD",c,aR(aR({},d),{},{noResolveJson:!0}),e,void 0,a),remove:async(b,c,d,e,f)=>a$(b,"DELETE",c,e,f,d,a)}}let{get:a0,post:a1,put:a2,head:a3,remove:a4}=a_("storage"),a5=a_("vectors");var a6=class{constructor(a,b={},c,d="storage"){this.shouldThrowOnError=!1,this.url=a,this.headers=function(a){let b={};for(let[c,d]of Object.entries(a))b[c.toLowerCase()]=d;return b}(b),this.fetch=(a=>a?(...b)=>a(...b):(...a)=>fetch(...a))(c),this.namespace=d}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(a,b){return this.headers=aW(this.headers,a,b),this}async handleOperation(a){try{return{data:await a(),error:null}}catch(a){if(this.shouldThrowOnError)throw a;if(aT(a))return{data:null,error:a};throw a}}},a7=class{constructor(a,b){this.downloadFn=a,this.shouldThrowOnError=b}then(a,b){return this.execute().then(a,b)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(a){if(this.shouldThrowOnError)throw a;if(aT(a))return{data:null,error:a};throw a}}};d=Symbol.toStringTag;var a8=class{constructor(a,b){this.downloadFn=a,this.shouldThrowOnError=b,this[d]="BlobDownloadBuilder",this.promise=null}asStream(){return new a7(this.downloadFn,this.shouldThrowOnError)}then(a,b){return this.getPromise().then(a,b)}catch(a){return this.getPromise().catch(a)}finally(a){return this.getPromise().finally(a)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await (await this.downloadFn()).blob(),error:null}}catch(a){if(this.shouldThrowOnError)throw a;if(aT(a))return{data:null,error:a};throw a}}};let a9={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ba={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var bb=class extends a6{constructor(a,b={},c,d){super(a,b,d,"storage"),this.bucketId=c}async uploadOrUpdate(a,b,c,d){var e=this;return e.handleOperation(async()=>{let f,g=aR(aR({},ba),d),h=aR(aR({},e.headers),"POST"===a&&{"x-upsert":String(g.upsert)}),i=g.metadata;if("undefined"!=typeof Blob&&c instanceof Blob?((f=new FormData).append("cacheControl",g.cacheControl),i&&f.append("metadata",e.encodeMetadata(i)),f.append("",c)):"undefined"!=typeof FormData&&c instanceof FormData?((f=c).has("cacheControl")||f.append("cacheControl",g.cacheControl),i&&!f.has("metadata")&&f.append("metadata",e.encodeMetadata(i))):(f=c,h["cache-control"]=`max-age=${g.cacheControl}`,h["content-type"]=g.contentType,i&&(h["x-metadata"]=e.toBase64(e.encodeMetadata(i))),("undefined"!=typeof ReadableStream&&f instanceof ReadableStream||f&&"object"==typeof f&&"pipe"in f&&"function"==typeof f.pipe)&&!g.duplex&&(g.duplex="half")),null==d?void 0:d.headers)for(let[a,b]of Object.entries(d.headers))h=aW(h,a,b);let j=e._removeEmptyFolders(b),k=e._getFinalPath(j),l=await ("PUT"==a?a2:a1)(e.fetch,`${e.url}/object/${k}`,f,aR({headers:h},(null==g?void 0:g.duplex)?{duplex:g.duplex}:{}));return{path:j,id:l.Id,fullPath:l.Key}})}async upload(a,b,c){return this.uploadOrUpdate("POST",a,b,c)}async uploadToSignedUrl(a,b,c,d){var e=this;let f=e._removeEmptyFolders(a),g=e._getFinalPath(f),h=new URL(e.url+`/object/upload/sign/${g}`);return h.searchParams.set("token",b),e.handleOperation(async()=>{let a,b=aR(aR({},ba),d),g=aR(aR({},e.headers),{"x-upsert":String(b.upsert)}),i=b.metadata;if("undefined"!=typeof Blob&&c instanceof Blob?((a=new FormData).append("cacheControl",b.cacheControl),i&&a.append("metadata",e.encodeMetadata(i)),a.append("",c)):"undefined"!=typeof FormData&&c instanceof FormData?((a=c).has("cacheControl")||a.append("cacheControl",b.cacheControl),i&&!a.has("metadata")&&a.append("metadata",e.encodeMetadata(i))):(a=c,g["cache-control"]=`max-age=${b.cacheControl}`,g["content-type"]=b.contentType,i&&(g["x-metadata"]=e.toBase64(e.encodeMetadata(i))),("undefined"!=typeof ReadableStream&&a instanceof ReadableStream||a&&"object"==typeof a&&"pipe"in a&&"function"==typeof a.pipe)&&!b.duplex&&(b.duplex="half")),null==d?void 0:d.headers)for(let[a,b]of Object.entries(d.headers))g=aW(g,a,b);return{path:f,fullPath:(await a2(e.fetch,h.toString(),a,aR({headers:g},(null==b?void 0:b.duplex)?{duplex:b.duplex}:{}))).Key}})}async createSignedUploadUrl(a,b){var c=this;return c.handleOperation(async()=>{let d=c._getFinalPath(a),e=aR({},c.headers);(null==b?void 0:b.upsert)&&(e["x-upsert"]="true");let f=await a1(c.fetch,`${c.url}/object/upload/sign/${d}`,{},{headers:e}),g=new URL(c.url+f.url),h=g.searchParams.get("token");if(!h)throw new aS("No token returned by API");return{signedUrl:g.toString(),path:a,token:h}})}async update(a,b,c){return this.uploadOrUpdate("PUT",a,b,c)}async move(a,b,c){var d=this;return d.handleOperation(async()=>await a1(d.fetch,`${d.url}/object/move`,{bucketId:d.bucketId,sourceKey:a,destinationKey:b,destinationBucket:null==c?void 0:c.destinationBucket},{headers:d.headers}))}async copy(a,b,c){var d=this;return d.handleOperation(async()=>({path:(await a1(d.fetch,`${d.url}/object/copy`,{bucketId:d.bucketId,sourceKey:a,destinationKey:b,destinationBucket:null==c?void 0:c.destinationBucket},{headers:d.headers})).Key}))}async createSignedUrl(a,b,c){var d=this;return d.handleOperation(async()=>{let e=d._getFinalPath(a),f="object"==typeof(null==c?void 0:c.transform)&&null!==c.transform&&Object.keys(c.transform).length>0,g=await a1(d.fetch,`${d.url}/object/sign/${e}`,aR({expiresIn:b},f?{transform:c.transform}:{}),{headers:d.headers}),h=new URLSearchParams;(null==c?void 0:c.download)&&h.set("download",!0===c.download?"":c.download),(null==c?void 0:c.cacheNonce)!=null&&h.set("cacheNonce",String(c.cacheNonce));let i=h.toString();return{signedUrl:encodeURI(`${d.url}${g.signedURL}${i?`&${i}`:""}`)}})}async createSignedUrls(a,b,c){var d=this;return d.handleOperation(async()=>{let e=await a1(d.fetch,`${d.url}/object/sign/${d.bucketId}`,{expiresIn:b,paths:a},{headers:d.headers}),f=new URLSearchParams;(null==c?void 0:c.download)&&f.set("download",!0===c.download?"":c.download),(null==c?void 0:c.cacheNonce)!=null&&f.set("cacheNonce",String(c.cacheNonce));let g=f.toString();return e.map(a=>aR(aR({},a),{},{signedUrl:a.signedURL?encodeURI(`${d.url}${a.signedURL}${g?`&${g}`:""}`):null}))})}download(a,b,c){let d="object"==typeof(null==b?void 0:b.transform)&&null!==b.transform&&Object.keys(b.transform).length>0?"render/image/authenticated":"object",e=new URLSearchParams;(null==b?void 0:b.transform)&&this.applyTransformOptsToQuery(e,b.transform),(null==b?void 0:b.cacheNonce)!=null&&e.set("cacheNonce",String(b.cacheNonce));let f=e.toString(),g=this._getFinalPath(a);return new a8(()=>a0(this.fetch,`${this.url}/${d}/${g}${f?`?${f}`:""}`,{headers:this.headers,noResolveJson:!0},c),this.shouldThrowOnError)}async info(a){var b=this;let c=b._getFinalPath(a);return b.handleOperation(async()=>aX(await a0(b.fetch,`${b.url}/object/info/${c}`,{headers:b.headers})))}async exists(a){var b;let c=this._getFinalPath(a);try{return await a3(this.fetch,`${this.url}/object/${c}`,{headers:this.headers}),{data:!0,error:null}}catch(a){if(this.shouldThrowOnError)throw a;if(aT(a)){let c=a instanceof aU?a.status:a instanceof aV?null==(b=a.originalError)?void 0:b.status:void 0;if(void 0!==c&&[400,404].includes(c))return{data:!1,error:a}}throw a}}getPublicUrl(a,b){let c=this._getFinalPath(a),d=new URLSearchParams;(null==b?void 0:b.download)&&d.set("download",!0===b.download?"":b.download),(null==b?void 0:b.transform)&&this.applyTransformOptsToQuery(d,b.transform),(null==b?void 0:b.cacheNonce)!=null&&d.set("cacheNonce",String(b.cacheNonce));let e=d.toString(),f="object"==typeof(null==b?void 0:b.transform)&&null!==b.transform&&Object.keys(b.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${f}/public/${c}`)+(e?`?${e}`:"")}}}async remove(a){var b=this;return b.handleOperation(async()=>await a4(b.fetch,`${b.url}/object/${b.bucketId}`,{prefixes:a},{headers:b.headers}))}async list(a,b,c){var d=this;return d.handleOperation(async()=>{let e=aR(aR(aR({},a9),b),{},{prefix:a||""});return await a1(d.fetch,`${d.url}/object/list/${d.bucketId}`,e,{headers:d.headers},c)})}async listV2(a,b){var c=this;return c.handleOperation(async()=>{let d=aR({},a);return await a1(c.fetch,`${c.url}/object/list-v2/${c.bucketId}`,d,{headers:c.headers},b)})}encodeMetadata(a){return JSON.stringify(a)}toBase64(a){return"undefined"!=typeof Buffer?Buffer.from(a).toString("base64"):btoa(a)}_getFinalPath(a){return`${this.bucketId}/${a.replace(/^\/+/,"")}`}_removeEmptyFolders(a){return a.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(a,b){return b.width&&a.set("width",b.width.toString()),b.height&&a.set("height",b.height.toString()),b.resize&&a.set("resize",b.resize),b.format&&a.set("format",b.format),b.quality&&a.set("quality",b.quality.toString()),a}};let bc={"X-Client-Info":"storage-js/2.105.3"};var bd=class extends a6{constructor(a,b={},c,d){let e=new URL(a);(null==d?void 0:d.useNewHostname)&&/supabase\.(co|in|red)$/.test(e.hostname)&&!e.hostname.includes("storage.supabase.")&&(e.hostname=e.hostname.replace("supabase.","storage.supabase.")),super(e.href.replace(/\/$/,""),aR(aR({},bc),b),c,"storage")}async listBuckets(a){var b=this;return b.handleOperation(async()=>{let c=b.listBucketOptionsToQueryString(a);return await a0(b.fetch,`${b.url}/bucket${c}`,{headers:b.headers})})}async getBucket(a){var b=this;return b.handleOperation(async()=>await a0(b.fetch,`${b.url}/bucket/${a}`,{headers:b.headers}))}async createBucket(a,b={public:!1}){var c=this;return c.handleOperation(async()=>await a1(c.fetch,`${c.url}/bucket`,{id:a,name:a,type:b.type,public:b.public,file_size_limit:b.fileSizeLimit,allowed_mime_types:b.allowedMimeTypes},{headers:c.headers}))}async updateBucket(a,b){var c=this;return c.handleOperation(async()=>await a2(c.fetch,`${c.url}/bucket/${a}`,{id:a,name:a,public:b.public,file_size_limit:b.fileSizeLimit,allowed_mime_types:b.allowedMimeTypes},{headers:c.headers}))}async emptyBucket(a){var b=this;return b.handleOperation(async()=>await a1(b.fetch,`${b.url}/bucket/${a}/empty`,{},{headers:b.headers}))}async deleteBucket(a){var b=this;return b.handleOperation(async()=>await a4(b.fetch,`${b.url}/bucket/${a}`,{},{headers:b.headers}))}listBucketOptionsToQueryString(a){let b={};return a&&("limit"in a&&(b.limit=String(a.limit)),"offset"in a&&(b.offset=String(a.offset)),a.search&&(b.search=a.search),a.sortColumn&&(b.sortColumn=a.sortColumn),a.sortOrder&&(b.sortOrder=a.sortOrder)),Object.keys(b).length>0?"?"+new URLSearchParams(b).toString():""}},be=class extends a6{constructor(a,b={},c){super(a.replace(/\/$/,""),aR(aR({},bc),b),c,"storage")}async createBucket(a){var b=this;return b.handleOperation(async()=>await a1(b.fetch,`${b.url}/bucket`,{name:a},{headers:b.headers}))}async listBuckets(a){var b=this;return b.handleOperation(async()=>{let c=new URLSearchParams;(null==a?void 0:a.limit)!==void 0&&c.set("limit",a.limit.toString()),(null==a?void 0:a.offset)!==void 0&&c.set("offset",a.offset.toString()),(null==a?void 0:a.sortColumn)&&c.set("sortColumn",a.sortColumn),(null==a?void 0:a.sortOrder)&&c.set("sortOrder",a.sortOrder),(null==a?void 0:a.search)&&c.set("search",a.search);let d=c.toString(),e=d?`${b.url}/bucket?${d}`:`${b.url}/bucket`;return await a0(b.fetch,e,{headers:b.headers})})}async deleteBucket(a){var b=this;return b.handleOperation(async()=>await a4(b.fetch,`${b.url}/bucket/${a}`,{},{headers:b.headers}))}from(a){var b=this;if(!(!(!a||"string"!=typeof a||0===a.length||a.length>100||a.trim()!==a||a.includes("/")||a.includes("\\"))&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(a)))throw new aS("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 c=new aO({baseUrl:this.url,catalogName:a,auth:{type:"custom",getHeaders:async()=>b.headers},fetch:this.fetch}),d=this.shouldThrowOnError;return new Proxy(c,{get(a,b){let c=a[b];return"function"!=typeof c?c:async(...b)=>{try{return{data:await c.apply(a,b),error:null}}catch(a){if(d)throw a;return{data:null,error:a}}}}})}},bf=class extends a6{constructor(a,b={},c){super(a.replace(/\/$/,""),aR(aR({},bc),{},{"Content-Type":"application/json"},b),c,"vectors")}async createIndex(a){var b=this;return b.handleOperation(async()=>await a5.post(b.fetch,`${b.url}/CreateIndex`,a,{headers:b.headers})||{})}async getIndex(a,b){var c=this;return c.handleOperation(async()=>await a5.post(c.fetch,`${c.url}/GetIndex`,{vectorBucketName:a,indexName:b},{headers:c.headers}))}async listIndexes(a){var b=this;return b.handleOperation(async()=>await a5.post(b.fetch,`${b.url}/ListIndexes`,a,{headers:b.headers}))}async deleteIndex(a,b){var c=this;return c.handleOperation(async()=>await a5.post(c.fetch,`${c.url}/DeleteIndex`,{vectorBucketName:a,indexName:b},{headers:c.headers})||{})}},bg=class extends a6{constructor(a,b={},c){super(a.replace(/\/$/,""),aR(aR({},bc),{},{"Content-Type":"application/json"},b),c,"vectors")}async putVectors(a){var b=this;if(a.vectors.length<1||a.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return b.handleOperation(async()=>await a5.post(b.fetch,`${b.url}/PutVectors`,a,{headers:b.headers})||{})}async getVectors(a){var b=this;return b.handleOperation(async()=>await a5.post(b.fetch,`${b.url}/GetVectors`,a,{headers:b.headers}))}async listVectors(a){var b=this;if(void 0!==a.segmentCount){if(a.segmentCount<1||a.segmentCount>16)throw Error("segmentCount must be between 1 and 16");if(void 0!==a.segmentIndex&&(a.segmentIndex<0||a.segmentIndex>=a.segmentCount))throw Error(`segmentIndex must be between 0 and ${a.segmentCount-1}`)}return b.handleOperation(async()=>await a5.post(b.fetch,`${b.url}/ListVectors`,a,{headers:b.headers}))}async queryVectors(a){var b=this;return b.handleOperation(async()=>await a5.post(b.fetch,`${b.url}/QueryVectors`,a,{headers:b.headers}))}async deleteVectors(a){var b=this;if(a.keys.length<1||a.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return b.handleOperation(async()=>await a5.post(b.fetch,`${b.url}/DeleteVectors`,a,{headers:b.headers})||{})}},bh=class extends a6{constructor(a,b={},c){super(a.replace(/\/$/,""),aR(aR({},bc),{},{"Content-Type":"application/json"},b),c,"vectors")}async createBucket(a){var b=this;return b.handleOperation(async()=>await a5.post(b.fetch,`${b.url}/CreateVectorBucket`,{vectorBucketName:a},{headers:b.headers})||{})}async getBucket(a){var b=this;return b.handleOperation(async()=>await a5.post(b.fetch,`${b.url}/GetVectorBucket`,{vectorBucketName:a},{headers:b.headers}))}async listBuckets(a={}){var b=this;return b.handleOperation(async()=>await a5.post(b.fetch,`${b.url}/ListVectorBuckets`,a,{headers:b.headers}))}async deleteBucket(a){var b=this;return b.handleOperation(async()=>await a5.post(b.fetch,`${b.url}/DeleteVectorBucket`,{vectorBucketName:a},{headers:b.headers})||{})}},bi=class extends bh{constructor(a,b={}){super(a,b.headers||{},b.fetch)}from(a){return new bj(this.url,this.headers,a,this.fetch)}async createBucket(a){return super.createBucket.call(this,a)}async getBucket(a){return super.getBucket.call(this,a)}async listBuckets(a={}){return super.listBuckets.call(this,a)}async deleteBucket(a){return super.deleteBucket.call(this,a)}},bj=class extends bf{constructor(a,b,c,d){super(a,b,d),this.vectorBucketName=c}async createIndex(a){return super.createIndex.call(this,aR(aR({},a),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(a={}){return super.listIndexes.call(this,aR(aR({},a),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(a){return super.getIndex.call(this,this.vectorBucketName,a)}async deleteIndex(a){return super.deleteIndex.call(this,this.vectorBucketName,a)}index(a){return new bk(this.url,this.headers,this.vectorBucketName,a,this.fetch)}},bk=class extends bg{constructor(a,b,c,d,e){super(a,b,e),this.vectorBucketName=c,this.indexName=d}async putVectors(a){return super.putVectors.call(this,aR(aR({},a),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async getVectors(a){return super.getVectors.call(this,aR(aR({},a),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async listVectors(a={}){return super.listVectors.call(this,aR(aR({},a),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async queryVectors(a){return super.queryVectors.call(this,aR(aR({},a),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async deleteVectors(a){return super.deleteVectors.call(this,aR(aR({},a),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}},bl=class extends bd{constructor(a,b={},c,d){super(a,b,c,d)}from(a){return new bb(this.url,this.headers,a,this.fetch)}get vectors(){return new bi(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new be(this.url+"/iceberg",this.headers,this.fetch)}};let bm="2.105.3",bn={"X-Client-Info":`gotrue-js/${bm}`},bo="X-Supabase-Api-Version",bp={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},bq=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class br extends Error{constructor(a,b,c){super(a),this.__isAuthError=!0,this.name="AuthError",this.status=b,this.code=c}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function bs(a){return"object"==typeof a&&null!==a&&"__isAuthError"in a}class bt extends br{constructor(a,b,c){super(a,b,c),this.name="AuthApiError",this.status=b,this.code=c}}class bu extends br{constructor(a,b){super(a),this.name="AuthUnknownError",this.originalError=b}}class bv extends br{constructor(a,b,c,d){super(a,c,d),this.name=b,this.status=c}}class bw extends bv{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function bx(a){return bs(a)&&"AuthSessionMissingError"===a.name}class by extends bv{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class bz extends bv{constructor(a){super(a,"AuthInvalidCredentialsError",400,void 0)}}class bA extends bv{constructor(a,b=null){super(a,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=b}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class bB extends bv{constructor(a,b=null){super(a,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=b}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class bC extends bv{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 bD extends bv{constructor(a,b){super(a,"AuthRetryableFetchError",b,void 0)}}function bE(a){return bs(a)&&"AuthRetryableFetchError"===a.name}class bF extends bv{constructor(a,b,c){super(a,"AuthWeakPasswordError",b,"weak_password"),this.reasons=c}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class bG extends bv{constructor(a){super(a,"AuthInvalidJwtError",400,"invalid_jwt")}}let bH="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),bI=" \n\r=".split(""),bJ=(()=>{let a=Array(128);for(let b=0;b<a.length;b+=1)a[b]=-1;for(let b=0;b<bI.length;b+=1)a[bI[b].charCodeAt(0)]=-2;for(let b=0;b<bH.length;b+=1)a[bH[b].charCodeAt(0)]=b;return a})();function bK(a,b,c){if(null!==a)for(b.queue=b.queue<<8|a,b.queuedBits+=8;b.queuedBits>=6;)c(bH[b.queue>>b.queuedBits-6&63]),b.queuedBits-=6;else if(b.queuedBits>0)for(b.queue=b.queue<<6-b.queuedBits,b.queuedBits=6;b.queuedBits>=6;)c(bH[b.queue>>b.queuedBits-6&63]),b.queuedBits-=6}function bL(a,b,c){let d=bJ[a];if(d>-1)for(b.queue=b.queue<<6|d,b.queuedBits+=6;b.queuedBits>=8;)c(b.queue>>b.queuedBits-8&255),b.queuedBits-=8;else if(-2===d)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(a)}"`)}function bM(a){let b=[],c=a=>{b.push(String.fromCodePoint(a))},d={utf8seq:0,codepoint:0},e={queue:0,queuedBits:0},f=a=>{!function(a,b,c){if(0===b.utf8seq){if(a<=127)return c(a);for(let c=1;c<6;c+=1)if((a>>7-c&1)==0){b.utf8seq=c;break}if(2===b.utf8seq)b.codepoint=31&a;else if(3===b.utf8seq)b.codepoint=15&a;else if(4===b.utf8seq)b.codepoint=7&a;else throw Error("Invalid UTF-8 sequence");b.utf8seq-=1}else if(b.utf8seq>0){if(a<=127)throw Error("Invalid UTF-8 sequence");b.codepoint=b.codepoint<<6|63&a,b.utf8seq-=1,0===b.utf8seq&&c(b.codepoint)}}(a,d,c)};for(let b=0;b<a.length;b+=1)bL(a.charCodeAt(b),e,f);return b.join("")}function bN(a){let b=[],c={queue:0,queuedBits:0},d=a=>{b.push(a)};for(let b=0;b<a.length;b+=1)bL(a.charCodeAt(b),c,d);return new Uint8Array(b)}function bO(a){let b=[],c={queue:0,queuedBits:0},d=a=>{b.push(a)};return a.forEach(a=>bK(a,c,d)),bK(null,c,d),b.join("")}let bP=()=>"undefined"!=typeof window&&"undefined"!=typeof document,bQ={tested:!1,writable:!1},bR=()=>{if(!bP())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(a){return!1}if(bQ.tested)return bQ.writable;let a=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(a,a),globalThis.localStorage.removeItem(a),bQ.tested=!0,bQ.writable=!0}catch(a){bQ.tested=!0,bQ.writable=!1}return bQ.writable},bS=a=>a?(...b)=>a(...b):(...a)=>fetch(...a),bT=async(a,b,c)=>{await a.setItem(b,JSON.stringify(c))},bU=async(a,b)=>{let c=await a.getItem(b);if(!c)return null;try{return JSON.parse(c)}catch(a){return c}},bV=async(a,b)=>{await a.removeItem(b)};class bW{constructor(){this.promise=new bW.promiseConstructor((a,b)=>{this.resolve=a,this.reject=b})}}function bX(a){let b=a.split(".");if(3!==b.length)throw new bG("Invalid JWT structure");for(let a=0;a<b.length;a++)if(!bq.test(b[a]))throw new bG("JWT not in base64url format");return{header:JSON.parse(bM(b[0])),payload:JSON.parse(bM(b[1])),signature:bN(b[2]),raw:{header:b[0],payload:b[1]}}}async function bY(a){return await new Promise(b=>{setTimeout(()=>b(null),a)})}function bZ(a){return("0"+a.toString(16)).substr(-2)}async function b$(a){let b=new TextEncoder().encode(a);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",b))).map(a=>String.fromCharCode(a)).join("")}async function b_(a){return"undefined"==typeof crypto||void 0===crypto.subtle||"undefined"==typeof TextEncoder?(console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),a):btoa(await b$(a)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function b0(a,b,c=!1){let d=function(){let a=new Uint32Array(56);if("undefined"==typeof crypto){let a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",b=a.length,c="";for(let d=0;d<56;d++)c+=a.charAt(Math.floor(Math.random()*b));return c}return crypto.getRandomValues(a),Array.from(a,bZ).join("")}(),e=d;c&&(e+="/recovery"),await bT(a,`${b}-code-verifier`,e);let f=await b_(d),g=d===f?"plain":"s256";return[f,g]}bW.promiseConstructor=Promise;let b1=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i,b2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function b3(a){if(!b2.test(a))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function b4(a){if(!a.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 b5(){return new Proxy({},{get:(a,b)=>{if("__isUserNotAvailableProxy"===b)return!0;if("symbol"==typeof b){let a=b.toString();if("Symbol(Symbol.toPrimitive)"===a||"Symbol(Symbol.toStringTag)"===a||"Symbol(util.inspect.custom)"===a)return}throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${b}" property of the session object is not supported. Please use getUser() instead.`)},set:(a,b)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${b}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(a,b)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${b}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function b6(a){return JSON.parse(JSON.stringify(a))}let b7=a=>{if("object"==typeof a&&null!==a){if("string"==typeof a.msg)return a.msg;if("string"==typeof a.message)return a.message;if("string"==typeof a.error_description)return a.error_description;if("string"==typeof a.error)return a.error}return JSON.stringify(a)},b8=[502,503,504,520,521,522,523,524,530];async function b9(a){var b;let c,d;if(!("object"==typeof a&&null!==a&&"status"in a&&"ok"in a&&"json"in a&&"function"==typeof a.json))throw new bD(b7(a),0);if(b8.includes(a.status))throw new bD(b7(a),a.status);try{c=await a.json()}catch(a){throw new bu(b7(a),a)}let e=function(a){let b=a.headers.get(bo);if(!b||!b.match(b1))return null;try{return new Date(`${b}T00:00:00.0Z`)}catch(a){return null}}(a);if(e&&e.getTime()>=bp["2024-01-01"].timestamp&&"object"==typeof c&&c&&"string"==typeof c.code?d=c.code:"object"==typeof c&&c&&"string"==typeof c.error_code&&(d=c.error_code),d){if("weak_password"===d)throw new bF(b7(c),a.status,(null==(b=c.weak_password)?void 0:b.reasons)||[]);else if("session_not_found"===d)throw new bw}else if("object"==typeof c&&c&&"object"==typeof c.weak_password&&c.weak_password&&Array.isArray(c.weak_password.reasons)&&c.weak_password.reasons.length&&c.weak_password.reasons.reduce((a,b)=>a&&"string"==typeof b,!0))throw new bF(b7(c),a.status,c.weak_password.reasons);throw new bt(b7(c),a.status||500,d)}async function ca(a,b,c,d){var e;let f=Object.assign({},null==d?void 0:d.headers);f[bo]||(f[bo]=bp["2024-01-01"].name),(null==d?void 0:d.jwt)&&(f.Authorization=`Bearer ${d.jwt}`);let g=null!=(e=null==d?void 0:d.query)?e:{};(null==d?void 0:d.redirectTo)&&(g.redirect_to=d.redirectTo);let h=Object.keys(g).length?"?"+new URLSearchParams(g).toString():"",i=await cb(a,b,c+h,{headers:f,noResolveJson:null==d?void 0:d.noResolveJson},{},null==d?void 0:d.body);return(null==d?void 0:d.xform)?null==d?void 0:d.xform(i):{data:Object.assign({},i),error:null}}async function cb(a,b,c,d,e,f){let g,h=((a,b,c,d)=>{let e={method:a,headers:(null==b?void 0:b.headers)||{}};return"GET"===a?e:(e.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==b?void 0:b.headers),e.body=JSON.stringify(d),Object.assign(Object.assign({},e),c))})(b,d,e,f);try{g=await a(c,Object.assign({},h))}catch(a){throw console.error(a),new bD(b7(a),0)}if(g.ok||await b9(g),null==d?void 0:d.noResolveJson)return g;try{return await g.json()}catch(a){await b9(a)}}function cc(a){var b,c,d;let e=null;(d=a).access_token&&d.refresh_token&&d.expires_in&&(e=Object.assign({},a),a.expires_at||(e.expires_at=(c=a.expires_in,Math.round(Date.now()/1e3)+c)));return{data:{session:e,user:null!=(b=a.user)?b:a},error:null}}function cd(a){let b=cc(a);return!b.error&&a.weak_password&&"object"==typeof a.weak_password&&Array.isArray(a.weak_password.reasons)&&a.weak_password.reasons.length&&a.weak_password.message&&"string"==typeof a.weak_password.message&&a.weak_password.reasons.reduce((a,b)=>a&&"string"==typeof b,!0)&&(b.data.weak_password=a.weak_password),b}function ce(a){var b;return{data:{user:null!=(b=a.user)?b:a},error:null}}function cf(a){return{data:a,error:null}}function cg(a){let{action_link:b,email_otp:c,hashed_token:d,redirect_to:e,verification_type:f}=a;return{data:{properties:{action_link:b,email_otp:c,hashed_token:d,redirect_to:e,verification_type:f},user:Object.assign({},y(a,["action_link","email_otp","hashed_token","redirect_to","verification_type"]))},error:null}}function ch(a){return a}let ci=["global","local","others"];class cj{constructor({url:a="",headers:b={},fetch:c,experimental:d}){this.url=a,this.headers=b,this.fetch=bS(c),this.experimental=null!=d?d:{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(a,b=ci[0]){if(0>ci.indexOf(b))throw Error(`@supabase/auth-js: Parameter scope must be one of ${ci.join(", ")}`);try{return await ca(this.fetch,"POST",`${this.url}/logout?scope=${b}`,{headers:this.headers,jwt:a,noResolveJson:!0}),{data:null,error:null}}catch(a){if(bs(a))return{data:null,error:a};throw a}}async inviteUserByEmail(a,b={}){try{return await ca(this.fetch,"POST",`${this.url}/invite`,{body:{email:a,data:b.data},headers:this.headers,redirectTo:b.redirectTo,xform:ce})}catch(a){if(bs(a))return{data:{user:null},error:a};throw a}}async generateLink(a){try{let{options:b}=a,c=y(a,["options"]),d=Object.assign(Object.assign({},c),b);return"newEmail"in c&&(d.new_email=null==c?void 0:c.newEmail,delete d.newEmail),await ca(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:d,headers:this.headers,xform:cg,redirectTo:null==b?void 0:b.redirectTo})}catch(a){if(bs(a))return{data:{properties:null,user:null},error:a};throw a}}async createUser(a){try{return await ca(this.fetch,"POST",`${this.url}/admin/users`,{body:a,headers:this.headers,xform:ce})}catch(a){if(bs(a))return{data:{user:null},error:a};throw a}}async listUsers(a){var b,c,d,e,f,g,h;try{let i={nextPage:null,lastPage:0,total:0},j=await ca(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!=(c=null==(b=null==a?void 0:a.page)?void 0:b.toString())?c:"",per_page:null!=(e=null==(d=null==a?void 0:a.perPage)?void 0:d.toString())?e:""},xform:ch});if(j.error)throw j.error;let k=await j.json(),l=null!=(f=j.headers.get("x-total-count"))?f:0,m=null!=(h=null==(g=j.headers.get("link"))?void 0:g.split(","))?h:[];return m.length>0&&(m.forEach(a=>{let b=parseInt(a.split(";")[0].split("=")[1].substring(0,1)),c=JSON.parse(a.split(";")[1].split("=")[1]);i[`${c}Page`]=b}),i.total=parseInt(l)),{data:Object.assign(Object.assign({},k),i),error:null}}catch(a){if(bs(a))return{data:{users:[]},error:a};throw a}}async getUserById(a){b3(a);try{return await ca(this.fetch,"GET",`${this.url}/admin/users/${a}`,{headers:this.headers,xform:ce})}catch(a){if(bs(a))return{data:{user:null},error:a};throw a}}async updateUserById(a,b){b3(a);try{return await ca(this.fetch,"PUT",`${this.url}/admin/users/${a}`,{body:b,headers:this.headers,xform:ce})}catch(a){if(bs(a))return{data:{user:null},error:a};throw a}}async deleteUser(a,b=!1){b3(a);try{return await ca(this.fetch,"DELETE",`${this.url}/admin/users/${a}`,{headers:this.headers,body:{should_soft_delete:b},xform:ce})}catch(a){if(bs(a))return{data:{user:null},error:a};throw a}}async _listFactors(a){b3(a.userId);try{let{data:b,error:c}=await ca(this.fetch,"GET",`${this.url}/admin/users/${a.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:b,error:c}}catch(a){if(bs(a))return{data:null,error:a};throw a}}async _deleteFactor(a){b3(a.userId),b3(a.id);try{return{data:await ca(this.fetch,"DELETE",`${this.url}/admin/users/${a.userId}/factors/${a.id}`,{headers:this.headers}),error:null}}catch(a){if(bs(a))return{data:null,error:a};throw a}}async _listOAuthClients(a){var b,c,d,e,f,g,h;try{let i={nextPage:null,lastPage:0,total:0},j=await ca(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!=(c=null==(b=null==a?void 0:a.page)?void 0:b.toString())?c:"",per_page:null!=(e=null==(d=null==a?void 0:a.perPage)?void 0:d.toString())?e:""},xform:ch});if(j.error)throw j.error;let k=await j.json(),l=null!=(f=j.headers.get("x-total-count"))?f:0,m=null!=(h=null==(g=j.headers.get("link"))?void 0:g.split(","))?h:[];return m.length>0&&(m.forEach(a=>{let b=parseInt(a.split(";")[0].split("=")[1].substring(0,1)),c=JSON.parse(a.split(";")[1].split("=")[1]);i[`${c}Page`]=b}),i.total=parseInt(l)),{data:Object.assign(Object.assign({},k),i),error:null}}catch(a){if(bs(a))return{data:{clients:[]},error:a};throw a}}async _createOAuthClient(a){try{return await ca(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:a,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(bs(a))return{data:null,error:a};throw a}}async _getOAuthClient(a){try{return await ca(this.fetch,"GET",`${this.url}/admin/oauth/clients/${a}`,{headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(bs(a))return{data:null,error:a};throw a}}async _updateOAuthClient(a,b){try{return await ca(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${a}`,{body:b,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(bs(a))return{data:null,error:a};throw a}}async _deleteOAuthClient(a){try{return await ca(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${a}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(a){if(bs(a))return{data:null,error:a};throw a}}async _regenerateOAuthClientSecret(a){try{return await ca(this.fetch,"POST",`${this.url}/admin/oauth/clients/${a}/regenerate_secret`,{headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(bs(a))return{data:null,error:a};throw a}}async _listCustomProviders(a){try{let b={};return(null==a?void 0:a.type)&&(b.type=a.type),await ca(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:b,xform:a=>{var b;return{data:{providers:null!=(b=null==a?void 0:a.providers)?b:[]},error:null}}})}catch(a){if(bs(a))return{data:{providers:[]},error:a};throw a}}async _createCustomProvider(a){try{return await ca(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:a,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(bs(a))return{data:null,error:a};throw a}}async _getCustomProvider(a){try{return await ca(this.fetch,"GET",`${this.url}/admin/custom-providers/${a}`,{headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(bs(a))return{data:null,error:a};throw a}}async _updateCustomProvider(a,b){try{return await ca(this.fetch,"PUT",`${this.url}/admin/custom-providers/${a}`,{body:b,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(bs(a))return{data:null,error:a};throw a}}async _deleteCustomProvider(a){try{return await ca(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${a}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(a){if(bs(a))return{data:null,error:a};throw a}}async _adminListPasskeys(a){b4(this.experimental),b3(a.userId);try{return await ca(this.fetch,"GET",`${this.url}/admin/users/${a.userId}/passkeys`,{headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(bs(a))return{data:null,error:a};throw a}}async _adminDeletePasskey(a){b4(this.experimental),b3(a.userId),b3(a.passkeyId);try{return await ca(this.fetch,"DELETE",`${this.url}/admin/users/${a.userId}/passkeys/${a.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(a){if(bs(a))return{data:null,error:a};throw a}}}function ck(a={}){return{getItem:b=>a[b]||null,setItem:(b,c)=>{a[b]=c},removeItem:b=>{delete a[b]}}}let cl={debug:!!(globalThis&&bR()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class cm extends Error{constructor(a){super(a),this.isAcquireTimeout=!0}}class cn extends cm{}async function co(a,b,c){let d;cl.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",a,b);let e=new globalThis.AbortController;b>0&&(d=setTimeout(()=>{e.abort(),cl.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",a)},b)),await Promise.resolve();try{return await globalThis.navigator.locks.request(a,0===b?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:e.signal},async e=>{if(e){clearTimeout(d),cl.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",a,e.name);try{return await c()}finally{cl.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",a,e.name)}}if(0===b)throw cl.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",a),new cn(`Acquiring an exclusive Navigator LockManager lock "${a}" immediately failed`);if(cl.debug)try{let a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}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(d),await c()})}catch(f){if(b>0&&clearTimeout(d),null!==f&&"object"==typeof f&&"name"in f&&"AbortError"===f.name&&b>0)if(e.signal.aborted)return cl.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",a),console.warn(`@supabase/gotrue-js: Lock "${a}" was not released within ${b}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(a,{mode:"exclusive",steal:!0},async b=>{if(!b)return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await c();cl.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",a,b.name);try{return await c()}finally{cl.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",a,b.name)}}));else throw cl.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",a),new cn(`Lock "${a}" was released because another request stole it`);throw f}}function cp(a){if(!/^0x[a-fA-F0-9]{40}$/.test(a))throw Error(`@supabase/auth-js: Address "${a}" is invalid.`);return a.toLowerCase()}class cq extends Error{constructor({message:a,code:b,cause:c,name:d}){var e;super(a,{cause:c}),this.__isWebAuthnError=!0,this.name=null!=(e=null!=d?d:c instanceof Error?c.name:void 0)?e:"Unknown Error",this.code=b}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class cr extends cq{constructor(a,b){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:b,message:a}),this.name="WebAuthnUnknownError",this.originalError=b}}class cs{createNewAbortSignal(){if(this.controller){let a=Error("Cancelling existing WebAuthn API call for new one");a.name="AbortError",this.controller.abort(a)}let a=new AbortController;return this.controller=a,a.signal}cancelCeremony(){if(this.controller){let a=Error("Manually cancelling existing WebAuthn API call");a.name="AbortError",this.controller.abort(a),this.controller=void 0}}}let ct=new cs;function cu(a){if(!a)throw Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(a);let{challenge:b,user:c,excludeCredentials:d}=a,e=y(a,["challenge","user","excludeCredentials"]),f=bN(b).buffer,g=Object.assign(Object.assign({},c),{id:bN(c.id).buffer}),h=Object.assign(Object.assign({},e),{challenge:f,user:g});if(d&&d.length>0){h.excludeCredentials=Array(d.length);for(let a=0;a<d.length;a++){let b=d[a];h.excludeCredentials[a]=Object.assign(Object.assign({},b),{id:bN(b.id).buffer,type:b.type||"public-key",transports:b.transports})}}return h}function cv(a){if(!a)throw Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(a);let{challenge:b,allowCredentials:c}=a,d=y(a,["challenge","allowCredentials"]),e=bN(b).buffer,f=Object.assign(Object.assign({},d),{challenge:e});if(c&&c.length>0){f.allowCredentials=Array(c.length);for(let a=0;a<c.length;a++){let b=c[a];f.allowCredentials[a]=Object.assign(Object.assign({},b),{id:bN(b.id).buffer,type:b.type||"public-key",transports:b.transports})}}return f}function cw(a){var b;return"toJSON"in a&&"function"==typeof a.toJSON?a.toJSON():{id:a.id,rawId:a.id,response:{attestationObject:bO(new Uint8Array(a.response.attestationObject)),clientDataJSON:bO(new Uint8Array(a.response.clientDataJSON))},type:"public-key",clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:null!=(b=a.authenticatorAttachment)?b:void 0}}function cx(a){var b;if("toJSON"in a&&"function"==typeof a.toJSON)return a.toJSON();let c=a.getClientExtensionResults(),d=a.response;return{id:a.id,rawId:a.id,response:{authenticatorData:bO(new Uint8Array(d.authenticatorData)),clientDataJSON:bO(new Uint8Array(d.clientDataJSON)),signature:bO(new Uint8Array(d.signature)),userHandle:d.userHandle?bO(new Uint8Array(d.userHandle)):void 0},type:"public-key",clientExtensionResults:c,authenticatorAttachment:null!=(b=a.authenticatorAttachment)?b:void 0}}function cy(a){return"localhost"===a||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(a)}function cz(){var a,b;return!!(bP()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null==(a=null==navigator?void 0:navigator.credentials)?void 0:a.create)&&"function"==typeof(null==(b=null==navigator?void 0:navigator.credentials)?void 0:b.get))}async function cA(a){try{let b=await navigator.credentials.create(a);if(!b)return{data:null,error:new cr("Empty credential response",b)};if(!(b instanceof PublicKeyCredential))return{data:null,error:new cr("Browser returned unexpected credential type",b)};return{data:b,error:null}}catch(b){return{data:null,error:function({error:a,options:b}){var c,d,e;let{publicKey:f}=b;if(!f)throw Error("options was missing required publicKey property");if("AbortError"===a.name){if(b.signal instanceof AbortSignal)return new cq({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:a})}else if("ConstraintError"===a.name){if((null==(c=f.authenticatorSelection)?void 0:c.requireResidentKey)===!0)return new cq({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:a});else if("conditional"===b.mediation&&(null==(d=f.authenticatorSelection)?void 0:d.userVerification)==="required")return new cq({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:a});else if((null==(e=f.authenticatorSelection)?void 0:e.userVerification)==="required")return new cq({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:a})}else if("InvalidStateError"===a.name)return new cq({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:a});else if("NotAllowedError"===a.name)return new cq({message:a.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:a});else if("NotSupportedError"===a.name)return new cq(0===f.pubKeyCredParams.filter(a=>"public-key"===a.type).length?{message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:a}:{message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:a});else if("SecurityError"===a.name){let b=window.location.hostname;if(!cy(b))return new cq({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:a});if(f.rp.id!==b)return new cq({message:`The RP ID "${f.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:a})}else if("TypeError"===a.name){if(f.user.id.byteLength<1||f.user.id.byteLength>64)return new cq({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:a})}else if("UnknownError"===a.name)return new cq({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:a});return new cq({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:a})}({error:b,options:a})}}}async function cB(a){try{let b=await navigator.credentials.get(a);if(!b)return{data:null,error:new cr("Empty credential response",b)};if(!(b instanceof PublicKeyCredential))return{data:null,error:new cr("Browser returned unexpected credential type",b)};return{data:b,error:null}}catch(b){return{data:null,error:function({error:a,options:b}){let{publicKey:c}=b;if(!c)throw Error("options was missing required publicKey property");if("AbortError"===a.name){if(b.signal instanceof AbortSignal)return new cq({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:a})}else if("NotAllowedError"===a.name)return new cq({message:a.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:a});else if("SecurityError"===a.name){let b=window.location.hostname;if(!cy(b))return new cq({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:a});if(c.rpId!==b)return new cq({message:`The RP ID "${c.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:a})}else if("UnknownError"===a.name)return new cq({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:a});return new cq({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:a})}({error:b,options:a})}}}let cC={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},cD={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function cE(...a){let b=a=>null!==a&&"object"==typeof a&&!Array.isArray(a),c=a=>a instanceof ArrayBuffer||ArrayBuffer.isView(a),d={};for(let e of a)if(e)for(let a in e){let f=e[a];if(void 0!==f)if(Array.isArray(f))d[a]=f;else if(c(f))d[a]=f;else if(b(f)){let c=d[a];b(c)?d[a]=cE(c,f):d[a]=cE(f)}else d[a]=f}return d}class cF{constructor(a){this.client=a,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(a){return this.client.mfa.enroll(Object.assign(Object.assign({},a),{factorType:"webauthn"}))}async _challenge({factorId:a,webauthn:b,friendlyName:c,signal:d},e){var f,g,h,i,j;try{let{data:k,error:l}=await this.client.mfa.challenge({factorId:a,webauthn:b});if(!k)return{data:null,error:l};let m=null!=d?d:ct.createNewAbortSignal();if("create"===k.webauthn.type){let{user:a}=k.webauthn.credential_options.publicKey;if(!a.name)if(c)a.name=`${a.id}:${c}`;else{let b=(await this.client.getUser()).data.user,c=(null==(f=null==b?void 0:b.user_metadata)?void 0:f.name)||(null==b?void 0:b.email)||(null==b?void 0:b.id)||"User";a.name=`${a.id}:${c}`}a.displayName||(a.displayName=a.name)}switch(k.webauthn.type){case"create":{let b=(g=k.webauthn.credential_options.publicKey,h=null==e?void 0:e.create,cE(cC,g,h||{})),{data:c,error:d}=await cA({publicKey:b,signal:m});if(c)return{data:{factorId:a,challengeId:k.id,webauthn:{type:k.webauthn.type,credential_response:c}},error:null};return{data:null,error:d}}case"request":{let b=(i=k.webauthn.credential_options.publicKey,j=null==e?void 0:e.request,cE(cD,i,j||{})),{data:c,error:d}=await cB(Object.assign(Object.assign({},k.webauthn.credential_options),{publicKey:b,signal:m}));if(c)return{data:{factorId:a,challengeId:k.id,webauthn:{type:k.webauthn.type,credential_response:c}},error:null};return{data:null,error:d}}}}catch(a){if(bs(a))return{data:null,error:a};return{data:null,error:new bu("Unexpected error in challenge",a)}}}async _verify({challengeId:a,factorId:b,webauthn:c}){return this.client.mfa.verify({factorId:b,challengeId:a,webauthn:c})}async _authenticate({factorId:a,webauthn:{rpId:b="undefined"!=typeof window?window.location.hostname:void 0,rpOrigins:c="undefined"!=typeof window?[window.location.origin]:void 0,signal:d}={}},e){if(!b)return{data:null,error:new br("rpId is required for WebAuthn authentication")};try{if(!cz())return{data:null,error:new bu("Browser does not support WebAuthn",null)};let{data:f,error:g}=await this.challenge({factorId:a,webauthn:{rpId:b,rpOrigins:c},signal:d},{request:e});if(!f)return{data:null,error:g};let{webauthn:h}=f;return this._verify({factorId:a,challengeId:f.challengeId,webauthn:{type:h.type,rpId:b,rpOrigins:c,credential_response:h.credential_response}})}catch(a){if(bs(a))return{data:null,error:a};return{data:null,error:new bu("Unexpected error in authenticate",a)}}}async _register({friendlyName:a,webauthn:{rpId:b="undefined"!=typeof window?window.location.hostname:void 0,rpOrigins:c="undefined"!=typeof window?[window.location.origin]:void 0,signal:d}={}},e){if(!b)return{data:null,error:new br("rpId is required for WebAuthn registration")};try{if(!cz())return{data:null,error:new bu("Browser does not support WebAuthn",null)};let{data:f,error:g}=await this._enroll({friendlyName:a});if(!f)return await this.client.mfa.listFactors().then(b=>{var c;return null==(c=b.data)?void 0:c.all.find(b=>"webauthn"===b.factor_type&&b.friendly_name===a&&"unverified"!==b.status)}).then(a=>a?this.client.mfa.unenroll({factorId:null==a?void 0:a.id}):void 0),{data:null,error:g};let{data:h,error:i}=await this._challenge({factorId:f.id,friendlyName:f.friendly_name,webauthn:{rpId:b,rpOrigins:c},signal:d},{create:e});if(!h)return{data:null,error:i};return this._verify({factorId:f.id,challengeId:h.challengeId,webauthn:{rpId:b,rpOrigins:c,type:h.webauthn.type,credential_response:h.webauthn.credential_response}})}catch(a){if(bs(a))return{data:null,error:a};return{data:null,error:new bu("Unexpected error in register",a)}}}}if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(a){"undefined"!=typeof self&&(self.globalThis=self)}let cG={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:bn,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function cH(a,b,c){return await c()}let cI={};class cJ{get jwks(){var a,b;return null!=(b=null==(a=cI[this.storageKey])?void 0:a.jwks)?b:{keys:[]}}set jwks(a){cI[this.storageKey]=Object.assign(Object.assign({},cI[this.storageKey]),{jwks:a})}get jwks_cached_at(){var a,b;return null!=(b=null==(a=cI[this.storageKey])?void 0:a.cachedAt)?b:Number.MIN_SAFE_INTEGER}set jwks_cached_at(a){cI[this.storageKey]=Object.assign(Object.assign({},cI[this.storageKey]),{cachedAt:a})}constructor(a){var b,c,d,e;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;let f=Object.assign(Object.assign({},cG),a);if(this.storageKey=f.storageKey,this.instanceID=null!=(b=cJ.nextInstanceID[this.storageKey])?b:0,cJ.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!f.debug,"function"==typeof f.debug&&(this.logger=f.debug),this.instanceID>0&&bP()){let a=`${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(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=f.persistSession,this.autoRefreshToken=f.autoRefreshToken,this.experimental=null!=(c=f.experimental)?c:{},this.admin=new cj({url:f.url,headers:f.headers,fetch:f.fetch,experimental:this.experimental}),this.url=f.url,this.headers=f.headers,this.fetch=bS(f.fetch),this.lock=f.lock||cH,this.detectSessionInUrl=f.detectSessionInUrl,this.flowType=f.flowType,this.hasCustomAuthorizationHeader=f.hasCustomAuthorizationHeader,this.throwOnError=f.throwOnError,this.lockAcquireTimeout=f.lockAcquireTimeout,f.lock?this.lock=f.lock:this.persistSession&&bP()&&(null==(d=null==globalThis?void 0:globalThis.navigator)?void 0:d.locks)?this.lock=co:this.lock=cH,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 cF(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?(f.storage?this.storage=f.storage:bR()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=ck(this.memoryStorage)),f.userStorage&&(this.userStorage=f.userStorage)):(this.memoryStorage={},this.storage=ck(this.memoryStorage)),bP()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}null==(e=this.broadcastChannel)||e.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}f.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(a){if(this.throwOnError&&a&&a.error)throw a.error;return a}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${bm}) ${new Date().toISOString()}`}_debug(...a){return this.logDebugMessages&&this.logger(this._logPrefix(),...a),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var a;try{let b={},c="none";if(bP()&&(b=function(a){let b={},c=new URL(a);if(c.hash&&"#"===c.hash[0])try{new URLSearchParams(c.hash.substring(1)).forEach((a,c)=>{b[c]=a})}catch(a){}return c.searchParams.forEach((a,c)=>{b[c]=a}),b}(window.location.href),this._isImplicitGrantCallback(b)?c="implicit":await this._isPKCECallback(b)&&(c="pkce")),bP()&&this.detectSessionInUrl&&"none"!==c){let{data:d,error:e}=await this._getSessionFromURL(b,c);if(e){(this._debug("#_initialize()","error detecting session from URL",e),bs(e)&&"AuthImplicitGrantRedirectError"===e.name)&&(null==(a=e.details)||a.code);return{error:e}}let{session:f,redirectType:g}=d;return this._debug("#_initialize()","detected session in URL",f,"redirect type",g),await this._saveSession(f),setTimeout(async()=>{"recovery"===g?await this._notifyAllSubscribers("PASSWORD_RECOVERY",f):await this._notifyAllSubscribers("SIGNED_IN",f)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(a){if(bs(a))return this._returnResult({error:a});return this._returnResult({error:new bu("Unexpected error during initialization",a)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(a){var b,c,d;try{let{data:e,error:f}=await ca(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!=(c=null==(b=null==a?void 0:a.options)?void 0:b.data)?c:{},gotrue_meta_security:{captcha_token:null==(d=null==a?void 0:a.options)?void 0:d.captchaToken}},xform:cc});if(f||!e)return this._returnResult({data:{user:null,session:null},error:f});let g=e.session,h=e.user;return e.session&&(await this._saveSession(e.session),await this._notifyAllSubscribers("SIGNED_IN",g)),this._returnResult({data:{user:h,session:g},error:null})}catch(a){if(bs(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signUp(a){var b,c,d;try{let e;if("email"in a){let{email:c,password:d,options:f}=a,g=null,h=null;"pkce"===this.flowType&&([g,h]=await b0(this.storage,this.storageKey)),e=await ca(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==f?void 0:f.emailRedirectTo,body:{email:c,password:d,data:null!=(b=null==f?void 0:f.data)?b:{},gotrue_meta_security:{captcha_token:null==f?void 0:f.captchaToken},code_challenge:g,code_challenge_method:h},xform:cc})}else if("phone"in a){let{phone:b,password:f,options:g}=a;e=await ca(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:b,password:f,data:null!=(c=null==g?void 0:g.data)?c:{},channel:null!=(d=null==g?void 0:g.channel)?d:"sms",gotrue_meta_security:{captcha_token:null==g?void 0:g.captchaToken}},xform:cc})}else throw new bz("You must provide either an email or phone number and a password");let{data:f,error:g}=e;if(g||!f)return await bV(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:g});let h=f.session,i=f.user;return f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("SIGNED_IN",h)),this._returnResult({data:{user:i,session:h},error:null})}catch(a){if(await bV(this.storage,`${this.storageKey}-code-verifier`),bs(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(a){try{let b;if("email"in a){let{email:c,password:d,options:e}=a;b=await ca(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:c,password:d,gotrue_meta_security:{captcha_token:null==e?void 0:e.captchaToken}},xform:cd})}else if("phone"in a){let{phone:c,password:d,options:e}=a;b=await ca(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:c,password:d,gotrue_meta_security:{captcha_token:null==e?void 0:e.captchaToken}},xform:cd})}else throw new bz("You must provide either an email or phone number and a password");let{data:c,error:d}=b;if(d)return this._returnResult({data:{user:null,session:null},error:d});if(!c||!c.session||!c.user){let a=new by;return this._returnResult({data:{user:null,session:null},error:a})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:Object.assign({user:c.user,session:c.session},c.weak_password?{weakPassword:c.weak_password}:null),error:d})}catch(a){if(bs(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithOAuth(a){var b,c,d,e;return await this._handleProviderSignIn(a.provider,{redirectTo:null==(b=a.options)?void 0:b.redirectTo,scopes:null==(c=a.options)?void 0:c.scopes,queryParams:null==(d=a.options)?void 0:d.queryParams,skipBrowserRedirect:null==(e=a.options)?void 0:e.skipBrowserRedirect})}async exchangeCodeForSession(a){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(a))}async signInWithWeb3(a){let{chain:b}=a;switch(b){case"ethereum":return await this.signInWithEthereum(a);case"solana":return await this.signInWithSolana(a);default:throw Error(`@supabase/auth-js: Unsupported chain "${b}"`)}}async signInWithEthereum(a){var b,c,d,e,f,g,h,i,j,k,l,m;let n,o;if("message"in a)n=a.message,o=a.signature;else{let k,{chain:l,wallet:p,statement:q,options:r}=a;if(bP())if("object"==typeof p)k=p;else{let a=window;if("ethereum"in a&&"object"==typeof a.ethereum&&"request"in a.ethereum&&"function"==typeof a.ethereum.request)k=a.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 p||!(null==r?void 0:r.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");k=p}let s=new URL(null!=(b=null==r?void 0:r.url)?b:window.location.href),t=await k.request({method:"eth_requestAccounts"}).then(a=>a).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!t||0===t.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let u=cp(t[0]),v=null==(c=null==r?void 0:r.signInWithEthereum)?void 0:c.chainId;v||(v=parseInt(await k.request({method:"eth_chainId"}),16)),n=function(a){var b;let{chainId:c,domain:d,expirationTime:e,issuedAt:f=new Date,nonce:g,notBefore:h,requestId:i,resources:j,scheme:k,uri:l,version:m}=a;if(!Number.isInteger(c))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${c}`);if(!d)throw Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(g&&g.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${g}`);if(!l)throw Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==m)throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${m}`);if(null==(b=a.statement)?void 0:b.includes("\n"))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${a.statement}`);let n=cp(a.address),o=k?`${k}://${d}`:d,p=a.statement?`${a.statement}
|
|
`:"",q=`${o} wants you to sign in with your Ethereum account:
|
|
${n}
|
|
|
|
${p}`,r=`URI: ${l}
|
|
Version: ${m}
|
|
Chain ID: ${c}${g?`
|
|
Nonce: ${g}`:""}
|
|
Issued At: ${f.toISOString()}`;if(e&&(r+=`
|
|
Expiration Time: ${e.toISOString()}`),h&&(r+=`
|
|
Not Before: ${h.toISOString()}`),i&&(r+=`
|
|
Request ID: ${i}`),j){let a="\nResources:";for(let b of j){if(!b||"string"!=typeof b)throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${b}`);a+=`
|
|
- ${b}`}r+=a}return`${q}
|
|
${r}`}({domain:s.host,address:u,statement:q,uri:s.href,version:"1",chainId:v,nonce:null==(d=null==r?void 0:r.signInWithEthereum)?void 0:d.nonce,issuedAt:null!=(f=null==(e=null==r?void 0:r.signInWithEthereum)?void 0:e.issuedAt)?f:new Date,expirationTime:null==(g=null==r?void 0:r.signInWithEthereum)?void 0:g.expirationTime,notBefore:null==(h=null==r?void 0:r.signInWithEthereum)?void 0:h.notBefore,requestId:null==(i=null==r?void 0:r.signInWithEthereum)?void 0:i.requestId,resources:null==(j=null==r?void 0:r.signInWithEthereum)?void 0:j.resources}),o=await k.request({method:"personal_sign",params:[(m=n,"0x"+Array.from(new TextEncoder().encode(m),a=>a.toString(16).padStart(2,"0")).join("")),u]})}try{let{data:b,error:c}=await ca(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:n,signature:o},(null==(k=a.options)?void 0:k.captchaToken)?{gotrue_meta_security:{captcha_token:null==(l=a.options)?void 0:l.captchaToken}}:null),xform:cc});if(c)throw c;if(!b||!b.session||!b.user){let a=new by;return this._returnResult({data:{user:null,session:null},error:a})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:c})}catch(a){if(bs(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithSolana(a){var b,c,d,e,f,g,h,i,j,k,l,m;let n,o;if("message"in a)n=a.message,o=a.signature;else{let l,{chain:m,wallet:p,statement:q,options:r}=a;if(bP())if("object"==typeof p)l=p;else{let a=window;if("solana"in a&&"object"==typeof a.solana&&("signIn"in a.solana&&"function"==typeof a.solana.signIn||"signMessage"in a.solana&&"function"==typeof a.solana.signMessage))l=a.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 p||!(null==r?void 0:r.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");l=p}let s=new URL(null!=(b=null==r?void 0:r.url)?b:window.location.href);if("signIn"in l&&l.signIn){let a,b=await l.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},null==r?void 0:r.signInWithSolana),{version:"1",domain:s.host,uri:s.href}),q?{statement:q}:null));if(Array.isArray(b)&&b[0]&&"object"==typeof b[0])a=b[0];else if(b&&"object"==typeof b&&"signedMessage"in b&&"signature"in b)a=b;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in a&&"signature"in a&&("string"==typeof a.signedMessage||a.signedMessage instanceof Uint8Array)&&a.signature instanceof Uint8Array)n="string"==typeof a.signedMessage?a.signedMessage:new TextDecoder().decode(a.signedMessage),o=a.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in l)||"function"!=typeof l.signMessage||!("publicKey"in l)||"object"!=typeof l||!l.publicKey||!("toBase58"in l.publicKey)||"function"!=typeof l.publicKey.toBase58)throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");n=[`${s.host} wants you to sign in with your Solana account:`,l.publicKey.toBase58(),...q?["",q,""]:[""],"Version: 1",`URI: ${s.href}`,`Issued At: ${null!=(d=null==(c=null==r?void 0:r.signInWithSolana)?void 0:c.issuedAt)?d:new Date().toISOString()}`,...(null==(e=null==r?void 0:r.signInWithSolana)?void 0:e.notBefore)?[`Not Before: ${r.signInWithSolana.notBefore}`]:[],...(null==(f=null==r?void 0:r.signInWithSolana)?void 0:f.expirationTime)?[`Expiration Time: ${r.signInWithSolana.expirationTime}`]:[],...(null==(g=null==r?void 0:r.signInWithSolana)?void 0:g.chainId)?[`Chain ID: ${r.signInWithSolana.chainId}`]:[],...(null==(h=null==r?void 0:r.signInWithSolana)?void 0:h.nonce)?[`Nonce: ${r.signInWithSolana.nonce}`]:[],...(null==(i=null==r?void 0:r.signInWithSolana)?void 0:i.requestId)?[`Request ID: ${r.signInWithSolana.requestId}`]:[],...(null==(k=null==(j=null==r?void 0:r.signInWithSolana)?void 0:j.resources)?void 0:k.length)?["Resources",...r.signInWithSolana.resources.map(a=>`- ${a}`)]:[]].join("\n");let a=await l.signMessage(new TextEncoder().encode(n),"utf8");if(!a||!(a instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");o=a}}try{let{data:b,error:c}=await ca(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:n,signature:bO(o)},(null==(l=a.options)?void 0:l.captchaToken)?{gotrue_meta_security:{captcha_token:null==(m=a.options)?void 0:m.captchaToken}}:null),xform:cc});if(c)throw c;if(!b||!b.session||!b.user){let a=new by;return this._returnResult({data:{user:null,session:null},error:a})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:c})}catch(a){if(bs(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async _exchangeCodeForSession(a){let b=await bU(this.storage,`${this.storageKey}-code-verifier`),[c,d]=(null!=b?b:"").split("/");try{if(!c&&"pkce"===this.flowType)throw new bC;let{data:b,error:e}=await ca(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:a,code_verifier:c},xform:cc});if(await bV(this.storage,`${this.storageKey}-code-verifier`),e)throw e;if(!b||!b.session||!b.user){let a=new by;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("recovery"===d?"PASSWORD_RECOVERY":"SIGNED_IN",b.session)),this._returnResult({data:Object.assign(Object.assign({},b),{redirectType:null!=d?d:null}),error:e})}catch(a){if(await bV(this.storage,`${this.storageKey}-code-verifier`),bs(a))return this._returnResult({data:{user:null,session:null,redirectType:null},error:a});throw a}}async signInWithIdToken(a){try{let{options:b,provider:c,token:d,access_token:e,nonce:f}=a,{data:g,error:h}=await ca(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:c,id_token:d,access_token:e,nonce:f,gotrue_meta_security:{captcha_token:null==b?void 0:b.captchaToken}},xform:cc});if(h)return this._returnResult({data:{user:null,session:null},error:h});if(!g||!g.session||!g.user){let a=new by;return this._returnResult({data:{user:null,session:null},error:a})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:g,error:h})}catch(a){if(bs(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithOtp(a){var b,c,d,e,f;try{if("email"in a){let{email:d,options:e}=a,f=null,g=null;"pkce"===this.flowType&&([f,g]=await b0(this.storage,this.storageKey));let{error:h}=await ca(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:d,data:null!=(b=null==e?void 0:e.data)?b:{},create_user:null==(c=null==e?void 0:e.shouldCreateUser)||c,gotrue_meta_security:{captcha_token:null==e?void 0:e.captchaToken},code_challenge:f,code_challenge_method:g},redirectTo:null==e?void 0:e.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in a){let{phone:b,options:c}=a,{data:g,error:h}=await ca(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:b,data:null!=(d=null==c?void 0:c.data)?d:{},create_user:null==(e=null==c?void 0:c.shouldCreateUser)||e,gotrue_meta_security:{captcha_token:null==c?void 0:c.captchaToken},channel:null!=(f=null==c?void 0:c.channel)?f:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==g?void 0:g.message_id},error:h})}throw new bz("You must provide either an email or phone number.")}catch(a){if(await bV(this.storage,`${this.storageKey}-code-verifier`),bs(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(a){var b,c;try{let d,e;"options"in a&&(d=null==(b=a.options)?void 0:b.redirectTo,e=null==(c=a.options)?void 0:c.captchaToken);let{data:f,error:g}=await ca(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},a),{gotrue_meta_security:{captcha_token:e}}),redirectTo:d,xform:cc});if(g)throw g;if(!f)throw Error("An error occurred on token verification.");let h=f.session,i=f.user;return(null==h?void 0:h.access_token)&&(await this._saveSession(h),await this._notifyAllSubscribers("recovery"==a.type?"PASSWORD_RECOVERY":"SIGNED_IN",h)),this._returnResult({data:{user:i,session:h},error:null})}catch(a){if(bs(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithSSO(a){var b,c,d,e,f;try{let g=null,h=null;"pkce"===this.flowType&&([g,h]=await b0(this.storage,this.storageKey));let i=await ca(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in a?{provider_id:a.providerId}:null),"domain"in a?{domain:a.domain}:null),{redirect_to:null!=(c=null==(b=a.options)?void 0:b.redirectTo)?c:void 0}),(null==(d=null==a?void 0:a.options)?void 0:d.captchaToken)?{gotrue_meta_security:{captcha_token:a.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:g,code_challenge_method:h}),headers:this.headers,xform:cf});return(null==(e=i.data)?void 0:e.url)&&bP()&&!(null==(f=a.options)?void 0:f.skipBrowserRedirect)&&window.location.assign(i.data.url),this._returnResult(i)}catch(a){if(await bV(this.storage,`${this.storageKey}-code-verifier`),bs(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async a=>{let{data:{session:b},error:c}=a;if(c)throw c;if(!b)throw new bw;let{error:d}=await ca(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:b.access_token});return this._returnResult({data:{user:null,session:null},error:d})})}catch(a){if(bs(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async resend(a){try{let b=`${this.url}/resend`;if("email"in a){let{email:c,type:d,options:e}=a,{error:f}=await ca(this.fetch,"POST",b,{headers:this.headers,body:{email:c,type:d,gotrue_meta_security:{captcha_token:null==e?void 0:e.captchaToken}},redirectTo:null==e?void 0:e.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in a){let{phone:c,type:d,options:e}=a,{data:f,error:g}=await ca(this.fetch,"POST",b,{headers:this.headers,body:{phone:c,type:d,gotrue_meta_security:{captcha_token:null==e?void 0:e.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==f?void 0:f.message_id},error:g})}throw new bz("You must provide either an email or phone number and a type")}catch(a){if(bs(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async a=>a))}async _acquireLock(a,b){this._debug("#_acquireLock","begin",a);try{if(this.lockAcquired){let a=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),c=(async()=>(await a,await b()))();return this.pendingInLock.push((async()=>{try{await c}catch(a){}})()),c}return await this.lock(`lock:${this.storageKey}`,a,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let a=b();for(this.pendingInLock.push((async()=>{try{await a}catch(a){}})()),await a;this.pendingInLock.length;){let a=[...this.pendingInLock];await Promise.all(a),this.pendingInLock.splice(0,a.length)}return await a}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(a){this._debug("#_useSession","begin");try{let b=await this.__loadSession();return await a(b)}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 b=null,c=await bU(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",c),null!==c&&(this._isValidSession(c)?b=c:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!b)return{data:{session:null},error:null};let d=!!b.expires_at&&1e3*b.expires_at-Date.now()<9e4;if(this._debug("#__loadSession()",`session has${d?"":" not"} expired`,"expires_at",b.expires_at),!d){if(this.userStorage){let a=await bU(this.userStorage,this.storageKey+"-user");(null==a?void 0:a.user)?b.user=a.user:b.user=b5()}if(this.storage.isServer&&b.user&&!b.user.__isUserNotAvailableProxy){var a;let c={value:this.suppressGetSessionWarning};b.user=(a=b.user,new Proxy(a,{get:(a,b,d)=>{if("__isInsecureUserWarningProxy"===b)return!0;if("symbol"==typeof b){let c=b.toString();if("Symbol(Symbol.toPrimitive)"===c||"Symbol(Symbol.toStringTag)"===c||"Symbol(util.inspect.custom)"===c||"Symbol(nodejs.util.inspect.custom)"===c)return Reflect.get(a,b,d)}return c.value||"string"!=typeof b||(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."),c.value=!0),Reflect.get(a,b,d)}})),c.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:b},error:null}}let{data:e,error:f}=await this._callRefreshToken(b.refresh_token);if(f)return this._returnResult({data:{session:null},error:f});return this._returnResult({data:{session:e},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(a){if(a)return await this._getUser(a);await this.initializePromise;let b=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return b.data.user&&(this.suppressGetSessionWarning=!0),b}async _getUser(a){try{if(a)return await ca(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:a,xform:ce});return await this._useSession(async a=>{var b,c,d;let{data:e,error:f}=a;if(f)throw f;return(null==(b=e.session)?void 0:b.access_token)||this.hasCustomAuthorizationHeader?await ca(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!=(d=null==(c=e.session)?void 0:c.access_token)?d:void 0,xform:ce}):{data:{user:null},error:new bw}})}catch(a){if(bs(a))return bx(a)&&(await this._removeSession(),await bV(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:a});throw a}}async updateUser(a,b={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(a,b))}async _updateUser(a,b={}){try{return await this._useSession(async c=>{let{data:d,error:e}=c;if(e)throw e;if(!d.session)throw new bw;let f=d.session,g=null,h=null;"pkce"===this.flowType&&null!=a.email&&([g,h]=await b0(this.storage,this.storageKey));let{data:i,error:j}=await ca(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==b?void 0:b.emailRedirectTo,body:Object.assign(Object.assign({},a),{code_challenge:g,code_challenge_method:h}),jwt:f.access_token,xform:ce});if(j)throw j;return f.user=i.user,await this._saveSession(f),await this._notifyAllSubscribers("USER_UPDATED",f),this._returnResult({data:{user:f.user},error:null})})}catch(a){if(await bV(this.storage,`${this.storageKey}-code-verifier`),bs(a))return this._returnResult({data:{user:null},error:a});throw a}}async setSession(a){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(a))}async _setSession(a){try{if(!a.access_token||!a.refresh_token)throw new bw;let b=Date.now()/1e3,c=b,d=!0,e=null,{payload:f}=bX(a.access_token);if(f.exp&&(d=(c=f.exp)<=b),d){let{data:b,error:c}=await this._callRefreshToken(a.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!b)return{data:{user:null,session:null},error:null};e=b}else{let{data:d,error:f}=await this._getUser(a.access_token);if(f)return this._returnResult({data:{user:null,session:null},error:f});e={access_token:a.access_token,refresh_token:a.refresh_token,user:d.user,token_type:"bearer",expires_in:c-b,expires_at:c},await this._saveSession(e),await this._notifyAllSubscribers("SIGNED_IN",e)}return this._returnResult({data:{user:e.user,session:e},error:null})}catch(a){if(bs(a))return this._returnResult({data:{session:null,user:null},error:a});throw a}}async refreshSession(a){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(a))}async _refreshSession(a){try{return await this._useSession(async b=>{var c;if(!a){let{data:d,error:e}=b;if(e)throw e;a=null!=(c=d.session)?c:void 0}if(!(null==a?void 0:a.refresh_token))throw new bw;let{data:d,error:e}=await this._callRefreshToken(a.refresh_token);return e?this._returnResult({data:{user:null,session:null},error:e}):d?this._returnResult({data:{user:d.user,session:d},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(a){if(bs(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async _getSessionFromURL(a,b){var c;try{if(!bP())throw new bA("No browser detected.");if(a.error||a.error_description||a.error_code)throw new bA(a.error_description||"Error in URL with unspecified error_description",{error:a.error||"unspecified_error",code:a.error_code||"unspecified_code"});switch(b){case"implicit":if("pkce"===this.flowType)throw new bB("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new bA("Not a valid implicit grant flow url.")}if("pkce"===b){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!a.code)throw new bB("No code detected.");let{data:b,error:d}=await this._exchangeCodeForSession(a.code);if(d)throw d;let e=new URL(window.location.href);return e.searchParams.delete("code"),window.history.replaceState(window.history.state,"",e.toString()),{data:{session:b.session,redirectType:null!=(c=b.redirectType)?c:null},error:null}}let{provider_token:d,provider_refresh_token:e,access_token:f,refresh_token:g,expires_in:h,expires_at:i,token_type:j}=a;if(!f||!h||!g||!j)throw new bA("No session defined in URL");let k=Math.round(Date.now()/1e3),l=parseInt(h),m=k+l;i&&(m=parseInt(i));let n=m-k;1e3*n<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${n}s, should have been closer to ${l}s`);let o=m-l;k-o>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",o,m,k):k-o<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",o,m,k);let{data:p,error:q}=await this._getUser(f);if(q)throw q;let r={provider_token:d,provider_refresh_token:e,access_token:f,expires_in:l,expires_at:m,refresh_token:g,token_type:j,user:p.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:r,redirectType:a.type},error:null})}catch(a){if(bs(a))return this._returnResult({data:{session:null,redirectType:null},error:a});throw a}}_isImplicitGrantCallback(a){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),a):!!(a.access_token||a.error_description)}async _isPKCECallback(a){let b=await bU(this.storage,`${this.storageKey}-code-verifier`);return!!(a.code&&b)}async signOut(a={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(a))}async _signOut({scope:a}={scope:"global"}){return await this._useSession(async b=>{var c;let{data:d,error:e}=b;if(e&&!bx(e))return this._returnResult({error:e});let f=null==(c=d.session)?void 0:c.access_token;if(f){let{error:b}=await this.admin.signOut(f,a);if(b&&!(bs(b)&&"AuthApiError"===b.name&&(404===b.status||401===b.status||403===b.status)||bx(b)))return this._returnResult({error:b})}return"others"!==a&&(await this._removeSession(),await bV(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(a){let b=Symbol("auth-callback"),c={id:b,callback:a,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",b),this.stateChangeEmitters.delete(b)}};return this._debug("#onAuthStateChange()","registered callback with id",b),this.stateChangeEmitters.set(b,c),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(b)})})(),{data:{subscription:c}}}async _emitInitialSession(a){return await this._useSession(async b=>{var c,d;try{let{data:{session:d},error:e}=b;if(e)throw e;await (null==(c=this.stateChangeEmitters.get(a))?void 0:c.callback("INITIAL_SESSION",d)),this._debug("INITIAL_SESSION","callback id",a,"session",d)}catch(b){await (null==(d=this.stateChangeEmitters.get(a))?void 0:d.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",a,"error",b),bx(b)?console.warn(b):console.error(b)}})}async resetPasswordForEmail(a,b={}){let c=null,d=null;"pkce"===this.flowType&&([c,d]=await b0(this.storage,this.storageKey,!0));try{return await ca(this.fetch,"POST",`${this.url}/recover`,{body:{email:a,code_challenge:c,code_challenge_method:d,gotrue_meta_security:{captcha_token:b.captchaToken}},headers:this.headers,redirectTo:b.redirectTo})}catch(a){if(await bV(this.storage,`${this.storageKey}-code-verifier`),bs(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var a;try{let{data:b,error:c}=await this.getUser();if(c)throw c;return this._returnResult({data:{identities:null!=(a=b.user.identities)?a:[]},error:null})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async linkIdentity(a){return"token"in a?this.linkIdentityIdToken(a):this.linkIdentityOAuth(a)}async linkIdentityOAuth(a){var b;try{let{data:c,error:d}=await this._useSession(async b=>{var c,d,e,f,g;let{data:h,error:i}=b;if(i)throw i;let j=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,a.provider,{redirectTo:null==(c=a.options)?void 0:c.redirectTo,scopes:null==(d=a.options)?void 0:d.scopes,queryParams:null==(e=a.options)?void 0:e.queryParams,skipBrowserRedirect:!0});return await ca(this.fetch,"GET",j,{headers:this.headers,jwt:null!=(g=null==(f=h.session)?void 0:f.access_token)?g:void 0})});if(d)throw d;return!bP()||(null==(b=a.options)?void 0:b.skipBrowserRedirect)||window.location.assign(null==c?void 0:c.url),this._returnResult({data:{provider:a.provider,url:null==c?void 0:c.url},error:null})}catch(b){if(bs(b))return this._returnResult({data:{provider:a.provider,url:null},error:b});throw b}}async linkIdentityIdToken(a){return await this._useSession(async b=>{var c;try{let{error:d,data:{session:e}}=b;if(d)throw d;let{options:f,provider:g,token:h,access_token:i,nonce:j}=a,{data:k,error:l}=await ca(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!=(c=null==e?void 0:e.access_token)?c:void 0,body:{provider:g,id_token:h,access_token:i,nonce:j,link_identity:!0,gotrue_meta_security:{captcha_token:null==f?void 0:f.captchaToken}},xform:cc});if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!k||!k.session||!k.user)return this._returnResult({data:{user:null,session:null},error:new by});return k.session&&(await this._saveSession(k.session),await this._notifyAllSubscribers("USER_UPDATED",k.session)),this._returnResult({data:k,error:l})}catch(a){if(await bV(this.storage,`${this.storageKey}-code-verifier`),bs(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}})}async unlinkIdentity(a){try{return await this._useSession(async b=>{var c,d;let{data:e,error:f}=b;if(f)throw f;return await ca(this.fetch,"DELETE",`${this.url}/user/identities/${a.identity_id}`,{headers:this.headers,jwt:null!=(d=null==(c=e.session)?void 0:c.access_token)?d:void 0})})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _refreshAccessToken(a){let b=`#_refreshAccessToken(${a.substring(0,5)}...)`;this._debug(b,"begin");try{var c,d;let e=Date.now();return await (c=async c=>(c>0&&await bY(200*Math.pow(2,c-1)),this._debug(b,"refreshing attempt",c),await ca(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:a},headers:this.headers,xform:cc})),d=(a,b)=>{let c=200*Math.pow(2,a);return b&&bE(b)&&Date.now()+c-e<3e4},new Promise((a,b)=>{(async()=>{for(let e=0;e<1/0;e++)try{let b=await c(e);if(!d(e,null,b))return void a(b)}catch(a){if(!d(e,a))return void b(a)}})()}))}catch(a){if(this._debug(b,"error",a),bs(a))return this._returnResult({data:{session:null,user:null},error:a});throw a}finally{this._debug(b,"end")}}_isValidSession(a){return"object"==typeof a&&null!==a&&"access_token"in a&&"refresh_token"in a&&"expires_at"in a}async _handleProviderSignIn(a,b){let c=await this._getUrlForProvider(`${this.url}/authorize`,a,{redirectTo:b.redirectTo,scopes:b.scopes,queryParams:b.queryParams});return this._debug("#_handleProviderSignIn()","provider",a,"options",b,"url",c),bP()&&!b.skipBrowserRedirect&&window.location.assign(c),{data:{provider:a,url:c},error:null}}async _recoverAndRefresh(){var a,b;let c="#_recoverAndRefresh()";this._debug(c,"begin");try{let d=await bU(this.storage,this.storageKey);if(d&&this.userStorage){let b=await bU(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!b&&(b={user:d.user},await bT(this.userStorage,this.storageKey+"-user",b)),d.user=null!=(a=null==b?void 0:b.user)?a:b5()}else if(d&&!d.user&&!d.user){let a=await bU(this.storage,this.storageKey+"-user");a&&(null==a?void 0:a.user)?(d.user=a.user,await bV(this.storage,this.storageKey+"-user"),await bT(this.storage,this.storageKey,d)):d.user=b5()}if(this._debug(c,"session from storage",d),!this._isValidSession(d)){this._debug(c,"session is not valid"),null!==d&&await this._removeSession();return}let e=(null!=(b=d.expires_at)?b:1/0)*1e3-Date.now()<9e4;if(this._debug(c,`session has${e?"":" not"} expired with margin of 90000s`),e){if(this.autoRefreshToken&&d.refresh_token){let{error:a}=await this._callRefreshToken(d.refresh_token);a&&(console.error(a),bE(a)||(this._debug(c,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(d.user&&!0===d.user.__isUserNotAvailableProxy)try{let{data:a,error:b}=await this._getUser(d.access_token);!b&&(null==a?void 0:a.user)?(d.user=a.user,await this._saveSession(d),await this._notifyAllSubscribers("SIGNED_IN",d)):this._debug(c,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(c,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",d)}catch(a){this._debug(c,"error",a),console.error(a);return}finally{this._debug(c,"end")}}async _callRefreshToken(a){var b,c;if(!a)throw new bw;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let d=`#_callRefreshToken(${a.substring(0,5)}...)`;this._debug(d,"begin");try{this.refreshingDeferred=new bW;let{data:b,error:c}=await this._refreshAccessToken(a);if(c)throw c;if(!b.session)throw new bw;await this._saveSession(b.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",b.session);let d={data:b.session,error:null};return this.refreshingDeferred.resolve(d),d}catch(a){if(this._debug(d,"error",a),bs(a)){let c={data:null,error:a};return bE(a)||await this._removeSession(),null==(b=this.refreshingDeferred)||b.resolve(c),c}throw null==(c=this.refreshingDeferred)||c.reject(a),a}finally{this.refreshingDeferred=null,this._debug(d,"end")}}async _notifyAllSubscribers(a,b,c=!0){let d=`#_notifyAllSubscribers(${a})`;this._debug(d,"begin",b,`broadcast = ${c}`);try{this.broadcastChannel&&c&&this.broadcastChannel.postMessage({event:a,session:b});let d=[],e=Array.from(this.stateChangeEmitters.values()).map(async c=>{try{await c.callback(a,b)}catch(a){d.push(a)}});if(await Promise.all(e),d.length>0){for(let a=0;a<d.length;a+=1)console.error(d[a]);throw d[0]}}finally{this._debug(d,"end")}}async _saveSession(a){this._debug("#_saveSession()",a),this.suppressGetSessionWarning=!0,await bV(this.storage,`${this.storageKey}-code-verifier`);let b=Object.assign({},a),c=b.user&&!0===b.user.__isUserNotAvailableProxy;if(this.userStorage){!c&&b.user&&await bT(this.userStorage,this.storageKey+"-user",{user:b.user});let a=Object.assign({},b);delete a.user;let d=b6(a);await bT(this.storage,this.storageKey,d)}else{let a=b6(b);await bT(this.storage,this.storageKey,a)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await bV(this.storage,this.storageKey),await bV(this.storage,this.storageKey+"-code-verifier"),await bV(this.storage,this.storageKey+"-user"),this.userStorage&&await bV(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let a=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{a&&bP()&&(null==window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",a)}catch(a){console.error("removing visibilitychange callback failed",a)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let a=setInterval(()=>this._autoRefreshTokenTick(),3e4);this.autoRefreshTicker=a,a&&"object"==typeof a&&"function"==typeof a.unref?a.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(a);let b=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=b,b&&"object"==typeof b&&"function"==typeof b.unref?b.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(b)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let a=this.autoRefreshTicker;this.autoRefreshTicker=null,a&&clearInterval(a);let b=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,b&&clearTimeout(b)}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 a=Date.now();try{return await this._useSession(async b=>{let{data:{session:c}}=b;if(!c||!c.refresh_token||!c.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let d=Math.floor((1e3*c.expires_at-a)/3e4);this._debug("#_autoRefreshTokenTick()",`access token expires in ${d} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),d<=3&&await this._callRefreshToken(c.refresh_token)})}catch(a){console.error("Auto refresh tick failed with error. This is likely a transient error.",a)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(a){if(a instanceof cm)this._debug("auto refresh token tick lock not available");else throw a}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!bP()||!(null==window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(a){this._debug("#visibilityChangedCallback","error",a)}},null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(a){console.error("_handleVisibilityChange",a)}}async _onVisibilityChanged(a){let b=`#_onVisibilityChanged(${a})`;this._debug(b,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),a||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if("visible"!==document.visibilityState)return void this._debug(b,"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(a,b,c){let d=[`provider=${encodeURIComponent(b)}`];if((null==c?void 0:c.redirectTo)&&d.push(`redirect_to=${encodeURIComponent(c.redirectTo)}`),(null==c?void 0:c.scopes)&&d.push(`scopes=${encodeURIComponent(c.scopes)}`),"pkce"===this.flowType){let[a,b]=await b0(this.storage,this.storageKey),c=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(b)}`});d.push(c.toString())}if(null==c?void 0:c.queryParams){let a=new URLSearchParams(c.queryParams);d.push(a.toString())}return(null==c?void 0:c.skipBrowserRedirect)&&d.push(`skip_http_redirect=${c.skipBrowserRedirect}`),`${a}?${d.join("&")}`}async _unenroll(a){try{return await this._useSession(async b=>{var c;let{data:d,error:e}=b;return e?this._returnResult({data:null,error:e}):await ca(this.fetch,"DELETE",`${this.url}/factors/${a.factorId}`,{headers:this.headers,jwt:null==(c=null==d?void 0:d.session)?void 0:c.access_token})})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _enroll(a){try{return await this._useSession(async b=>{var c,d;let{data:e,error:f}=b;if(f)return this._returnResult({data:null,error:f});let g=Object.assign({friendly_name:a.friendlyName,factor_type:a.factorType},"phone"===a.factorType?{phone:a.phone}:"totp"===a.factorType?{issuer:a.issuer}:{}),{data:h,error:i}=await ca(this.fetch,"POST",`${this.url}/factors`,{body:g,headers:this.headers,jwt:null==(c=null==e?void 0:e.session)?void 0:c.access_token});return i?this._returnResult({data:null,error:i}):("totp"===a.factorType&&"totp"===h.type&&(null==(d=null==h?void 0:h.totp)?void 0:d.qr_code)&&(h.totp.qr_code=`data:image/svg+xml;utf-8,${h.totp.qr_code}`),this._returnResult({data:h,error:null}))})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _verify(a){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async b=>{var c;let{data:d,error:e}=b;if(e)return this._returnResult({data:null,error:e});let f=Object.assign({challenge_id:a.challengeId},"webauthn"in a?{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_response:"create"===a.webauthn.type?cw(a.webauthn.credential_response):cx(a.webauthn.credential_response)})}:{code:a.code}),{data:g,error:h}=await ca(this.fetch,"POST",`${this.url}/factors/${a.factorId}/verify`,{body:f,headers:this.headers,jwt:null==(c=null==d?void 0:d.session)?void 0:c.access_token});return h?this._returnResult({data:null,error:h}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+g.expires_in},g)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",g),this._returnResult({data:g,error:h}))})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}})}async _challenge(a){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async b=>{var c;let{data:d,error:e}=b;if(e)return this._returnResult({data:null,error:e});let f=await ca(this.fetch,"POST",`${this.url}/factors/${a.factorId}/challenge`,{body:a,headers:this.headers,jwt:null==(c=null==d?void 0:d.session)?void 0:c.access_token});if(f.error)return f;let{data:g}=f;if("webauthn"!==g.type)return{data:g,error:null};switch(g.webauthn.type){case"create":return{data:Object.assign(Object.assign({},g),{webauthn:Object.assign(Object.assign({},g.webauthn),{credential_options:Object.assign(Object.assign({},g.webauthn.credential_options),{publicKey:cu(g.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},g),{webauthn:Object.assign(Object.assign({},g.webauthn),{credential_options:Object.assign(Object.assign({},g.webauthn.credential_options),{publicKey:cv(g.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}})}async _challengeAndVerify(a){let{data:b,error:c}=await this._challenge({factorId:a.factorId});return c?this._returnResult({data:null,error:c}):await this._verify({factorId:a.factorId,challengeId:b.id,code:a.code})}async _listFactors(){var a;let{data:{user:b},error:c}=await this.getUser();if(c)return{data:null,error:c};let d={all:[],phone:[],totp:[],webauthn:[]};for(let c of null!=(a=null==b?void 0:b.factors)?a:[])d.all.push(c),"verified"===c.status&&d[c.factor_type].push(c);return{data:d,error:null}}async _getAuthenticatorAssuranceLevel(a){var b,c,d,e;if(a)try{let{payload:d}=bX(a),e=null;d.aal&&(e=d.aal);let f=e,{data:{user:g},error:h}=await this.getUser(a);if(h)return this._returnResult({data:null,error:h});(null!=(c=null==(b=null==g?void 0:g.factors)?void 0:b.filter(a=>"verified"===a.status))?c:[]).length>0&&(f="aal2");let i=d.amr||[];return{data:{currentLevel:e,nextLevel:f,currentAuthenticationMethods:i},error:null}}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}let{data:{session:f},error:g}=await this.getSession();if(g)return this._returnResult({data:null,error:g});if(!f)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:h}=bX(f.access_token),i=null;h.aal&&(i=h.aal);let j=i;return(null!=(e=null==(d=f.user.factors)?void 0:d.filter(a=>"verified"===a.status))?e:[]).length>0&&(j="aal2"),{data:{currentLevel:i,nextLevel:j,currentAuthenticationMethods:h.amr||[]},error:null}}async _getAuthorizationDetails(a){try{return await this._useSession(async b=>{let{data:{session:c},error:d}=b;return d?this._returnResult({data:null,error:d}):c?await ca(this.fetch,"GET",`${this.url}/oauth/authorizations/${a}`,{headers:this.headers,jwt:c.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new bw})})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _approveAuthorization(a,b){try{return await this._useSession(async c=>{let{data:{session:d},error:e}=c;if(e)return this._returnResult({data:null,error:e});if(!d)return this._returnResult({data:null,error:new bw});let f=await ca(this.fetch,"POST",`${this.url}/oauth/authorizations/${a}/consent`,{headers:this.headers,jwt:d.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return f.data&&f.data.redirect_url&&bP()&&!(null==b?void 0:b.skipBrowserRedirect)&&window.location.assign(f.data.redirect_url),f})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _denyAuthorization(a,b){try{return await this._useSession(async c=>{let{data:{session:d},error:e}=c;if(e)return this._returnResult({data:null,error:e});if(!d)return this._returnResult({data:null,error:new bw});let f=await ca(this.fetch,"POST",`${this.url}/oauth/authorizations/${a}/consent`,{headers:this.headers,jwt:d.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return f.data&&f.data.redirect_url&&bP()&&!(null==b?void 0:b.skipBrowserRedirect)&&window.location.assign(f.data.redirect_url),f})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _listOAuthGrants(){try{return await this._useSession(async a=>{let{data:{session:b},error:c}=a;return c?this._returnResult({data:null,error:c}):b?await ca(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:b.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new bw})})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _revokeOAuthGrant(a){try{return await this._useSession(async b=>{let{data:{session:c},error:d}=b;return d?this._returnResult({data:null,error:d}):c?(await ca(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:c.access_token,query:{client_id:a.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new bw})})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async fetchJwk(a,b={keys:[]}){let c=b.keys.find(b=>b.kid===a);if(c)return c;let d=Date.now();if((c=this.jwks.keys.find(b=>b.kid===a))&&this.jwks_cached_at+6e5>d)return c;let{data:e,error:f}=await ca(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(f)throw f;return e.keys&&0!==e.keys.length&&(this.jwks=e,this.jwks_cached_at=d,c=e.keys.find(b=>b.kid===a))?c:null}async getClaims(a,b={}){try{let c=a;if(!c){let{data:a,error:b}=await this.getSession();if(b||!a.session)return this._returnResult({data:null,error:b});c=a.session.access_token}let{header:d,payload:e,signature:f,raw:{header:g,payload:h}}=bX(c);(null==b?void 0:b.allowExpired)||function(a){if(!a)throw Error("Missing exp claim");if(a<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}(e.exp);let i=!d.alg||d.alg.startsWith("HS")||!d.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(d.kid,(null==b?void 0:b.keys)?{keys:b.keys}:null==b?void 0:b.jwks);if(!i){let{error:a}=await this.getUser(c);if(a)throw a;return{data:{claims:e,header:d,signature:f},error:null}}let j=function(a){switch(a){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")}}(d.alg),k=await crypto.subtle.importKey("jwk",i,j,!0,["verify"]);if(!await crypto.subtle.verify(j,k,f,function(a){let b=[];return!function(a,b){for(let c=0;c<a.length;c+=1){let d=a.charCodeAt(c);if(d>55295&&d<=56319){let b=(d-55296)*1024&65535;d=(a.charCodeAt(c+1)-56320&65535|b)+65536,c+=1}!function(a,b){if(a<=127)return b(a);if(a<=2047){b(192|a>>6),b(128|63&a);return}if(a<=65535){b(224|a>>12),b(128|a>>6&63),b(128|63&a);return}if(a<=1114111){b(240|a>>18),b(128|a>>12&63),b(128|a>>6&63),b(128|63&a);return}throw Error(`Unrecognized Unicode codepoint: ${a.toString(16)}`)}(d,b)}}(a,a=>b.push(a)),new Uint8Array(b)}(`${g}.${h}`)))throw new bG("Invalid JWT signature");return{data:{claims:e,header:d,signature:f},error:null}}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async signInWithPasskey(a){var b,c,d;b4(this.experimental);try{if(!cz())return this._returnResult({data:null,error:new bu("Browser does not support WebAuthn",null)});let{data:e,error:f}=await this._startPasskeyAuthentication({options:{captchaToken:null==(b=null==a?void 0:a.options)?void 0:b.captchaToken}});if(f||!e)return this._returnResult({data:null,error:f});let g=cv(e.options),h=null!=(d=null==(c=null==a?void 0:a.options)?void 0:c.signal)?d:ct.createNewAbortSignal(),{data:i,error:j}=await cB({publicKey:g,signal:h});if(j||!i)return this._returnResult({data:null,error:null!=j?j:new bu("WebAuthn ceremony failed",null)});let k=cx(i);return this._verifyPasskeyAuthentication({challengeId:e.challenge_id,credential:k})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async registerPasskey(a){var b,c;b4(this.experimental);try{if(!cz())return this._returnResult({data:null,error:new bu("Browser does not support WebAuthn",null)});let{data:d,error:e}=await this._startPasskeyRegistration();if(e||!d)return this._returnResult({data:null,error:e});let f=cu(d.options),g=null!=(c=null==(b=null==a?void 0:a.options)?void 0:b.signal)?c:ct.createNewAbortSignal(),{data:h,error:i}=await cA({publicKey:f,signal:g});if(i||!h)return this._returnResult({data:null,error:null!=i?i:new bu("WebAuthn ceremony failed",null)});let j=cw(h);return this._verifyPasskeyRegistration({challengeId:d.challenge_id,credential:j})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _startPasskeyRegistration(){b4(this.experimental);try{return await this._useSession(async a=>{let{data:{session:b},error:c}=a;if(c)return this._returnResult({data:null,error:c});if(!b)return this._returnResult({data:null,error:new bw});let{data:d,error:e}=await ca(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:b.access_token,body:{}});return e?this._returnResult({data:null,error:e}):this._returnResult({data:d,error:null})})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _verifyPasskeyRegistration(a){b4(this.experimental);try{return await this._useSession(async b=>{let{data:{session:c},error:d}=b;if(d)return this._returnResult({data:null,error:d});if(!c)return this._returnResult({data:null,error:new bw});let{data:e,error:f}=await ca(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:c.access_token,body:{challenge_id:a.challengeId,credential:a.credential}});return f?this._returnResult({data:null,error:f}):this._returnResult({data:e,error:null})})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _startPasskeyAuthentication(a){var b;b4(this.experimental);try{let{data:c,error:d}=await ca(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:null==(b=null==a?void 0:a.options)?void 0:b.captchaToken}}});if(d)return this._returnResult({data:null,error:d});return this._returnResult({data:c,error:null})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _verifyPasskeyAuthentication(a){b4(this.experimental);try{let{data:b,error:c}=await ca(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:a.challengeId,credential:a.credential},xform:cc});if(c)return this._returnResult({data:null,error:c});return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:b,error:null})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _listPasskeys(){b4(this.experimental);try{return await this._useSession(async a=>{let{data:{session:b},error:c}=a;if(c)return this._returnResult({data:null,error:c});if(!b)return this._returnResult({data:null,error:new bw});let{data:d,error:e}=await ca(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:b.access_token,xform:a=>({data:a,error:null})});return e?this._returnResult({data:null,error:e}):this._returnResult({data:d,error:null})})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _updatePasskey(a){b4(this.experimental);try{return await this._useSession(async b=>{let{data:{session:c},error:d}=b;if(d)return this._returnResult({data:null,error:d});if(!c)return this._returnResult({data:null,error:new bw});let{data:e,error:f}=await ca(this.fetch,"PATCH",`${this.url}/passkeys/${a.passkeyId}`,{headers:this.headers,jwt:c.access_token,body:{friendly_name:a.friendlyName}});return f?this._returnResult({data:null,error:f}):this._returnResult({data:e,error:null})})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}async _deletePasskey(a){b4(this.experimental);try{return await this._useSession(async b=>{let{data:{session:c},error:d}=b;if(d)return this._returnResult({data:null,error:d});if(!c)return this._returnResult({data:null,error:new bw});let{error:e}=await ca(this.fetch,"DELETE",`${this.url}/passkeys/${a.passkeyId}`,{headers:this.headers,jwt:c.access_token,noResolveJson:!0});return e?this._returnResult({data:null,error:e}):this._returnResult({data:null,error:null})})}catch(a){if(bs(a))return this._returnResult({data:null,error:a});throw a}}}cJ.nextInstanceID={};let cK=cJ,cL="";cL="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";let cM={headers:{"X-Client-Info":`supabase-js-${cL}/2.105.3`}},cN={schema:"public"},cO={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},cP={};function cQ(a){return(cQ="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a})(a)}function cR(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d)}return c}function cS(a){for(var b=1;b<arguments.length;b++){var c=null!=arguments[b]?arguments[b]:{};b%2?cR(Object(c),!0).forEach(function(b){!function(a,b,c){var d;(d=function(a,b){if("object"!=cQ(a)||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=cQ(d))return d;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}(b,"string"),(b="symbol"==cQ(d)?d:d+"")in a)?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c}(a,b,c[b])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(c)):cR(Object(c)).forEach(function(b){Object.defineProperty(a,b,Object.getOwnPropertyDescriptor(c,b))})}return a}var cT=class extends cK{constructor(a){super(a)}},cU=class{constructor(a,b,c){var d,e,f;this.supabaseUrl=a,this.supabaseKey=b;let g=function(a){let b=null==a?void 0:a.trim();if(!b)throw Error("supabaseUrl is required.");if(!b.match(/^https?:\/\//i))throw Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(b.endsWith("/")?b:b+"/")}catch(a){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}(a);if(!b)throw Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",g),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",g),this.storageUrl=new URL("storage/v1",g),this.functionsUrl=new URL("functions/v1",g);let h=`sb-${g.hostname.split(".")[0]}-auth-token`,i=function(a,b){var c,d;let{db:e,auth:f,realtime:g,global:h}=a,{db:i,auth:j,realtime:k,global:l}=b,m={db:cS(cS({},i),e),auth:cS(cS({},j),f),realtime:cS(cS({},k),g),storage:{},global:cS(cS(cS({},l),h),{},{headers:cS(cS({},null!=(c=null==l?void 0:l.headers)?c:{}),null!=(d=null==h?void 0:h.headers)?d:{})}),accessToken:async()=>""};return a.accessToken?m.accessToken=a.accessToken:delete m.accessToken,m}(null!=c?c:{},{db:cN,realtime:cP,auth:cS(cS({},cO),{},{storageKey:h}),global:cM});this.storageKey=null!=(d=i.auth.storageKey)?d:"",this.headers=null!=(e=i.global.headers)?e:{},i.accessToken?(this.accessToken=i.accessToken,this.auth=new Proxy({},{get:(a,b)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(b)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!=(f=i.auth)?f:{},this.headers,i.global.fetch),this.fetch=((a,b,c)=>{let d=(a=>a?(...b)=>a(...b):(...a)=>fetch(...a))(c),e=Headers;return async(c,f)=>{var g;let h=null!=(g=await b())?g:a,i=new e(null==f?void 0:f.headers);return i.has("apikey")||i.set("apikey",a),i.has("Authorization")||i.set("Authorization",`Bearer ${h}`),d(c,cS(cS({},f),{},{headers:i}))}})(b,this._getAccessToken.bind(this),i.global.fetch),this.realtime=this._initRealtimeClient(cS({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},i.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(a=>this.realtime.setAuth(a)).catch(a=>console.warn("Failed to set initial Realtime auth token:",a)),this.rest=new R(new URL("rest/v1",g).href,{headers:this.headers,schema:i.db.schema,fetch:this.fetch,timeout:i.db.timeout,urlLengthLimit:i.db.urlLengthLimit}),this.storage=new bl(this.storageUrl.href,this.headers,this.fetch,null==c?void 0:c.storage),i.accessToken||this._listenForAuthEvents()}get functions(){return new D(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(a){return this.rest.from(a)}schema(a){return this.rest.schema(a)}rpc(a,b={},c={head:!1,get:!1,count:void 0}){return this.rest.rpc(a,b,c)}channel(a,b={config:{}}){return this.realtime.channel(a,b)}getChannels(){return this.realtime.getChannels()}removeChannel(a){return this.realtime.removeChannel(a)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var a,b;if(this.accessToken)return await this.accessToken();let{data:c}=await this.auth.getSession();return null!=(a=null==(b=c.session)?void 0:b.access_token)?a:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:a,persistSession:b,detectSessionInUrl:c,storage:d,userStorage:e,storageKey:f,flowType:g,lock:h,debug:i,throwOnError:j,experimental:k,lockAcquireTimeout:l,skipAutoInitialize:m},n,o){let p={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new cT({url:this.authUrl.href,headers:cS(cS({},p),n),storageKey:f,autoRefreshToken:a,persistSession:b,detectSessionInUrl:c,storage:d,userStorage:e,flowType:g,lock:h,debug:i,throwOnError:j,experimental:k,fetch:o,lockAcquireTimeout:l,skipAutoInitialize:m,hasCustomAuthorizationHeader:Object.keys(this.headers).some(a=>"authorization"===a.toLowerCase())})}_initRealtimeClient(a){return new aH(this.realtimeUrl.href,cS(cS({},a),{},{params:cS(cS({},{apikey:this.supabaseKey}),null==a?void 0:a.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((a,b)=>{this._handleTokenChanged(a,"CLIENT",null==b?void 0:b.access_token)})}_handleTokenChanged(a,b,c){("TOKEN_REFRESHED"===a||"SIGNED_IN"===a)&&this.changedAccessToken!==c?(this.changedAccessToken=c,this.realtime.setAuth(c)):"SIGNED_OUT"===a&&(this.realtime.setAuth(),"STORAGE"==b&&this.auth.signOut(),this.changedAccessToken=void 0)}};function cV(a,b,c){if(!a||!b)throw Error(`Your project's URL and Key are required to create a Supabase client!
|
|
|
|
Check your Supabase project's API settings to find these values
|
|
|
|
https://supabase.com/dashboard/project/_/settings/api`);let{storage:d,getAll:e,setAll:f,setItems:g,removedItems:h}=function(a,b){let c,d,e=a.cookies??null,f=a.cookieEncoding,g={},h={};if(e)if("get"in e){let a=async a=>{let b=a.flatMap(a=>[a,...Array.from({length:5}).map((b,c)=>`${a}.${c}`)]),c=[];for(let a=0;a<b.length;a+=1){let d=await e.get(b[a]);(d||"string"==typeof d)&&c.push({name:b[a],value:d})}return c};if(c=async b=>await a(b),"set"in e&&"remove"in e)d=async a=>{for(let b=0;b<a.length;b+=1){let{name:c,value:d,options:f}=a[b];d?await e.set(c,d,f):await e.remove(c,f)}};else if(b)d=async()=>{console.warn("@supabase/ssr: createServerClient was configured without set and remove cookie methods, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness. Consider switching to the getAll and setAll cookie methods instead of get, set and remove which are deprecated and can be difficult to use correctly.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring a getAll and setAll cookie method (deprecated: alternatively both get, set and remove can be used)")}else if("getAll"in e)if(c=async()=>await e.getAll(),"setAll"in e)d=e.setAll;else if(b)d=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: ${b?"createServerClient":"createBrowserClient"} requires configuring getAll and setAll cookie methods (deprecated: alternatively use get, set and remove).${l()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""}`);else if(!b&&l())c=()=>(()=>{let a=(0,k.qg)(document.cookie);return Object.keys(a).map(b=>({name:b,value:a[b]??""}))})(),d=a=>{a.forEach(({name:a,value:b,options:c})=>{document.cookie=(0,k.lK)(a,b,c)})};else if(b)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 c=()=>[],d=()=>{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 b?{getAll:c,setAll:d,setItems:g,removedItems:h,storage:{isServer:!0,getItem:async a=>{if("string"==typeof g[a])return g[a];if(h[a])return null;let b=await c([a]),d=await q(a,async a=>{let c=b?.find(({name:b})=>b===a)||null;return c?c.value:null});if(!d)return null;let e=d;return"string"==typeof d&&d.startsWith(w)&&(e=v(d.substring(w.length))),e},setItem:async(b,e)=>{b.endsWith("-code-verifier")&&await x({getAll:c,setAll:d,setItems:{[b]:e},removedItems:{}},{cookieOptions:a?.cookieOptions??null,cookieEncoding:f}),g[b]=e,delete h[b]},removeItem:async a=>{delete g[a],h[a]=!0}}}:{getAll:c,setAll:d,setItems:g,removedItems:h,storage:{isServer:!1,getItem:async a=>{let b=await c([a]),d=await q(a,async a=>{let c=b?.find(({name:b})=>b===a)||null;return c?c.value:null});if(!d)return null;let e=d;return d.startsWith(w)&&(e=v(d.substring(w.length))),e},setItem:async(b,e)=>{let g=await c([b]),h=new Set((g?.map(({name:a})=>a)||[]).filter(a=>o(a,b))),i=e;"base64url"===f&&(i=w+u(e));let j=p(b,i);j.forEach(({name:a})=>{h.delete(a)});let k={...m,...a?.cookieOptions,maxAge:0},l={...m,...a?.cookieOptions,maxAge:m.maxAge};delete k.name,delete l.name;let n=[...[...h].map(a=>({name:a,value:"",options:k})),...j.map(({name:a,value:b})=>({name:a,value:b,options:l}))];n.length>0&&await d(n,{})},removeItem:async b=>{let e=await c([b]),f=(e?.map(({name:a})=>a)||[]).filter(a=>o(a,b)),g={...m,...a?.cookieOptions,maxAge:0};delete g.name,f.length>0&&await d(f.map(a=>({name:a,value:"",options:g})),{})}}}}({...c,cookieEncoding:c?.cookieEncoding??"base64url"},!0),i=new cU(a,b,{...c,global:{...c?.global,headers:{...c?.global?.headers,"X-Client-Info":"supabase-ssr/0.10.2 createServerClient"}},auth:{...c?.cookieOptions?.name?{storageKey:c.cookieOptions.name}:null,...c?.auth,flowType:"pkce",autoRefreshToken:!1,detectSessionInUrl:!1,persistSession:!0,skipAutoInitialize:!0,storage:d,...c?.cookies&&"encode"in c.cookies&&"tokens-only"===c.cookies.encode?{userStorage:c?.auth?.userStorage??function(a={}){return{getItem:b=>a[b]||null,setItem:(b,c)=>{a[b]=c},removeItem:b=>{delete a[b]}}}()}:null}});return i.auth.onAuthStateChange(async a=>{(Object.keys(g).length>0||Object.keys(h).length>0)&&("SIGNED_IN"===a||"TOKEN_REFRESHED"===a||"USER_UPDATED"===a||"PASSWORD_RECOVERY"===a||"SIGNED_OUT"===a||"MFA_CHALLENGE_VERIFIED"===a)&&await x({getAll:e,setAll:f,setItems:g,removedItems:h},{cookieOptions:c?.cookieOptions??null,cookieEncoding:c?.cookieEncoding??"base64url"})}),i}if(function(){if("undefined"!=typeof window)return!1;let a=globalThis.process;if(!a)return!1;let b=a.version;if(null==b)return!1;let c=b.match(/^v(\d+)\./);return!!c&&18>=parseInt(c[1],10)}()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217"),"undefined"!=typeof process&&process.env?.npm_package_name){let a=process.env.npm_package_name;["@supabase/auth-helpers-nextjs","@supabase/auth-helpers-react","@supabase/auth-helpers-remix","@supabase/auth-helpers-sveltekit"].includes(a)&&console.warn(`
|
|
╔════════════════════════════════════════════════════════════════════════════╗
|
|
║ ⚠️ IMPORTANT: Package Consolidation Notice ║
|
|
║ ║
|
|
║ The ${a.padEnd(35)} package name is deprecated. ║
|
|
║ ║
|
|
║ You are now using @supabase/ssr - a unified solution for all frameworks. ║
|
|
║ ║
|
|
║ The auth-helpers packages have been consolidated into @supabase/ssr ║
|
|
║ to provide better maintenance and consistent APIs across frameworks. ║
|
|
║ ║
|
|
║ Please update your package.json to use @supabase/ssr directly: ║
|
|
║ npm uninstall ${a.padEnd(42)} ║
|
|
║ npm install @supabase/ssr ║
|
|
║ ║
|
|
║ For more information, visit: ║
|
|
║ https://supabase.com/docs/guides/auth/server-side ║
|
|
╚════════════════════════════════════════════════════════════════════════════╝
|
|
`)}},86802:(a,b,c)=>{c.d(b,{UL:()=>d.U});var d=c(14230);c(34603),c(35916)},94134:(a,b)=>{b.qg=function(a,b){let c=new h,d=a.length;if(d<2)return c;let e=b?.decode||k,f=0;do{let b=function(a,b,c){let d=a.indexOf("=",b);return d<c?d:-1}(a,f,d);if(-1===b)break;let g=function(a,b,c){let d=a.indexOf(";",b);return -1===d?c:d}(a,f,d);if(b>g){f=a.lastIndexOf(";",b-1)+1;continue}let h=j(a,f,b);void 0===c[h]&&(c[h]=e(j(a,b+1,g))),f=g+1}while(f<d);return c},b.lK=i,b.lK=i;let c=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,d=/^[\u0021-\u003A\u003C-\u007E]*$/,e=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,f=/^[\u0020-\u003A\u003D-\u007E]*$/,g=Object.prototype.toString,h=(()=>{let a=function(){};return a.prototype=Object.create(null),a})();function i(a,b,h){let i="object"==typeof a?a:{...h,name:a,value:String(b)},j=("object"==typeof b?b:h)?.encode||encodeURIComponent;if(!c.test(i.name))throw TypeError(`argument name is invalid: ${i.name}`);let k=i.value?j(i.value):"";if(!d.test(k))throw TypeError(`argument val is invalid: ${i.value}`);let l=i.name+"="+k;if(void 0!==i.maxAge){if(!Number.isInteger(i.maxAge))throw TypeError(`option maxAge is invalid: ${i.maxAge}`);l+="; Max-Age="+i.maxAge}if(i.domain){if(!e.test(i.domain))throw TypeError(`option domain is invalid: ${i.domain}`);l+="; Domain="+i.domain}if(i.path){if(!f.test(i.path))throw TypeError(`option path is invalid: ${i.path}`);l+="; Path="+i.path}if(i.expires){var m;if(m=i.expires,"[object Date]"!==g.call(m)||!Number.isFinite(i.expires.valueOf()))throw TypeError(`option expires is invalid: ${i.expires}`);l+="; Expires="+i.expires.toUTCString()}if(i.httpOnly&&(l+="; HttpOnly"),i.secure&&(l+="; Secure"),i.partitioned&&(l+="; Partitioned"),i.priority)switch("string"==typeof i.priority?i.priority.toLowerCase():void 0){case"low":l+="; Priority=Low";break;case"medium":l+="; Priority=Medium";break;case"high":l+="; Priority=High";break;default:throw TypeError(`option priority is invalid: ${i.priority}`)}if(i.sameSite)switch("string"==typeof i.sameSite?i.sameSite.toLowerCase():i.sameSite){case!0:case"strict":l+="; SameSite=Strict";break;case"lax":l+="; SameSite=Lax";break;case"none":l+="; SameSite=None";break;default:throw TypeError(`option sameSite is invalid: ${i.sameSite}`)}return l}function j(a,b,c){let d=b,e=c;do{let b=a.charCodeAt(d);if(32!==b&&9!==b)break}while(++d<e);for(;e>d;){let b=a.charCodeAt(e-1);if(32!==b&&9!==b)break;e--}return a.slice(d,e)}function k(a){if(-1===a.indexOf("%"))return a;try{return decodeURIComponent(a)}catch(b){return a}}}}; |