1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,39377,e=>{"use strict";var t=e.i(46882),r=e.i(55118),s=e.i(2796),i=e.i(41203),n=e.i(27355),a=e.i(95445),o=e.i(48753),l=e.i(11838),h=e.i(19081),u=e.i(57274),c=e.i(97648),d=e.i(39177),p=e.i(96561);function f({value:e,onChange:i,label:n}){let o=(0,s.useTranslations)("IntegrationBuilder"),[g,m]=(0,r.useState)(!1),[y,b]=(0,r.useState)(""),[w,v]=(0,r.useState)([]),[_,k]=(0,r.useState)(!1),[S,E]=(0,r.useState)(!1),[T,A]=(0,r.useState)(0),[R,O]=(0,r.useState)(!0),C=(0,r.useRef)(null),x=(0,r.useRef)(null),j=(0,r.useRef)(null),P=(0,c.createClient)(),I=(0,r.useCallback)(async(e,t,r)=>{r?k(!0):E(!0);let s=P.from("integrations").select("id,slug,name,short_description,logo_url,categories,provider,is_most_loved,created_at,description,price_min_usd,price_max_usd,endpoint_count,requires_setup").order("name").range(50*t,(t+1)*50-1);e.trim()&&(s=s.ilike("name",`%${e.trim()}%`));let{data:i}=await s,n=(0,d.withIntegrationLogos)(i??[]);O(50===n.length),v(e=>r?n:[...e,...n]),A(t),r?k(!1):E(!1)},[P]);(0,r.useEffect)(()=>{g&&(A(0),O(!0),I(y,0,!0),setTimeout(()=>C.current?.focus(),50))},[g]),(0,r.useEffect)(()=>{if(!g)return;let e=setTimeout(()=>{A(0),O(!0),I(y,0,!0)},200);return()=>clearTimeout(e)},[y,g,I]),(0,r.useEffect)(()=>{if(!j.current)return;let e=new IntersectionObserver(e=>{e[0].isIntersecting&&R&&!_&&!S&&I(y,T+1,!1)},{threshold:.1});return e.observe(j.current),()=>e.disconnect()},[R,_,S,T,y,I]),(0,r.useEffect)(()=>{function e(e){x.current&&!x.current.contains(e.target)&&m(!1)}return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let $=e?.categories?.[0]?.split("-")[0]?.toUpperCase()??"";return(0,t.jsxs)("div",{className:"flex-1 min-w-0 relative",ref:x,children:[(0,t.jsx)("p",{className:"mb-2 font-mono text-[10.5px] uppercase tracking-[0.08em] text-[#666661]",children:n}),(0,t.jsxs)("button",{type:"button",onClick:()=>m(e=>!e),className:"flex w-full items-center gap-3.5 rounded-2xl border border-black/10 bg-white px-4 py-[15p
1x] text-left transition-colors hover:border-black/20",children:[e?(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(u.AppIcon,{directLogoUrl:e.logo_url,name:e.name,size:"md"}),(0,t.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,t.jsx)("span",{className:"block truncate text-base font-semibold leading-[21px] tracking-[-0.1px] text-[#0a0a0a]",children:e.name}),(0,t.jsx)("span",{className:"mt-[5px] block truncate font-mono text-[10px] uppercase leading-[14px] tracking-[0.7px] text-[#666661]",children:$})]})]}):(0,t.jsx)("span",{className:"flex-1 text-base text-[#666661]",children:o("selectApp")}),(0,t.jsx)(a.ChevronDown,{className:(0,p.cn)("h-4 w-4 shrink-0 text-[#666661] transition-transform",g&&"rotate-180")})]}),g&&(0,t.jsxs)("div",{className:"absolute left-0 right-0 top-[calc(100%+8px)] z-[500] rounded-2xl border border-black/10 bg-white shadow-xl shadow-black/10",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 border-b border-black/[0.06] px-3 py-2.5",children:[(0,t.jsx)(h.Search,{className:"h-4 w-4 shrink-0 text-[#666661]"}),(0,t.jsx)("input",{ref:C,type:"text",value:y,onChange:e=>b(e.target.value),placeholder:o("searchPlaceholder"),className:"flex-1 bg-transparent text-sm text-[#0a0a0a] outline-none placeholder:text-[#666661]"})]}),(0,t.jsxs)("div",{className:"max-h-64 overflow-y-auto p-1.5",children:[_&&(0,t.jsx)("p",{className:"px-3 py-4 text-center text-xs text-[#666661]",children:o("loading")}),!_&&0===w.length&&(0,t.jsx)("p",{className:"px-3 py-4 text-center text-xs text-[#666661]",children:o("noResults")}),!_&&w.map(r=>(0,t.jsxs)("button",{type:"button",onMouseDown:e=>{e.preventDefault(),i(r),b(""),m(!1)},className:"flex w-full items-center gap-3 rounded-xl px-2.5 py-2 text-left transition-colors hover:bg-[#f5f5f3]",children:[(0,t.jsx)(u.AppIcon,{directLogoUrl:r.logo_url,name:r.name,size:"sm"}),(0,t.jsx)("span",{className:"flex-1 truncate text-sm text-[#0a0a0a]",children:r.name}),r.id===e?.id&&(0,t.jsx)(l.Check,{className:"h-4 w-4 shrink-0 text-[#1a69fa]"})]},r.id)),(0,t.jsx)("div",{ref:j,className:"py-1",children:S&&(0,t.jsx)("p",{className:"px-3 py-2 text-center text-xs text-[#666661]",children:o("loadingMore")})})]})]})]})}e.s(["IntegrationBuilder",0,function({defaultTriggerSlug:e="github",defaultActionSlug:a="telegram"}={}){let l=(0,s.useTranslations)("IntegrationBuilder"),[h,p]=(0,r.useState)(null),[g,m]=(0,r.useState)(null),y=(0,c.createClient)();return(0,r.useEffect)(()=>{!async function(){let{data:t}=await y.from("integrations").select("*").in("slug",[e,a]);if(!t)return;let r=t.map(d.withIntegrationLogo);p(r.find(t=>t.slug===e)??r[0]),m(r.find(e=>e.slug===a)??r[1])}()},[e,a]),(0,t.jsxs)("div",{className:"rounded-[14px] border border-black/[0.08] bg-white p-5 shadow-[0_20px_60px_rgba(10,10,10,0.08)] md:p-8",children:[(0,t.jsxs)("div",{className:"flex flex-col items-stretch gap-4 md:flex-row md:items-end",children:[(0,t.jsx)(f,{value:h,onChange:p,label:l("triggerLabel")}),(0,t.jsx)("button",{type:"button",onClick:function(){p(g),m(h)},"aria-label":l("swapAria"),className:"mx-auto mb-2.5 flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-[#0a0a0a] text-white transition-transform hover:scale-105",children:(0,t.jsx)(n.ArrowLeftRight,{className:"h-5 w-5"})}),(0,t.jsx)(f,{value:g,onChange:m,label:l("actionLabel")})]}),h&&g&&(0,t.jsxs)("div",{className:"mt-6 flex flex-col items-start justify-between gap-4 border-t border-black/[0.08] pt-6 sm:flex-row sm:items-center",children:[(0,t.jsxs)("div",{className:"flex items-center gap-3.5",children:[(0,t.jsxs)("div",{className:"flex items-center -space-x-2",children:[(0,t.jsx)(u.AppIcon,{directLogoUrl:h.logo_url,name:h.name,size:"sm",className:"ring-2 ring-white"}),(0,t.jsx)(u.AppIcon,{directLogoUrl:g.logo_url,name:g.name,size:"sm",className:"ring-2 ring-white"})]}),(0,t.jsxs)("span",{className:"text-[15px] text-[#0a0a0a]",children:[h.name," + ",g.name]})]}),(0,t.jsxs)(i.Link,{href:`/integrations/${h.slug}/${g.slug}`,className:"inline-flex items-center gap-2 rounded-full bg-[#1a69fa] px-5 py-3 text-[15px] font-medium text-white transition-opacity hover:opacity-90",children:[l("seeIntegrationPage"),
1(0,t.jsx)(o.ArrowRight,{className:"h-3.5 w-3.5"})]})]})]})}])},55418,(e,t,r)=>{t.exports={$comment:"Replacement logos for integrations whose Website Supabase integrations.logo_url is broken (404, HTML body, empty, blank). Applied at read time by lib/integration-logos.ts, so the database is never written. Each entry was verified with scripts/audit-integration-logos.mjs and checked visually for the right brand. Remove an entry once the database row is fixed.",verified_at:"2026-09-24",overrides:{abstract:{logo_url:"https://logos.composio.dev/api/abstract",source:"composio",replaces:"https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/icons/abstract_mega_20250722.png"},cloudlayer:{logo_url:"https://cloudlayer.io/favicon.svg",source:"product-site",replaces:"https://cloudlayer.io/logo.png"},codereadr:{logo_url:"https://logos.composio.dev/api/codereadr",source:"composio",replaces:"https://www.codereadr.com/wp-content/uploads/2020/06/codereadr-logo.png"},college_football_data:{logo_url:"https://logos.composio.dev/api/college_football_data",source:"composio",replaces:"https://collegefootballdata.com/logo.png"},control_d:{logo_url:"https://logos.composio.dev/api/control_d",source:"composio",replaces:"https://controld.com/logo.png"},formbricks:{logo_url:"https://thesvg.org/icons/formbricks/default.svg",source:"thesvg.org",replaces:"https://formbricks.com/logo.png"},gatherup:{logo_url:"https://logos.composio.dev/api/gatherup",source:"composio",replaces:"https://gatherup.com/wp-content/uploads/2020/06/gatherup-logo.png"},geoapify:{logo_url:"https://logos.composio.dev/api/geoapify",source:"composio",replaces:"https://www.geoapify.com/wp-content/uploads/2020/06/geoapify_logo.svg"},getform:{logo_url:"https://logos.composio.dev/api/getform",source:"composio",replaces:"https://getform.io/favicon.ico"},gladia:{logo_url:"https://logos.composio.dev/api/gladia",source:"composio",replaces:"https://www.gladia.io/favicon.ico"},globalping:{logo_url:"https://logos.composio.dev/api/globalping",source:"composio",replaces:"https://globalping.io/logo.png"},godial:{logo_url:"https://logos.composio.dev/api/godial",source:"composio",replaces:"https://godial.cc/wp-content/uploads/2020/06/GoDial-Logo-1.png"},goodbits:{logo_url:"https://logos.composio.dev/api/goodbits",source:"composio",replaces:"https://goodbits.io/logo.png"},goody:{logo_url:"https://logos.composio.dev/api/goody",source:"composio",replaces:"https://www.ongoody.com/favicon.ico"},gosquared:{logo_url:"https://logos.composio.dev/api/gosquared",source:"composio",replaces:"https://www.gosquared.com/images/logo.png"},graphhopper:{logo_url:"https://logos.composio.dev/api/graphhopper",source:"composio",replaces:"https://www.graphhopper.com/images/graphhopper_logo.svg"},griptape:{logo_url:"https://logos.composio.dev/api/griptape",source:"composio",replaces:"https://www.griptape.ai/logo.png"},grist:{logo_url:"https://logos.composio.dev/api/grist",source:"composio",replaces:"https://www.getgrist.com/static/images/logo.svg"},here:{logo_url:"https://thesvg.org/icons/here/default.svg",source:"thesvg.org",replaces:"https://www.here.com/etc.clientlibs/here/clientlibs/website/clientlib-site/resources/images/here-logo.svg"},highergov:{logo_url:"https://logos.composio.dev/api/highergov",source:"composio",replaces:"https://www.highergov.com/favicon.ico"},honeyhive:{logo_url:"https://logos.composio.dev/api/honeyhive",source:"composio",replaces:"https://www.honeyhive.ai/logo.png"},html_to_image:{logo_url:"https://logos.composio.dev/api/html_to_image",source:"composio",replaces:"https://html2img.com/logo.png"},hunter:{logo_url:"https://logos.composio.dev/api/hunter",source:"composio",replaces:"https://logo.clearbit.com/hunter.io"},hyperise:{logo_url:"https://logos.composio.dev/api/hyperise",source:"composio",replaces:"https://hyperise.com/images/logo.png"},icypeas:{logo_url:"https://logos.composio.dev/api/icypeas",source:"composio",replaces:"https://www.icypeas.com/logo.png"},ignisign:{logo_url:"https://logos.composio.dev/api/ignisign",source:"composio",replaces:"https://ignisign.io/logo.png"},imagekit_io:{logo_url:"https://logos.composio.dev/api/imagekit_io",source:"composio",replaces:"https://imagekit.io/static/imagekit-logo.svg"},imgbb:{logo_url:"https://logos.composio.dev/api/imgbb",source:"composio",replaces:"https://imgbb.com/favicon.ico"},imgix:{logo_url:"https://logos.composio.dev/api/imgix",source:"composio",replaces:"https://assets.imgix.net/press/imgix-logo.png"},influxdb_cloud:{logo_url:"https://thesvg.org/icons/influxdb/default.svg",source:"thesvg.org",replaces:"https://www.influxdata.com/w
1p-content/uploads/influxdata-logo.png"},ip2location:{logo_url:"https://logos.composio.dev/api/ip2location",source:"composio",replaces:"https://www.ip2location.io/images/logo.png"},ip2whois:{logo_url:"https://logos.composio.dev/api/ip2whois",source:"composio",replaces:"https://www.ip2whois.com/images/logo.png"},ipdata_co:{logo_url:"https://logos.composio.dev/api/ipdata_co",source:"composio",replaces:"https://ipdata.co/static/images/ipdata-logo.png"},ipinfo_io:{logo_url:"https://logos.composio.dev/api/ipinfo_io",source:"composio",replaces:"https://ipinfo.io/static/images/ipinfo-logo.png"},page_x:{logo_url:"https://logos.composio.dev/api/page_x",source:"composio",replaces:"https://pipedream.com/apps/page-x/logo.png"},"postforme-linkedin":{logo_url:"https://thesvg.org/icons/linkedin/default.svg",source:"thesvg.org",replaces:"https://cdn.simpleicons.org/linkedin"},seat_geek:{logo_url:"https://thesvg.org/icons/seatgeek/default.svg",source:"thesvg.org",replaces:"https://seatgeek.com/favicon.ico"},tapfiliate:{logo_url:"https://logos.composio.dev/api/tapfiliate",source:"composio",replaces:"https://logo.clearbit.com/tapfiliate.com"},worksnaps:{logo_url:"https://logos.composio.dev/api/worksnaps",source:"composio",replaces:"https://www.worksnaps.com/images/logo.png"}}}},97648,39177,e=>{"use strict";let t,r,s,i;var n,a,o,l,h,u,c,d,p,f,g,m,y,b,w=e.i(19940);let v=Symbol.for("@supabase/supabase-js.traceContextExtractor");class _ extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class k extends _{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class S extends _{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class E extends _{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}(n=c||(c={})).Any="any",n.ApNortheast1="ap-northeast-1",n.ApNortheast2="ap-northeast-2",n.ApSouth1="ap-south-1",n.ApSoutheast1="ap-southeast-1",n.ApSoutheast2="ap-southeast-2",n.CaCentral1="ca-central-1",n.EuCentral1="eu-central-1",n.EuWest1="eu-west-1",n.EuWest2="eu-west-2",n.EuWest3="eu-west-3",n.SaEast1="sa-east-1",n.UsEast1="us-east-1",n.UsWest1="us-west-1",n.UsWest2="us-west-2";function T(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&0>t.indexOf(s)&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,s=Object.getOwnPropertySymbols(e);i<s.length;i++)0>t.indexOf(s[i])&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(r[s[i]]=e[s[i]]);return r}"function"==typeof SuppressedError&&SuppressedError;class A{constructor(e,{headers:t={},customFetch:r,region:s=c.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){var t,r,s,i;return t=this,r=arguments,s=void 0,i=function*(e,t={}){var r,s;let i,n,a;try{let s,{headers:o,method:l,body:h,signal:u,timeout:c}=t,d={},{region:p}=t;p||(p=this.region);let f=new URL(`${this.url}/${e}`);p&&"any"!==p&&(d["x-region"]=p,f.searchParams.set("forceFunctionRegion",p));let g=!!o&&Object.keys(o).some(e=>"content-type"===e.toLowerCase());h&&!g?"u">typeof Blob&&h instanceof Blob||h instanceof ArrayBuffer?(d["Content-Type"]="application/octet-stream",s=h):"string"==typeof h?(d["Content-Type"]="text/plain",s=h):"u">typeof FormData&&h instanceof FormData?s=h:(d["Content-Type"]="application/json",s=JSON.stringify(h)):s=!h||"string"==typeof h||"u">typeof Blob&&h instanceof Blob||h instanceof ArrayBuffer||"u">typeof FormData&&h instanceof FormData?h:JSON.stringify(h);let m=u;c&&(n=new AbortController,i=setTimeout(()=>n.abort(),c),u?(m=n.signal,a=()=>n.abort(),u.addEventListener("abort",a)):m=n.signal);let y=yield this.fetch(f.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),o),body:s,signal:m}).catch(e=>{throw new k(e)}),b=y.headers.get("x-relay-error");if(b&&"true"===b)throw new S(y);if(!y.ok)throw new E(y);let w=(null!=(r=y.headers.get("Content-Type"))?r:"text/plain").split(";")[0].trim().toLowerCase();return{data:"application/json"===w?yield y.json():"application/octet-stream"
1===w||"application/pdf"===w?yield y.blob():"text/event-stream"===w?y:"multipart/form-data"===w?yield y.formData():yield y.text(),error:null,response:y}}catch(e){return{data:null,error:e,response:e instanceof E||e instanceof S?e.context:void 0}}finally{i&&clearTimeout(i),a&&(null==(s=t.signal)||s.removeEventListener("abort",a))}},new(s||(s=Promise))(function(e,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(t){var r;t.done?e(t.value):((r=t.value)instanceof s?r:new s(function(e){e(r)})).then(a,o)}l((i=i.apply(t,r||[])).next())})}}var R=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};let O=e=>Math.min(1e3*2**e,3e4),C=[520,503],x=["GET","HEAD","OPTIONS"];function j(e){return(j="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function P(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function I(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?P(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=j(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=j(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==j(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):P(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function $(e,t){return new Promise(r=>{if(null==t?void 0:t.aborted)return void r();let s=setTimeout(()=>{null==t||t.removeEventListener("abort",i),r()},e);function i(){clearTimeout(s),r()}null==t||t.addEventListener("abort",i)})}async function N(e,t,r,s){let i=0;for(;;){var n,a,o,l,h;let u,c=I({},r.headers);i>0&&(c["X-Retry-Count"]=String(i));try{u=await e(t,{method:r.method,headers:c,body:r.body,signal:r.signal})}catch(e){if((null==e?void 0:e.name)==="AbortError"||(null==e?void 0:e.code)==="ABORT_ERR"||!x.includes(r.method))throw e;if(s&&i<3){let e=O(i);i++,await $(e,r.signal);continue}throw e}if(n=r.method,a=u.status,o=i,s&&!(o>=3)&&x.includes(n)&&C.includes(a)&&1){let e=null!=(l=null==(h=u.headers)?void 0:h.get("Retry-After"))?l:null,t=null!==e?1e3*Math.max(0,parseInt(e,10)||0):O(i);await u.text(),i++,await $(t,r.signal);continue}return u}}var U=class{constructor(e){var t,r,s,i,n;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!=(t=e.shouldThrowOnError)&&t,this.signal=e.signal,this.isMaybeSingle=null!=(r=e.isMaybeSingle)&&r,this.shouldStripNulls=null!=(s=e.shouldStripNulls)&&s,this.urlLengthLimit=null!=(i=e.urlLengthLimit)?i:8e3,this.retryEnabled=null==(n=e.retry)||n,e.fetch?this.fetch=e.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(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var r=this;if(void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){let e=this.headers.get("Accept");"application/vnd.pgrst.object+json"===e?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):e&&"application/json"!==e||this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let s=this.fetch,i=(async()=>{let e={};
1r.headers.forEach((t,r)=>{e[r]=t});let t=await N(s,r.url.toString(),{method:r.method,headers:e,body:JSON.stringify(r.body,(e,t)=>"bigint"==typeof t?t.toString():t),signal:r.signal},r.retryEnabled);return await r.processResponse(t)})();return this.shouldThrowOnError||(i=i.catch(e=>{var t,r,s,i,n,a;let o="",l="",h="",u=null==e?void 0:e.cause;if(u){let t=null!=(r=null==u?void 0:u.message)?r:"",a=null!=(s=null==u?void 0:u.code)?s:"";o=`${null!=(i=null==e?void 0:e.name)?i:"FetchError"}: ${null==e?void 0:e.message} 2 3Caused by: ${null!=(n=null==u?void 0:u.name)?n:"Error"}: ${t}`,a&&(o+=` (${a})`),(null==u?void 0:u.stack)&&(o+=` 4${u.stack}`)}else o=null!=(a=null==e?void 0:e.stack)?a:"";let c=this.url.toString().length;return(null==e?void 0:e.name)==="AbortError"||(null==e?void 0:e.code)==="ABORT_ERR"?(h="",l="Request was aborted (timeout or manual cancellation)",c>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${c} 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==u?void 0:u.name)==="HeadersOverflowError"||(null==u?void 0:u.code)==="UND_ERR_HEADERS_OVERFLOW")&&(h="",l="HTTP headers exceeded server limits (typically 16KB)",c>this.urlLengthLimit&&(l+=`. Your request URL is ${c} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${null!=(t=null==e?void 0:e.name)?t:"FetchError"}: ${null==e?void 0:e.message}`,details:o,hint:l,code:h},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}async processResponse(e){var t,r,s,i;let n=null,a=null,o=null,l=e.status,h=e.statusText;if(e.ok){if("HEAD"!==this.method){let t=await e.text();if(""===t);else if("text/csv"===this.headers.get("Accept"))a=t;else if(this.headers.get("Accept")&&(null==(s=this.headers.get("Accept"))?void 0:s.includes("application/vnd.pgrst.plan+text")))a=t;else try{a=JSON.parse(t)}catch(e){if(n={message:t},a=null,this.shouldThrowOnError)throw new R({message:t,details:"",hint:"",code:""})}}let u=null==(t=this.headers.get("Prefer"))?void 0:t.match(/count=(exact|planned|estimated)/),c=null==(r=e.headers.get("content-range"))?void 0:r.split("/");if(u&&c&&c.length>1&&(o=parseInt(c[1])),this.isMaybeSingle&&Array.isArray(a))if(a.length>1){if(n={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,o=null,l=406,h="Not Acceptable",this.shouldThrowOnError)throw new R(I(I({},n),{},{hint:null!=(i=n.hint)?i:""}))}else a=1===a.length?a[0]:null}else{let t=await e.text();try{n=JSON.parse(t),Array.isArray(n)&&404===e.status&&(a=[],n=null,l=200,h="OK")}catch(r){404===e.status&&""===t?(l=204,h="No Content"):n={message:t}}if(n&&this.shouldThrowOnError)throw new R(n)}return{success:null===n,error:n,data:a,count:o,status:l,statusText:h}}returns(){return this}overrideTypes(){return this}},L=class extends U{throwOnError(){return super.throwOnError()}select(e){let t=!1,r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){let i=void 0===s?"offset":`${s}.offset`,n=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(n,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}
4explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:n="text"}={}){var a;let o=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!=(a=this.headers.get("Accept"))?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${l}"; options=${o};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};let B=RegExp("[,()]");var D=class extends L{throwOnError(){return super.throwOnError()}eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&B.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&B.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let i="";"plain"===s?i="pl":"phrase"===s?i="ph":"websearch"===s&&(i="w");let n=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${n}.${t}`),this}match(e){return Object.entries(e).filter(([e,t])=>void 0!==t).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},q=class{constructor(e,{headers:t={},schema:r,fetch:s,urlLengthLimit:i=8e3,retry:n}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s,this.urlLengthLimit=i,this.retry=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:r=!1,count:s}=null!=t?t:{},i=!1,n=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e)).join(""),{url:a,headers:o}=this.cloneRequestState();return a.searchParams.set("select",n),s&&o.append("Prefer",`count=${s}`),new D({method:r?"HEAD":"GET",url:a,headers:o,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:r=!0}={}){var s;let{url:i,headers:n}=this.cloneRequestState();if(t&&n.append("Prefer",`count=${t}`),r||n.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>
4e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);i.searchParams.set("columns",e.join(","))}}return new D({method:"POST",url:i,headers:n,schema:this.schema,body:e,fetch:null!=(s=this.fetch)?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){var n;let{url:a,headers:o}=this.cloneRequestState();if(o.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&a.searchParams.set("on_conflict",t),s&&o.append("Prefer",`count=${s}`),i||o.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set("columns",e.join(","))}}return new D({method:"POST",url:a,headers:o,schema:this.schema,body:e,fetch:null!=(n=this.fetch)?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){var r;let{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new D({method:"PATCH",url:s,headers:i,schema:this.schema,body:e,fetch:null!=(r=this.fetch)?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){var t;let{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new D({method:"DELETE",url:r,headers:s,schema:this.schema,fetch:null!=(t=this.fetch)?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function M(e,t,r){var s;return{success:!1,error:new R({message:`${null!=(s=null==e?void 0:e.name)?s:"FetchError"}: ${null==e?void 0:e.message}`,details:"",hint:"",code:""}),data:null,count:null,status:t,statusText:r}}var F=class e{constructor(e,{headers:t={},schema:r,fetch:s,timeout:i,urlLengthLimit:n=8e3,retry:a}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.urlLengthLimit=n;const o=null!=s?s:globalThis.fetch;void 0!==i&&i>0?this.fetch=(e,t)=>{let r=new AbortController,s=setTimeout(()=>r.abort(),i),n=null==t?void 0:t.signal;if(n){if(n.aborted)return clearTimeout(s),o(e,t);let i=()=>{clearTimeout(s),r.abort()};return n.addEventListener("abort",i,{once:!0}),o(e,I(I({},t),{},{signal:r.signal})).finally(()=>{clearTimeout(s),n.removeEventListener("abort",i)})}return o(e,I(I({},t),{},{signal:r.signal})).finally(()=>clearTimeout(s))}:this.fetch=o,this.retry=a}from(e){if(!e||"string"!=typeof e||""===e.trim())throw Error("Invalid relation name: relation must be a non-empty string.");return new q(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}async getOpenApiSpec(){var e,t;let r,s,i=new Headers(this.headers);i.set("Accept","application/openapi+json"),this.schemaName&&i.set("Accept-Profile",this.schemaName);let n={};i.forEach((e,t)=>{n[t]=e});let a=null!=(e=this.fetch)?e:globalThis.fetch;try{r=await N(a,`${this.url}/`,{method:"GET",headers:n},null==(t=this.retry)||t)}catch(e){return M(e,0,"")}try{s=await r.text()}catch(e){return M(e,r.status,r.statusText)}if(r.ok)try{return{success:!0,error:null,data:JSON.parse(s),count:null,status:r.status,statusText:r.statusText}}catch(e){}return{success:!1,error:function(e,t){try{let t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t)){var r,s,i,n;return new R({message:String(null!=(r=t.message)?r:e),details:null!=(s=t.details)?s:"",hint:null!=(i=t.hint)?i:"",code:null!=(n=t.code)?n:""})}}catch(e){}return new R({message:e||t,details:"",hint:"",code:""})}(s,r.statusText),data:null,count:null,status:r.status,statusText:r.statusText}}rpc(e,t={},{head:r=!1,get:s=!1,count:i}={}){var n;let a,o,l=new URL(`${this.url}/rpc/${e}`),h=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(h)),u=r&&Object.values(t).some(h);u?(a="POST",o=t):r||s?(a=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{l.searchParams.append(e,t)})):(a="POST",o=t);let c=new Headers(this.headers);return u?c.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&c.set("Prefer",`count=${i}`),new D({method:a,url:l,headers:c,schema:this.schemaName,body:o,fetch:null!=(n=this.fetch)?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};let H=class{static detectEnvironment(){var t;if("u">typeof WebSocket)return{type:"native",wsConstructor:WebSocket};let r=globalThis;if("u">typeof globalThis&&void 0!==r.WebSocket)return{type:"native",wsConstructor:r.WebSocket};let s=e.g;if(s&&void 0!==s.WebSocket)return{type:"native",wsConstructor:s.WebSocket};if("u">typeof globalThis&&void 0!==r.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("u">typeof globalThis&&r.EdgeRuntime||"u">typeof navigator&&(null==(t=navigator.userAgent)?void 0:t.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let i=globalThis.process;if(i){let e=i.versions;if(e&&e.node)return{type:"unsupported",error:"Node.js detected but native WebSocket not found.",workaround:"Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=` 5 6Suggested solution: ${e.workaround}`),Error(t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return"native"===e.type}catch(e){return!1}}},W="2.0.0",K="errored",z="joined",J={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};class G{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){return e.event!==this.BROADCAST_EVENT||e.payload instanceof ArrayBuffer||"string"!=typeof e.payload.event?t(JSON.stringify([e.join_ref,e.ref,e.topic,e.event,e.payload])):t(this._binaryEncodeUserBroadcastPush(e))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null==(t=e.payload)?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;let s=null!=(r=null==(t=e.payload)?void 0:t.payload)?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,r;let s=null!=(r=null==(t=e.payload)?void 0:t.payload)?r:{},i=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,t,r){let s=new TextEncoder,i=s.encode(e.topic),n=s.encode(null!=(g=e.ref)?g:""),a=s.encode(null!=(m=e.join_ref)?m:""),o=s.encode(e.payload.event),l=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=s.encode(0===Object.keys(l).length?"":JSON.stringify(l));if(a.length>255)throw Error(`joinRef length ${a.length} exceeds maximum of 255`);if(n.length>255)throw Error(`ref length ${n.length} exceeds maximum of 255`);if(i.length>255)throw Error(`topic length ${i.length} exceeds maximum of 255`);if(o.length>255)throw Error(`userEvent length ${o.length} exceeds maximum of 255`);if(h.length>255)throw Error(`metadata length ${h.length} exceeds maximum of 255`);let u=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+n.length+i.length+o.length+h.length,c=new ArrayBuffer(this.HEADER_LENGTH+u),d=new DataView(c),p=new Uint8Array(c),f=0;d.setUint8(f++,this.KINDS.userBroadcastPush),d.setUint8(f++,a.length),d.setUint8(f++,n.length),d.setUint8(f++,i.length),d.setUint8(f++,o.length),d.setUint8(f++,h.length),d.setUint8(f++,t),p.set(a,f),f+=a.length,p.set(n,f),f+=n.length,p.set(i,f),f+=i.length,p.set(o,f),f+=o.length,p.set(h,f),f+=h.length;var g,m,y=new Uint8Array(c.byteLength+r.byteLength);return y.set(new Uint8Array(c),0),y.set(new Uint8Array(r),c.byteLength),y.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if("string"==typeof e){let[r,s,i,n,a]=JSON.parse(e);return t({join_ref:r,ref:s,topic:i,event:n,payload:a})}return t({})}_binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s
6)}_decodeUserBroadcast(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+4,l=r.decode(e.slice(o,o+s));o+=s;let h=r.decode(e.slice(o,o+i));o+=i;let u=r.decode(e.slice(o,o+n));o+=n;let c=e.slice(o,e.byteLength),d=a===this.JSON_ENCODING?JSON.parse(r.decode(c)):c,p={type:this.BROADCAST_EVENT,event:h,payload:d};return n>0&&(p.meta=JSON.parse(u)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||(null==(t=null==e?void 0:e.constructor)?void 0:t.name)==="ArrayBuffer"}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}(a=d||(d={})).abstime="abstime",a.bool="bool",a.date="date",a.daterange="daterange",a.float4="float4",a.float8="float8",a.int2="int2",a.int4="int4",a.int4range="int4range",a.int8="int8",a.int8range="int8range",a.json="json",a.jsonb="jsonb",a.money="money",a.numeric="numeric",a.oid="oid",a.reltime="reltime",a.text="text",a.time="time",a.timestamp="timestamp",a.timestamptz="timestamptz",a.timetz="timetz",a.tsrange="tsrange",a.tstzrange="tstzrange";let V=(e,t,r={})=>{var s;let i=null!=(s=r.skipTypes)?s:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=Y(s,e,t,i),r),{}):{}},Y=(e,t,r,s)=>{let i=t.find(t=>t.name===e),n=null==i?void 0:i.type,a=r[e];return n&&!s.includes(n)?X(n,a):Q(a)},X=(e,t)=>{if("_"===e.charAt(0))return er(t,e.slice(1,e.length));switch(e){case d.bool:return Z(t);case d.float4:case d.float8:case d.int2:case d.int4:case d.int8:case d.numeric:case d.oid:return ee(t);case d.json:case d.jsonb:return et(t);case d.timestamp:return es(t);case d.abstime:case d.date:case d.daterange:case d.int4range:case d.int8range:case d.money:case d.reltime:case d.text:case d.time:case d.timestamptz:case d.timetz:case d.tsrange:case d.tstzrange:default:return Q(t)}},Q=e=>e,Z=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},ee=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},et=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){}return e},er=(e,t)=>{if("string"!=typeof e)return e;let r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s,i=e.slice(1,r);try{s=JSON.parse("["+i+"]")}catch(e){s=i?i.split(","):[]}return s.map(e=>X(t,e))}return e},es=e=>"string"==typeof e?e.replace(" ","T"):e,ei=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};var en=e=>"function"==typeof e?e:function(){return e},ea="u">typeof window?window:null,eo=("u">typeof self?self:null)||ea||globalThis,el="closed",eh="errored",eu="joined",ec="joining",ed="leaving",ep="phx_close",ef="phx_error",eg="phx_reply",em="phx_leave",ey="websocket",eb="base64url.bearer.phx.",ew=class{constructor(e,t,r,s){this.channel=e,this.event=t,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:r}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},ev=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},e_=class{constructor(e,t,r){this.state=el,this.topic=e,this.params=en(t||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new ew(this,"phx_join",this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new ev(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=eu,this.rejoinTimer.reset(),this.pushBuffer.forEach(e
6=>e.send()),this.pushBuffer=[]}),this.joinPush.receive("error",e=>{this.state=eh,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,e),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=el,this.socket.remove(this)}),this.onError(e=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,e),this.isJoining()&&this.joinPush.reset(),this.state=eh,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new ew(this,em,en({}),this.timeout).send(),this.state=eh,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(eg,(e,t)=>{this.trigger(this.replyEventName(t),e)})}join(e=this.timeout){if(!this.joinedOnce)return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush;throw Error("tried to join multiple times. 'join' can only be called a single time per channel instance")}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=el,this.bindings=[]}onClose(e){this.on(ep,e)}onError(e){return this.on(ef,t=>e(t))}on(e,t){let r=this.bindingRef++;return this.bindings.push({event:e,ref:r,callback:t}),r}off(e,t){this.bindings=this.bindings.filter(r=>r.event!==e||void 0!==t&&t!==r.ref)}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,r=this.timeout){if(t=t||{},!this.joinedOnce)throw Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new ew(this,e,function(){return t},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=ed;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(ep,"leave")},r=new ew(this,em,en({}),e);return r.receive("ok",()=>t()).receive("timeout",()=>t()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(e,t,r){return t}filterBindings(e,t,r){return!0}isMember(e,t,r,s){return this.topic===e&&(!s||s===this.joinRef()||(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:r,joinRef:s}),!1))}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=ec,this.joinPush.resend(e))}trigger(e,t,r,s){let i=this.onMessage(e,t,r,s);if(t&&!i)throw Error("channel onMessage callbacks must return the payload, modified or unmodified");let n=this.bindings.filter(s=>s.event===e&&this.filterBindings(s,t,r));for(let e=0;e<n.length;e++)n[e].callback(i,r,s||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===el}isErrored(){return this.state===eh}isJoined(){return this.state===eu}isJoining(){return this.state===ec}isLeaving(){return this.state===ed}},ek=class{static request(e,t,r,s,i,n,a){if(eo.XDomainRequest){let r=new eo.XDomainRequest;return this.xdomainRequest(r,e,t,s,i,n,a)}if(eo.XMLHttpRequest){let o=new eo.XMLHttpRequest;return this.xhrRequest(o,e,t,r,s,i,n,a)}if(eo.fetch&&eo.AbortController)return this.fetchRequest(e,t,r,s,i,n,a);throw Error("No suitable XMLHttpRequest implementation found")}static fetchRequest(e,t,r,s,i,n,a){let o={method:e,headers:r,body:s},l=null;return i&&(l=new AbortController,setTimeout(()=>l.abort(),i),o.signal=l.signal),eo.fetch(t,o).then(e=>e.text()).then(e=>this.parseJSON(e)).then(e=>a&&a(e)).catch(e=>{"AbortError"===e.name&&n?n():a&&a(null)}),l}static xdomainRequest(e,t,r,s,i,n,a){return e.timeout=i,e.open(t,r),e.onload=()=>{let t=this.parseJSON(e.responseText);a&&a(t)},n&&(e.ontimeout=n),e.onprogress=()=>{},e.send(s),e}static xhrRequest(e,t,r,s,i,n,a,o){for(let[i,a]of(e.open(t,r,!0),e.timeout=n,Object.entries(s)))e.setRequestHeader(i,a);return e.onerror=()=>o&&o(null),e.onreadystatechange=()=>{4===e.readyState&&o&&o(this.parseJSON(e.responseText))},a&&(e.ontimeout=a),e.send(i),e}static parseJSON(e){if(!e||""===e)return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let r=[];for(var s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let i=t?`${t}[${s}]`:s,n=e[s];"object"==typeof n?r.push(this.serialize(n,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(n))}return r.join("&")}static appendParams(e,t){if(0===Object.keys(t).length)return e;let r=e.match(/\?/)?"&":"?";return`${e}${r}${this.serialize(t)}`}}
6,eS=class{constructor(e,t){t&&2===t.length&&t[1].startsWith(eb)&&(this.authToken=atob(t[1].slice(eb.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=0,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(RegExp("(.*)/"+ey),"$1/longpoll")}endpointURL(){return ek.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=0}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return 1===this.readyState||0===this.readyState}poll(){let e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:r,messages:s}=e;if(410===t&&null!==this.token){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=r}else t=0;switch(t){case 200:s.forEach(e=>{setTimeout(()=>this.onmessage({data:e}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=1,this.onopen({}),this.poll();break;
6case 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 ${t}`)}})}send(e){"string"!=typeof e&&(e=(e=>{let t="",r=new Uint8Array(e),s=r.byteLength;for(let e=0;e<s;e++)t+=String.fromCharCode(r[e]);return btoa(t)})(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e,t=0){this.awaitingBatchAck=!0;let r=t+100,s=e.slice(t,r);this.ajax("POST",{"Content-Type":"application/x-ndjson"},s.join("\n"),()=>this.onerror("timeout"),t=>{t&&200===t.status?r<e.length?this.batchSend(e,r):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1:(this.awaitingBatchAck=!1,this.onerror(t&&t.status),this.closeAndRetry(1011,"internal server error",!1))})}close(e,t,r){for(let e of this.reqs)e.abort();this.readyState=3;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,"u">typeof CloseEvent?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(e,t,r,s,i){let n,a=()=>{this.reqs.delete(n),s()};n=ek.request(e,this.endpointURL(),t,r,this.timeout,a,e=>{this.reqs.delete(n),this.isActive()&&i(e)}),this.reqs.add(n)}},eE=class e{constructor(t,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state=Object.create(null),this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,t=>{let{onJoin:r,onLeave:s,onSync:i}=this.caller;this.joinRef=this.channel.joinRef(),this.state=e.syncState(this.state,t,r,s),this.pendingDiffs.forEach(t=>{this.state=e.syncDiff(this.state,t,r,s)}),this.pendingDiffs=[],i()}),this.channel.on(s.diff,t=>{let{onJoin:r,onLeave:s,onSync:i}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,r,s),i())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(t){return e.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,t,r,s){let i=this.toNullProtoObj(this.clone(e));t=this.toNullProtoObj(t);let n=Object.create(null),a=Object.create(null);return this.map(i,(e,r)=>{t[e]||(a[e]=r)}),this.map(t,(e,t)=>{let r=i[e];if(r){let s=t.metas.map(e=>e.phx_ref),i=r.metas.map(e=>e.phx_ref),o=t.metas.filter(e=>0>i.indexOf(e.phx_ref)),l=r.metas.filter(e=>0>s.indexOf(e.phx_ref));o.length>0&&(n[e]=t,n[e].metas=o),l.length>0&&(a[e]=this.clone(r),a[e].metas=l)}else n[e]=t}),this.syncDiff(i,{joins:n,leaves:a},r,s)}static syncDiff(e,t,r,s){e=this.toNullProtoObj(e);let{joins:i,leaves:n}=this.clone(t);return r||(r=function(){}),s||(s=function(){}),this.map(i,(t,s)=>{let i=e[t];if(e[t]=this.clone(s),i){let r=e[t].metas.map(e=>e.phx_ref),s=i.metas.filter(e=>0>r.indexOf(e.phx_ref));e[t].metas.unshift(...s)}r(t,i,s)}),this.map(n,(t,r)=>{let i=e[t];if(!i)return;let n=r.metas.map(e=>e.phx_ref);i.metas=i.metas.filter(e=>0>n.indexOf(e.phx_ref)),s(t,i,r),0===i.metas.length&&delete e[t]}),e}static list(e,t){return t||(t=function(e,t){return t}),this.map(e,(e,r)=>t(e,r))}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static toNullProtoObj(e){if(null===Object.getPrototypeOf(e))return e;let t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(r=>{t[r]=e[r]}),t}static clone(e){return JSON.parse(JSON.stringify(e))}},eT={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){return e.payload.constructor===ArrayBuffer?t(this.binaryEncode(e)):t(JSON.stringify([e.join_ref,e.ref,e.topic,e.event,e.payload]))},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[r,s,i,n,a]=JSON.parse(e);return t({join_ref:r,ref:s,topic:i,event:n,payload:a})}},binaryEncode(e){let{join_ref:t,ref:r,event:s,topic:i,payload:n}=e,a=new TextEncoder,o=a.encode(t),l=a.encode(r),h=a.encode(i),u=a.encode(s);this.assertFieldSize(o.byteLength,"join_ref"),this.assertFieldSize(l.byteLength,"ref"),this.assertFieldSize(h.byteLength,"topic"),this.assertFieldSize(u.byteLength,"event");let c=this.META_LENGTH+o.byteLength+l.byteLength+h.byteLength+u.byteLength,d=new ArrayBuffer(this.HEADER_LENGTH+c),p=new Uint8Array(d),f=new DataView(d),g=0;f.setUint8(g++,this.KINDS.push),f.setUint8(g++,o.byteLength),f.setUint8(g++,l.byteLength),f.setUint8(g++,h.byteLength),f.setUint8(g++,u.byteLength),p.set(o,g),g+=o.byteLength,p.set(l,g),g+=l.byteLength,p.set(h,g),g+=h.b
6yteLength,p.set(u,g),g+=u.byteLength;var m=new Uint8Array(d.byteLength+n.byteLength);return m.set(p,0),m.set(new Uint8Array(n),d.byteLength),m.buffer},assertFieldSize(e,t){if(e>255)throw Error(`unable to convert ${t} to binary: must be less than or equal to 255 bytes, but is ${e} bytes`)},binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(e,t,s);case this.KINDS.reply:return this.decodeReply(e,t,s);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,s)}},decodePush(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=t.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(e.slice(a,a+s));a+=s;let l=r.decode(e.slice(a,a+i));a+=i;let h=r.decode(e.slice(a,a+n));return a+=n,{join_ref:o,ref:null,topic:l,event:h,payload:e.slice(a,e.byteLength)}},decodeReply(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(e.slice(o,o+s));o+=s;let h=r.decode(e.slice(o,o+i));o+=i;let u=r.decode(e.slice(o,o+n));o+=n;let c=r.decode(e.slice(o,o+a));return o+=a,{join_ref:l,ref:h,topic:u,event:eg,payload:{status:c,response:e.slice(o,e.byteLength)}}},decodeBroadcast(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=this.HEADER_LENGTH+2,a=r.decode(e.slice(n,n+s));n+=s;let o=r.decode(e.slice(n,n+i));return n+=i,{join_ref:null,ref:null,topic:a,event:o,payload:e.slice(n,e.byteLength)}}},eA=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||1e4,this.transport=t.transport||eo.WebSocket||eS,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=eo&&eo.sessionStorage}catch{}this.sessionStore=t.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=eT.encode.bind(eT),this.defaultDecoder=eT.decode.bind(eT),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==eS?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;ea&&ea.addEventListener&&(ea.addEventListener("pagehide",e=>{this.conn&&(this.disconnect(),s=this.connectClock)}),ea.addEventListener("pageshow",e=>{s===this.connectClock&&(s=null,this.connect())}),ea.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this.pageHidden=!0:(this.pageHidden=!1,this.isConnected()||this.closeWasClean||this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=e=>t.rejoinAfterMs?t.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4,this.reconnectAfterMs=e=>t.reconnectAfterMs?t.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(e,t,r)=>{console.log(`${e}: ${t}`,r)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=en(t.params||{}),this.endPoint=`${e}/${ey}`,this.vsn=t.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new ev(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken&&en(t.authToken)}getLongPollTransport(){return eS}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=ek.appendParams(ek.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"!==e.charAt(0)?e:"/"===e.charAt(1)?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,r)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=en(e)),(!this.conn||this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==eS?this.connectWithF
6allback(eS,this.longPollFallbackMs):this.transportConnect())}log(e,t,r){this.logger&&this.logger(e,t,r)}hasLogger(){return null!==this.logger}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let s=this.onMessage(i=>{i.ref===t&&(this.off([s]),e(Date.now()-r))});return!0}transportName(e){return e===eS?"LongPoll":e.name}transportConnect(){let e;this.connectClock++,this.closeWasClean=!1,this.authToken&&(e=["phoenix",`${eb}${btoa(this.authToken()).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){let r,s;clearTimeout(this.fallbackTimer);let i=!1,n=!0,a=this.transportName(e),o=t=>{this.log("transport",`falling back to ${a}...`,t),this.off([r,s]),n=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o("memorized");this.fallbackTimer=setTimeout(o,t),s=this.onError(e=>{this.log("transport","error",e),n&&!i&&(clearTimeout(this.fallbackTimer),o(e))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(i=!0,!n){let t=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t}`,"true"),this.log("transport",`established ${t} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,t),this.ping(e=>{this.log("transport","connected to primary after",e),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),1e3,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,r){if(!this.conn)return e&&e();let s=this.conn;this.waitForBufferDone(s,()=>{t?s.close(t,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,r=1){5!==r&&e.bufferedAmount?setTimeout(()=>{this.waitForBufferDone(e,t,r+1)},150*r):t()}waitForSocketClosed(e,t,r=1){5===r||3===e.readyState?t():setTimeout(()=>{this.waitForSocketClosed(e,t,r+1)},150*r)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(e),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",e)}onConnError(e){this.hasLogger()&&this.log("transport","error",e);let t=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",e,t,r),(t===this.transport||r>0)&&this.triggerChanError(e)}
6triggerChanError(e){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(ef,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case 0:return"connecting";case 1:return"open";case 2:return"closing";default:return"closed"}}isConnected(){return"open"===this.connectionState()}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([t])=>-1===e.indexOf(t))}channel(e,t={}){let r=new e_(e,t,this);return this.channels.push(r),r}push(e){if(this.hasLogger()){let{topic:t,event:r,payload:s,ref:i,join_ref:n}=e;this.log("push",`${t} ${r} (${n}, ${i})`,s)}this.isConnected()?this.encode(e,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(e,e=>this.conn.send(e)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}return}if(this.pendingHeartbeatRef)return void this.heartbeatTimeout();this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:r,payload:s,ref:i,join_ref:n}=e;if(i&&i===this.pendingHeartbeatRef){let e=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback("ok"===s.status?"ok":"error",e)}catch(e){this.log("error","error in heartbeat callback",e)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${s.status||""} ${t} ${r} ${i&&"("+i+")"||""}`.trim(),s);for(let e=0;e<this.channels.length;e++){let a=this.channels[e];a.isMember(t,r,s,n)&&a.trigger(r,s,i,n)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(e,...t){try{this.stateChangeCallbacks[e].forEach(([r,s])=>{try{s(...t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t.isJoined()||t.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};class eR{constructor(e,t){const r=function(e){return(null==e?void 0:e.events)&&{events:e.events}}(t);this.presence=new eE(e.getChannel(),r),this.presence.onJoin((t,r,s)=>{let i=eR.onJoinPayload(t,r,s);e.getChannel().trigger("presence",i)}),this.presence.onLeave((t,r,s)=>{let i=eR.onLeavePayload(t,r,s);e.getChannel().trigger("presence",i)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return eR.transformState(this.presence.state)}static transformState(e){return Object.getOwnPropertyNames(e=JSON.parse(JSON.stringify(e))).reduce((t,r)=>{let s=e[r];return t[r]=eO(s),t},{})}static onJoinPayload(e,t,r){return{event:"join",key:e,currentPresences:eC(t),newPresences:eO(r)}}static onLeavePayload(e,t,r){return{event:"leave",key:e,currentPresences:eC(t),leftPresences:eO(r)}}}function eO(e){return e.metas.map(e=>{let t=Object.defineProperties({},Object.getOwnPropertyDescriptors(e));return t.presence_ref=t.phx_ref,delete t.phx_ref,delete t.phx_ref_prev,t})}function eC(e){return(null==e?void 0:e.metas)?eO(e):[]}(o=p||(p={})).SYNC="sync",o.JOIN="join",o.LEAVE="leave";class ex{get state(){return this.presenceAdapter.state}constructor(e,t){this.channel=e,this.presenceAdapter=new eR(this.channel.channelAdapter,t)}}class ej{constructor(e,t,r){const s=function(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},e.config)}}(r);this.channel=e.getSocket().channel(t,s),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,t){return this.channel.on(e,t)}off(e,t){this.channel.off(e,t)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,t,r){let s;try{s=this.channel.push(e,t,r)}catch(t){throw Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>100){let e=this.channel.pushBuffer.shift();e.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload())}return s}updateJoinPayload(e){let t=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},t),e)}canPush(){return this.socket.isConnected()&&this.state===z}isJoined(){return this.state===z}isJoining(){return"joining"===this.state}isClosed(){return"closed"===this.state}isLeaving(){return"leaving"===this.state}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}let eP=/[,()"\\]/,eI=e=>{let t=null===e?"null":String(e);return eP.test(t)||t!==t.trim()?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t};class e${constructor(){this.filters=[]}add(e,t,r,s=!1){return this.filters.push(`${e}=${s?"not.":""}${((e,t)=>{if("in"===e){let e=Array.isArray(t)?t:[t];if(0===e.length)throw Error("Realtime `in` filter requires at least one value.");let r=Array.from(new Set(e)).map(e=>eI(e)).join(",");return`in.(${r})`}if("is"===e)return`is.${null===t?"null":String(t)}`;return`${e}.${eI(t)}`})(t,r)}`),this}eq(e,t){return this.add(e,"eq",t)}neq(e,t){return this.add(e,"neq",t)}gt(e,t){return this.add(e,"gt",t)}gte(e,t){return this.add(e,"gte",t)}lt(e,t){return this.add(e,"lt",t)}lte(e,t){return this.add(e,"lte",t)}in(e,t){return this.add(e,"in",t)}like(e,t){return this.add(e,"like",t)}ilike(e,t){return this.add(e,"ilike",t)}match(e,t){return this.add(e,"match",t)}imatch(e,t){return this.add(e,"imatch",t)}is(e,t){return this.add(e,"is",t)}isDistinct(e,t){return this.add(e,"isdistinct",t)}not(e,t,r){return this.add(e,t,r,!0)}build(){return this.filters.join(",")}toString(){return this.build()}}(l=f||(f={})).ALL="*",l.INSERT="INSERT",l.UPDATE="UPDATE",l.DELETE="DELETE",(h=g||(g={})).BROADCAST="broadcast",h.PRESENCE="presence",h.POSTGRES_CHANGES="postgres_changes",h.SYSTEM="system",(u=m||(m={})).SUBSCRIBED="SUBSCRIBED",u.TIMED_OUT="TIMED_OUT",u.CLOSED="CLOSED",u.CHANNEL_ERROR="CHANNEL_ERROR";class eN{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,t={config:{}},r){var s,i;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.channelAdapter=new ej(this.socket.socketAdapter,e,this.params),this.presence=new ex(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=ei(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(null==(i=null==(s=this.params.config)?void 0:s.broadcast)?void 0:i.replay))throw Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,t=this.timeout){var r,s,i,n;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:a,presence:o,private:l,postgres_changes_options:h}}=this.params,u=null!=(s=null==(r=this.bindings.postgres_changes)?void 0:r.map(e=>e.filter))?s:[],c=!!this.bindings[g.PRESENCE]&&this.bindings[g.PRESENCE].length>0||(null==(i=this.params.config.presence)?void 0:i.enabled)===!0,d={},p=Object.assign({broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:c}),postgres_changes:u,private:l},h?{postgres_changes_options:h}:{});this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(t=>{null==e||e(m.CHANNEL_ERROR,function(e){if(e instanceof Error)return e;if("string"==typeof e)return Error(e);
6if(e&&"object"==typeof e){if("number"==typeof e.code){let t="string"==typeof e.reason&&e.reason?` (${e.reason})`:"";return Error(`socket closed: ${e.code}${t}`,{cause:e})}return Error("channel error: transport failure",{cause:e})}return Error("channel error: connection lost")}(t))}),this._onClose(()=>null==e?void 0:e(m.CLOSED)),this.updateJoinPayload(Object.assign({config:p},d)),this._updateFilterMessage();let f=(null==h?void 0:h.wait)&&u.length>0?Math.max(t,(null!=(n=h.timeout)?n:15e3)+1e4):t;this.channelAdapter.subscribe(f).receive("ok",async({postgres_changes:t})=>{if(this.socket._isManualToken()||this.socket.setAuth(),void 0===t){null==e||e(m.SUBSCRIBED);return}this._updatePostgresBindings(t,e)}).receive("error",t=>{this.state=K;let r=Object.values(t).join(", ")||"error";null==e||e(m.CHANNEL_ERROR,Error(r,{cause:t}))}).receive("timeout",()=>{null==e||e(m.TIMED_OUT)})}return this}_updatePostgresBindings(e,t){var r;let s=this.bindings.postgres_changes,i=null!=(r=null==s?void 0:s.length)?r:0,n=[];for(let r=0;r<i;r++){let i=s[r],{filter:{event:a,schema:o,table:l,filter:h}}=i,u=e&&e[r];if(u&&u.event===a&&eN.isFilterValueEqual(u.schema,o)&&eN.isFilterValueEqual(u.table,l)&&eN.isFilterValueEqual(u.filter,h))n.push(Object.assign(Object.assign({},i),{id:u.id}));else{this.unsubscribe(),this.state=K,null==t||t(m.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=n,this.state!=K&&t&&t(m.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){let s=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===g.PRESENCE||e===g.POSTGRES_CHANGES;if(s&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,t,r)}async httpSend(e,t,r={}){var s;if(null==t)return Promise.reject(Error("Payload is required for httpSend()"));let i=t instanceof ArrayBuffer||ArrayBuffer.isView(t),n={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":i?"application/octet-stream":"application/json"};this.socket.accessTokenValue&&(n.Authorization=`Bearer ${this.socket.accessTokenValue}`);let a=new URL(this.broadcastEndpointURL);a.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(e)}`,this.private&&a.searchParams.set("private","true");let o={method:"POST",headers:n,body:i?t:JSON.stringify(t)},l=await this._fetchWithTimeout(a.toString(),o,null!=(s=r.timeout)?s:this.timeout);if(202===l.status)return{success:!0};if(404===l.status)return Promise.reject(Error("httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. See https://github.com/supabase/supabase-js/blob/master/packages/core/realtime-js/migrations/httpsend-server-version.md"));let h=l.statusText;try{let e=await l.json();h=e.error||e.message||h}catch(e){}return Promise.reject(Error(h))}async send(e,t={}){var r,s;if(this.channelAdapter.canPush()||"broadcast"!==e.type)return new Promise(r=>{var s,i,n;let a=this.channelAdapter.push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null==(n=null==(i=null==(s=this.params)?void 0:s.config)?void 0:i.broadcast)?void 0:n.ack)||r("ok"),a.receive("ok",()=>r("ok")),a.receive("error",()=>r("error")),a.receive("timeout",()=>r("timed out"))});{let i="Realtime send() is automatically falling back to REST API. This behavior will be deprecated
6in the future. Please use httpSend() explicitly for REST delivery.";this.socket.hasLogger()?this.socket.log("channel",i):console.warn(i);let{event:n,payload:a}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:a,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,l,null!=(r=t.timeout)?r:this.timeout);return await (null==(s=e.body)?void 0:s.cancel()),e.ok?"ok":"error"}catch(e){if(e instanceof Error&&"AbortError"===e.name)return"timed out";return"error"}}}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(t=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>t("ok")).receive("timeout",()=>t("timed out")).receive("error",()=>t("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,t,r){let s=new AbortController,i=setTimeout(()=>s.abort(),r),n=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(i),n}_on(e,t,r){var s;let i=e.toLocaleLowerCase(),n=null==t?void 0:t.filter;if((n instanceof e$||"object"==typeof n&&null!==n&&"function"==typeof n.build)&&(t=Object.assign(Object.assign({},t),{filter:n.build()})),i===g.POSTGRES_CHANGES&&(null==(s=this.bindings[i])?void 0:s.find(e=>eN.isSamePostgresFilter(e.filter,t))))return this.socket.log("error",`duplicate \`postgres_changes\` binding for ${this.topic} ignored`,t),this;let a=this.channelAdapter.on(e,r),o={type:i,filter:t,callback:r,ref:a};return this.bindings[i]?this.bindings[i].push(o):this.bindings[i]=[o],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,t,r)=>{var s,i,n,a,o,l,h;let u=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(u,r))return!1;let c=null==(s=this.bindings[u])?void 0:s.find(t=>t.ref===e.ref);if(!c)return!0;if(!["broadcast","presence","postgres_changes"].includes(u))return c.type.toLocaleLowerCase()===u;if("id"in c){let e=c.id,r=null==(i=c.filter)?void 0:i.event;return e&&(null==(n=t.ids)?void 0:n.includes(e))&&("*"===r||(null==r?void 0:r.toLocaleLowerCase())===(null==(a=t.data)?void 0:a.type.toLocaleLowerCase()))}{let e=null==(l=null==(o=null==c?void 0:c.filter)?void 0:o.event)?void 0:l.toLocaleLowerCase();return"*"===e||e===(null==(h=null==t?void 0:t.event)?void 0:h.toLocaleLowerCase())}})}_notThisChannelEvent(e,t){let{close:r,error:s,leave:i,join:n}=J;return t&&[r,s,i,n].includes(e)&&t!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,t,r)=>{if("object"==typeof t&&"ids"in t){let e=t.data,{schema:r,table:s,commit_timestamp:i,type:n,errors:a}=e;return Object.assign(Object.assign({},{schema:r,table:s,commit_timestamp:i,eventType:n,new:{},old:{},errors:a}),this._getPayloadRecords(e))}return t})}copyBindings(e){if(this.joinedOnce)throw Error("cannot copy bindings into joined channel");for(let t in e.bindings)for(let r of e.bindings[t])this._on(r.type,r.filter,r.callback)}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}static isSamePostgresFilter(e,t){var r,s,i,n;let a=null!=(s=null==(r=null==e?void 0:e.select)?void 0:r.join())?s:void 0,o=null!=(n=null==(i=null==t?void 0:t.select)?void 0:i.join())?n:void 0;return(null==e?void 0:e.event)===(null==t?void 0:t.event)&&eN.isFilterValueEqual(null==e?void 0:e.schema,null==t?void 0:t.schema)&&eN.isFilterValueEqual(null==e?void 0:e.table,null==t?void 0:t.table)&&eN.isFilterValueEqual(null==e?void 0:e.filter,null==t?void 0:t.filter)&&a===o}_getPayloadRecords(e){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=V(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=V(e.columns,e.old_record)),t}}class eU{constructor(e,t){this.socket=new eA(e,t)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,t,r,s=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),s),this.socket.disconnect(()=>{e(),i("ok")},t,r)})}push(e){this.socket.push(e)}log(e,t,r){this.socket.log(e,t,r)}hasLogger(){return this.socket.hasLogger()}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return"connecting"==this.socket.connectionState()}isDisconnecting(){return"closing"==this.socket.connectionState()}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}let eL=[1e3,2e3,5e3,1e4],eB=` 7 addEventListener("message", (e) => { 8 if (e.data.event === "start") { 9 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 10 } 11 });`;class eD{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,t){var r;if(this.channels=[],this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={}
11,this.ref=0,this.serializer=new G,this._manuallySetToken=!1,this._authPromise=null,this._authGeneration=0,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null==(r=null==t?void 0:t.params)?void 0:r.apikey))throw Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey;const s=this._initializeOptions(t);this.socketAdapter=new eU(e,s),this.httpEndpoint=ei(e),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(t){let e=t.message;throw Error(`WebSocket not available: ${e}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,t){return(this._cancelPendingDisconnect(),this.isDisconnecting())?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,t)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return"ok"===t&&e.teardown(),t}async removeAllChannels(){let e=this.channels.map(async e=>{let t=await e.unsubscribe();return e.teardown(),t}),t=await Promise.all(e);return await this.disconnect(),t}log(e,t,r){this.socketAdapter.log(e,t,r)}hasLogger(){return this.socketAdapter.hasLogger()}connectionState(){return this.socketAdapter.connectionState()||"closed"}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,t={config:{}}){let r=`realtime:${e}`,s=this.getChannels().find(e=>e.topic===r);if(s)return s;{let r=new eN(`realtime:${e}`,t,this);return this._cancelPendingDisconnect(),this.channels.push(r),r}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){let t=++this._authGeneration,r=this._performAuth(e,t);t===this._authGeneration&&(this._authPromise=r);try{await r}finally{this._authPromise===r&&(this._authPromise=null)}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic),0===this.channels.length&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),0===this._disconnectOnEmptyChannelsAfterMs){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}
11this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,0===this.channels.length&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){null!==this._pendingDisconnectTimer&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e,t){let r,s=!1;if(e)r=e,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),r=this.accessTokenValue}else r=this.accessTokenValue;t===this._authGeneration&&(this.accessToken?this._manuallySetToken=!1:s&&(this._manuallySetToken=!0),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(e=>{let t={access_token:r,version:"realtime-js/2.116.0"};e.updateJoinPayload(t),e.joinedOnce&&e.channelAdapter.isJoined()&&e.channelAdapter.push(J.access_token,{access_token:r})})))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(e=>{this.log("error","error waiting for auth on connect",e)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(t,r)=>{"disconnected"!==t&&("sent"==t&&this._setAuthSafely(),e&&e(t,r))}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob([eB],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_initializeOptions(e){var t,r,s,i,n,a,o,l,h,u,c,d;let p,f;this.worker=null!=(t=null==e?void 0:e.worker)&&t,this.accessToken=null!=(r=null==e?void 0:e.accessToken)?r:null;let g={};g.timeout=null!=(s=null==e?void 0:e.timeout)?s:1e4,g.heartbeatIntervalMs=null!=(i=null==e?void 0:e.heartbeatIntervalMs)?i:25e3,this._disconnectOnEmptyChannelsAfterMs=null!=(n=null==e?void 0:e.disconnectOnEmptyChannelsAfterMs)?n:2*(null!=(a=null==e?void 0:e.heartbeatIntervalMs)?a:25e3),g.transport=null!=(o=null==e?void 0:e.transport)?o:H.getWebSocketConstructor(),g.params=null==e?void 0:e.params,g.logger=null==e?void 0:e.logger,g.heartbeatCallback=this._wrapHeartbeatCallback(null==e?void 0:e.heartbeatCallback),g.sessionStorage=null!=(l=null==e?void 0:e.sessionStorage)?l:function(){let e;try{if("u">typeof globalThis&&globalThis.sessionStorage)return globalThis.sessionStorage}catch(e){}return e=new Map,{get length(){return e.size},clear(){e.clear()},getItem:t=>e.has(t)?e.get(t):null,key(t){var r;return null!=(r=Array.from(e.keys())[t])?r:null},removeItem(t){e.delete(t)},setItem(t,r){e.set(t,String(r))}}}(),g.reconnectAfterMs=null!=(h=null==e?void 0:e.reconnectAfterMs)?h:e=>eL[e-1]||1e4;let m=null!=(u=null==e?void 0:e.vsn)?u:W;switch(m){case"1.0.0":p=(e,t)=>t(JSON.stringify(e)),f=(e,t)=>t(JSON.parse(e));break;case W:p=this.serializer.encode.bind(this.serializer),f=this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${g.vsn}`)}if(g.vsn=m,g.encode=null!=(c=null==e?void 0:e.encode)?c:p,g.decode=null!=(d=null==e?void 0:e.decode)?d:f,g.beforeReconnect=this._reconnectAuth.bind(this),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,g.params=Object.assign(Object.assign({},g.params),{log_level:this.logLevel})),this.worker){if("u">typeof window&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl,g.autoSendHeartbeat=!this.worker}return g}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}
11var eq=e.i(89984),eM=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&t.icebergType?.includes("CommitState")===!0}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};async function eF(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}function eH(e){return e.join("\x1f")}var eW=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:eH(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){let r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${eH(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${eH(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${eH(e.namespace)}`}),!0}catch(e){if(e instanceof eM&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof eM&&409===e.status)return;throw e}}};function eK(e){return e.join("\x1f")}var ez=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${eK(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${eK(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${eK(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${eK(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${eK(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${eK(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof eM&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof eM&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},eJ=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=function(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:i,body:n,headers:a}){let o=function(e,t,r){let s=new URL(t,e);if(r)for(let[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,s,i),l=await eF(e.auth),h=await t(o,{method:r,headers:{...n?{"Content-Type":"application/json"}:{},...l,...a},body:n?JSON.stringify(n):void 0}),u=await h.text(),c=(h.headers.get("content-type")||"").includes("application/json"),d=c&&u?JSON.parse(u):u;if(!h.ok){let e=c?d:void 0,t=e?.error;throw new eM(t?.message??`Request failed with status ${h.status}`,{status:h.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:h.status,headers:h.headers,data:d}}}}({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new eW(this.client,t),this.tableOps=new ez(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}
11async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};function eG(e){return(eG="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function eV(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function eY(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?eV(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=eG(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=eG(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==eG(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):eV(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}var eX=class extends Error{constructor(e,t="storage",r,s){super(e),this.__isStorageError=!0,this.namespace=t,this.name="vectors"===t?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function eQ(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var eZ=class extends eX{constructor(e,t,r,s="storage",i){super(e,s,t,r),this.name="vectors"===s?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=r,this.co
11de=i}toJSON(){return eY(eY({},super.toJSON()),{},{code:this.code})}},e0=class extends eX{constructor(e,t,r="storage"){super(e,r),this.name="vectors"===r?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};function e1(e,t,r){let s=eY({},e),i=t.toLowerCase();for(let e of Object.keys(s))e.toLowerCase()===i&&delete s[e];return s[i]=r,s}let e2=e=>{if(Array.isArray(e))return e.map(e=>e2(e));if("function"==typeof e||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([e,r])=>{t[e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""))]=e2(r)}),t},e5=e=>e.split("/").map(encodeURIComponent).join("/"),e6=e=>{if("object"==typeof e&&null!==e){if("string"==typeof e.msg)return e.msg;if("string"==typeof e.message)return e.message;if("string"==typeof e.error_description)return e.error_description;if("string"==typeof e.error)return e.error;if("object"==typeof e.error&&null!==e.error){let t=e.error;if("string"==typeof t.message)return t.message}}return JSON.stringify(e)},e8=async(e,t,r,s)=>{if(null!==e&&"object"==typeof e&&"json"in e&&"function"==typeof e.json){let r=parseInt(String(e.status),10);Number.isFinite(r)||(r=500),e.json().then(e=>{let i=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new eZ(e6(e),r,i,s,null==e?void 0:e.code))}).catch(()=>{let i=r+"";t(new eZ(e.statusText||`HTTP ${r} error`,r,i,s))})}else t(new e0(e6(e),e,s))};async function e3(e,t,r,s,i,n,a){return new Promise((o,l)=>{e(r,((e,t,r,s)=>{let i={method:e,headers:(null==t?void 0:t.headers)||{}};if("GET"===e||"HEAD"===e||!s)return eY(eY({},i),r);if((e=>{if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)})(s)){var n;let e,r=(null==t?void 0:t.headers)||{};for(let[t,s]of Object.entries(r))"content-type"===t.toLowerCase()&&(e=s);i.headers=e1(r,"Content-Type",null!=(n=e)?n:"application/json"),i.body=JSON.stringify(s)}else i.body=s;return(null==t?void 0:t.duplex)&&(i.duplex=t.duplex),eY(eY({},i),r)})(t,s,i,n)).then(e=>{if(!e.ok)throw e;if(null==s?void 0:s.noResolveJson)return e;if("vectors"===a){let t=e.headers.get("content-type");if("0"===e.headers.get("content-length")||204===e.status||!t||!t.includes("application/json"))return{}}return e.json()}).then(e=>o(e)).catch(e=>e8(e,l,s,a))})}function e4(e="storage"){return{get:async(t,r,s,i)=>e3(t,"GET",r,s,i,void 0,e),post:async(t,r,s,i,n)=>e3(t,"POST",r,i,n,s,e),put:async(t,r,s,i,n)=>e3(t,"PUT",r,i,n,s,e),head:async(t,r,s,i)=>e3(t,"HEAD",r,eY(eY({},s),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,r,s,i,n)=>e3(t,"DELETE",r,i,n,s,e)}}let{get:e9,post:e7,put:te,head:tt,remove:tr}=e4("storage"),ts=e4("vectors");var ti=class{constructor(e,t={},r,s="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=function(e){let t={};for(let[r,s]of Object.entries(e))t[r.toLowerCase()]=s;return t}(t),this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=e1(this.headers,e,t),this}async handleOperation(e){try{return{data:await e(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eQ(e))return{data:null,error:e};throw e}}};t=Symbol.toStringTag;var tn=class{constructor(e,r){this.downloadFn=e,this.shouldThrowOnError=r,this[t]="StreamDownloadBuilder",this.promise=null}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eQ(e))return{data:null,error:e};throw e}}};r=Symbol.toStringTag;var ta=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[r]="BlobDownloadBuilder",this.promise=null}asStream(){return new tn(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await (await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eQ(e))return{data:null,error:e};throw e}}};let to={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},tl={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var th=class extends ti{constructor(e,t={},r,s){super(e,t,s,"storage"),this.bucketId=r}async uploadOrUpdate(e,t,r,s){var i=this;return i.handleOperation(async()=>{let n,a=eY(eY({},tl),s),o=eY(eY({},i.headers),"POST"===e&&{"x-upsert":String(a.upsert)}),l=a.metadata;if("u">typeof Blob&&r instanceof Blob?((n=new FormData).append("cacheControl",a.cacheControl),l&&n.append("metadata",i.encodeMetadata(l)),n.append("",r)):"u">typeof FormData&&r instanceof FormData?((n=r).has("cacheControl")||n.append("cacheControl",a.cacheControl),l&&!n.has("metadata")&&n.append("metadata",i.encodeMetadata(l))):(n=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=i.toBase64(i.encodeMetadata(l))),("u">typeof ReadableStream&&n instanceof ReadableStream||n&&"object"==typeof n&&"pipe"in n&&"function"==typeof n.pipe)&&!a.duplex&&(a.duplex="half")),null==s?void 0:s.headers)for(let[e,t]of Object.entries(s.headers))o=e1(o,e,t);let h=i._removeEmptyFolders(t),u=i._getFinalPath(h),c=await ("PUT"==e?te:e7)(i.fetch,`${i.url}/object/${u}`,n,eY({headers:o},(null==a?void 0:a.duplex)?{duplex:a.duplex}:{}));return{path:h,id:c.Id,fullPath:c.Key}})}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,s){var i=this;let n=i._removeEmptyFolders(e),a=i._getFinalPath(n),o=new URL(i.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",t),i.handleOperation(async()=>{let e,t=eY(eY({},tl),s),a=eY(eY({},i.headers),{"x-upsert":String(t.upsert)}),l=t.metadata;if("u">typeof Blob&&r instanceof Blob?((e=new FormData).append("cacheControl",t.cacheControl),l&&e.append("metadata",i.encodeMetadata(l)),e.append("",r)):"u">typeof FormData&&r instanceof FormData?((e=r).has("cacheControl")||e.append("cacheControl",t.cacheControl),l&&!e.has("metadata")&&e.append("metadata",i.encodeMetadata(l))):(e=r,a["cache-control"]=`max-age=${t.cacheControl}`,a["content-type"]=t.contentType,l&&(a["x-metadata"]=i.toBase64(i.encodeMetadata(l))),("u">typeof ReadableStream&&e instanceof ReadableStream||e&&"object"==typeof e&&"pipe"in e&&"function"==typeof e.pipe)&&!t.duplex&&(t.duplex="half")),null==s?void 0:s.headers)for(let[e,t]of Object.entries(s.headers))a=e1(a,e,t);return{path:n,fullPath:(await te(i.fetch,o.toString(),e,eY({headers:a},(null==t?void 0:t.duplex)?{duplex:t.duplex}:{}))).Key}})}async createSignedUploadUrl(e,t){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(e),i=eY({},r.headers);(null==t?void 0:t.upsert)&&(i["x-upsert"]="true");let n=await e7(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:i}),a=new URL(r.url+n.url),o=a.searchParams.get("token");if(!o)throw new eX("No token returned by API");return{signedUrl:a.toString(),path:e,token:o}})}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var s=this;return s.handleOperation(async()=>await e7(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,de
11stinationBucket:null==r?void 0:r.destinationBucket,sourceVersionId:null==r?void 0:r.sourceVersionId},{headers:s.headers}))}async copy(e,t,r){var s=this;return s.handleOperation(async()=>({path:(await e7(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket,sourceVersionId:null==r?void 0:r.sourceVersionId},{headers:s.headers})).Key}))}async createSignedUrl(e,t,r){var s=this;return s.handleOperation(async()=>{let i=s._getFinalPath(e),n="object"==typeof(null==r?void 0:r.transform)&&null!==r.transform&&Object.keys(r.transform).length>0,a=await e7(s.fetch,`${s.url}/object/sign/${i}`,eY(eY({expiresIn:t},n?{transform:r.transform}:{}),(null==r?void 0:r.versionId)!=null?{versionId:r.versionId}:{}),{headers:s.headers}),o=new URLSearchParams;(null==r?void 0:r.download)&&o.set("download",!0===r.download?"":r.download),(null==r?void 0:r.cacheNonce)!=null&&o.set("cacheNonce",String(r.cacheNonce));let l=o.toString();return{signedUrl:encodeURI(`${s.url}${a.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(e,t,r){var s=this;return s.handleOperation(async()=>{let i=await e7(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:t,paths:e},{headers:s.headers}),n=new URLSearchParams;(null==r?void 0:r.download)&&n.set("download",!0===r.download?"":r.download),(null==r?void 0:r.cacheNonce)!=null&&n.set("cacheNonce",String(r.cacheNonce));let a=n.toString();return i.map(e=>eY(eY({},e),{},{signedUrl:e.signedURL?encodeURI(`${s.url}${e.signedURL}${a?`&${a}`:""}`):null}))})}download(e,t,r){let s="object"==typeof(null==t?void 0:t.transform)&&null!==t.transform&&Object.keys(t.transform).length>0?"render/image/authenticated":"object",i=new URLSearchParams;(null==t?void 0:t.transform)&&this.applyTransformOptsToQuery(i,t.transform),(null==t?void 0:t.cacheNonce)!=null&&i.set("cacheNonce",String(t.cacheNonce)),(null==t?void 0:t.versionId)!=null&&i.set("versionId",String(t.versionId));let n=i.toString(),a=this._getFinalPath(e);return new ta(()=>e9(this.fetch,`${this.url}/${s}/${a}${n?`?${n}`:""}`,{headers:this.headers,noResolveJson:!0},r),this.shouldThrowOnError)}async info(e,t){var r=this;let s=r._getFinalPath(e),i=new URLSearchParams;(null==t?void 0:t.versionId)!=null&&i.set("versionId",String(t.versionId));let n=i.toString();return r.handleOperation(async()=>e2(await e9(r.fetch,`${r.url}/object/info/${s}${n?`?${n}`:""}`,{headers:r.headers})))}async exists(e){var t;let r=this._getFinalPath(e);try{return await tt(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(eQ(e)){let r=e instanceof eZ?e.status:e instanceof e0?null==(t=e.originalError)?void 0:t.status:void 0;if(void 0!==r&&[400,404].includes(r))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let r=this._getFinalPath(e),s=new URLSearchParams;(null==t?void 0:t.download)&&s.set("download",!0===t.download?"":t.download),(null==t?void 0:t.transform)&&this.applyTransformOptsToQuery(s,t.transform),(null==t?void 0:t.cacheNonce)!=null&&s.set("cacheNonce",String(t.cacheNonce)),(null==t?void 0:t.versionId)!=null&&s.set("versionId",String(t.versionId));let i=s.toString(),n="object"==typeof(null==t?void 0:t.transform)&&null!==t.transform&&Object.keys(t.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${n}/public/${r}`)+(i?`?${i}`:"")}}}async remove(e){var t=this;return t.handleOperation(async()=>await tr(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async purgeCache(e,t,r){var s=this;return s.handleOperation(async()=>{let i=e5(s._getFinalPath(e)),n=new URLSearchParams;(null==t?void 0:t.transformations)&&n.set("transformations","true");let a=n.toString();return await tr(s.fetch,`${s.url}/cdn/${i}${a?`?${a}`:""}`,{},{headers:s.headers},r)})}async list(e,t,r){var s=this;return s.handleOperation(async()=>{let i=(null==t?void 0:t.sortBy)?eY(eY({},to.sortBy),t.sortBy):to.sortBy,n=eY(eY(eY({},to),t),{},{sortBy:i,prefix:e||""});return await e7(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r)})}async listV2(e,t){var r=this;return r.handleOperation(async()=>{let s=eY({},e);return await e7(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return void 0!==eq.Buffer?eq.Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(e,t){return t.width&&e.set("width",t.width.toString()),t.height&&e.set("height",t.height.toString()),t.resize&&e.set("resize",t.resize),t.format&&e.set("format",t.format),t.quality&&e.set("qual
11ity",t.quality.toString()),e}};let tu={"X-Client-Info":"storage-js/2.116.0"};var tc=class extends ti{constructor(e,t={},r,s){const i=new URL(e);(null==s?void 0:s.useNewHostname)&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),super(i.href.replace(/\/$/,""),eY(eY({},tu),t),r,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=t.listBucketOptionsToQueryString(e);return await e9(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await e9(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var r=this;return r.handleOperation(async()=>await e7(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes,versioning_status:t.versioningStatus},{headers:r.headers}))}async updateBucket(e,t){var r=this;return r.handleOperation(async()=>await te(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes,versioning_status:t.versioningStatus},{headers:r.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await e7(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await tr(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}async getBucketLifecycle(e){var t=this;return t.handleOperation(async()=>await e9(t.fetch,t.bucketLifecycleUrl(e),{headers:t.headers}))}async updateBucketLifecycle(e,t){var r=this;return r.handleOperation(async()=>await te(r.fetch,r.bucketLifecycleUrl(e),t,{headers:r.headers}))}async deleteBucketLifecycle(e){var t=this;return t.handleOperation(async()=>await tr(t.fetch,t.bucketLifecycleUrl(e),{},{headers:t.headers}))}async purgeBucketCache(e,t,r){var s=this;return s.handleOperation(async()=>{let i=new URLSearchParams;(null==t?void 0:t.transformations)&&i.set("transformations","true");let n=i.toString();return await tr(s.fetch,`${s.url}/cdn/${e5(e)}${n?`?${n}`:""}`,{},{headers:s.headers},r)})}bucketLifecycleUrl(e){return`${this.url}/bucket/${e5(e)}/lifecycle`}listBucketOptionsToQueryString(e){let t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},td=class extends ti{constructor(e,t={},r){super(e.replace(/\/$/,""),eY(eY({},tu),t),r,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await e7(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=new URLSearchParams;(null==e?void 0:e.limit)!==void 0&&r.set("limit",e.limit.toString()),(null==e?void 0:e.offset)!==void 0&&r.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&r.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&r.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&r.set("search",e.search);let s=r.toString(),i=s?`${t.url}/bucket?${s}`:`${t.url}/bucket`;return await e9(t.fetch,i,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await tr(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!(!(!e||"string"!=typeof e||0===e.length||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\"))&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e)))throw new eX("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new eJ({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(e,t){let r=e[t];return"function"!=typeof r?r:async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(e){if(s)throw e;return{data:null,error:e}}}}})}},tp=class extends ti{constructor(e,t={},r){super(e.replace(/\/$/,""),eY(eY({},tu),{},{"Content-Type":"application/json"},t),r,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await ts.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var r=this;return r.handleOperation(async()=>await ts.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await ts.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var r=this;return r.handleOperation(async()=>await ts.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{})}},tf=class extends ti{constructor(e,t={},r){super(e.replace(/\/$/,""),eY(eY({},tu),{},{"Content-Type":"application/json"},t),r,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await ts.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await ts.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw Error("segmentCount must be between 1 and 16");
11if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await ts.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await ts.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await ts.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},tg=class extends ti{constructor(e,t={},r){super(e.replace(/\/$/,""),eY(eY({},tu),{},{"Content-Type":"application/json"},t),r,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await ts.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await ts.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await ts.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await ts.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},tm=class extends tg{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new ty(this.url,this.headers,e,this.fetch)}async createBucket(e){return super.createBucket.call(this,e)}async getBucket(e){return super.getBucket.call(this,e)}async listBuckets(e={}){return super.listBuckets.call(this,e)}async deleteBucket(e){return super.deleteBucket.call(this,e)}},ty=class extends tp{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}async createIndex(e){return super.createIndex.call(this,eY(eY({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return super.listIndexes.call(this,eY(eY({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return super.getIndex.call(this,this.vectorBucketName,e)}async deleteIndex(e){return super.deleteIndex.call(this,this.vectorBucketName,e)}index(e){return new tb(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},tb=class extends tf{constructor(e,t,r,s,i){super(e,t,i),this.vectorBucketName=r,this.indexName=s}async putVectors(e){return super.putVectors.call(this,eY(eY({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async getVectors(e){return super.getVectors.call(this,eY(eY({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async listVectors(e={}){return super.listVectors.call(this,eY(eY({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async queryVectors(e){return super.queryVectors.call(this,eY(eY({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async deleteVectors(e){return super.deleteVectors.call(this,eY(eY({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}},tw=class extends tc{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new th(this.url,this.headers,e,this.fetch)}get vectors(){return new tm(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new td(this.url+"/iceberg",this.headers,this.fetch)}};let tv="2.116.0",t_={"X-Client-Info":`gotrue-js/${tv}`},tk="X-Supabase-Api-Version",tS={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},tE=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,tT="sb_flow_id";class tA extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function tR(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class tO extends tA{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}function tC(e){return tR(e)&&"AuthApiError"===e.name}class tx extends tA{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class tj extends tA{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class tP extends tj{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function tI(e){return tR(e)&&"AuthSessionMissingError"===e.name}class t$ extends tj{constructor(){super("Auth session or user missing","AuthInvalidToken
11ResponseError",500,void 0)}}class tN extends tj{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class tU extends tj{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class tL extends tj{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class tB extends tj{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 tD extends tj{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function tq(e){return tR(e)&&"AuthRetryableFetchError"===e.name}class tM extends tj{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}}function tF(e){return tR(e)&&"AuthRefreshDiscardedError"===e.name}class tH extends tj{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class tW extends tj{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}let tK="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),tz=" \n\r=".split(""),tJ=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<tz.length;t+=1)e[tz[t].charCodeAt(0)]=-2;for(let t=0;t<tK.length;t+=1)e[tK[t].charCodeAt(0)]=t;return e})();function tG(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;)r(tK[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)r(tK[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function tV(e,t,r){let s=tJ[e];if(s>-1)for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else if(-2===s)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}function tY(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return r(e);for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else if(4===t.utf8seq)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let t=0;t<e.length;t+=1)tV(e.charCodeAt(t),i,n);return t.join("")}function tX(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)tV(e.charCodeAt(t),r,s);return new Uint8Array(t)}function tQ(e){let t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>tG(e,r,s)),tG(null,r,s),t.join("")}function tZ(e){return Math.round(Date.now()/1e3)+e}let t0=()=>"u">typeof window&&"u">typeof document,t1={tested:!1,writable:!1},t2=()=>{if(!t0())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(t1.tested)return t1.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),t1.tested=!0,t1.writable=!0}catch(e){t1.tested=!0,t1.writable=!1}return t1.writable};function t5(e){let t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}let t6=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),t8=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},t3=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return null}},t4=async(e,t)=>{await e.removeItem(t)};class t9{constructor(){this.promise=new t9.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function t7(e){let t=e.split(".");if(3!==t.length)throw new tW("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!tE.test(t[e]))throw new tW("JWT not in base64url format");return{header:JSON.parse(tY(t[0])),payload:JSON.parse(tY(t[1])),signature:tX(t[2]),raw:{header:t[0],payload:t[1]}}}async function re(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function rt(e){return("0"+e.toString(16)).substr(-2)}async function rr(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>String.fromCharCode(e)).join("")}async function rs(e){return"u">typeof crypto&&void 0!==crypto.subtle&&"u">typeof TextEncoder?btoa(await rr(e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""):(console.warn("WebCrypto API is not supported. Code
11challenge method will default to use plain instead of sha256."),e)}t9.promiseConstructor=Promise;let ri=/^[a-zA-Z0-9_-]{8,64}$/;function rn(e){return"string"==typeof e&&ri.test(e)?e:null}let ra=(e,t)=>`${e}-flow-${t}-code-verifier`,ro=e=>`${e}-flows-code-verifier`;async function rl(e,t){let r=await t3(e,ro(t));return Array.isArray(r)?r.filter(e=>null!==rn(e)):[]}async function rh(e,t,r,s,i){await t8(e,ra(t,r),s);let n=(await rl(e,t)).filter(e=>e!==r);for(n.push(r);n.length>5;){let r=n.shift();await t4(e,ra(t,r)),null==i||i(r)}await t8(e,ro(t),n),await t8(e,`${t}-code-verifier`,s)}async function ru(e,t,r){if(r){let s=await t3(e,ra(t,r));return{verifier:"string"==typeof s?s:null,flowId:r}}let s=await t3(e,`${t}-code-verifier`);return{verifier:"string"==typeof s?s:null,flowId:null}}async function rc(e,t,r){let s=`${t}-code-verifier`;if(!r)return void await t4(e,s);let i=ra(t,r),n=await t3(e,i);await t4(e,i);let a=await rl(e,t),o=a.filter(e=>e!==r);o.length!==a.length&&(o.length>0?await t8(e,ro(t),o):await t4(e,ro(t))),null!=n&&n===await t3(e,s)&&await t4(e,s)}async function rd(e,t){for(let r of(await rl(e,t)))await t4(e,ra(t,r));await t4(e,ro(t)),await t4(e,`${t}-code-verifier`)}async function rp(e,t,r=!1,s){let i=function(){let e=new Uint32Array(56);if("u"<typeof crypto){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length,r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,rt).join("")}(),n=i;r&&(n+="/recovery");let a=function(){if("u">typeof crypto&&"function"==typeof crypto.getRandomValues){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,rt).join("")}let e="";for(let t=0;t<32;t++)e+=Math.floor(16*Math.random()).toString(16);return e}();await rh(e,t,a,n,s);let o=await rs(i),l=i===o?"plain":"s256";return[o,l,a]}let rf=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i,rg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rm(e){if(!rg.test(e))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ry(e){if(!e.passkey)throw Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function rb(e){if(!e.recoveryCodes)throw Error("@supabase/auth-js: the MFA recovery codes API is experimental and disabled by default. Enable it by passing `auth: { experimental: { recoveryCodes: true } }` to createClient (or to the GoTrueClient constructor).")}function rw(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){let e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function rv(e){return JSON.parse(JSON.stringify(e))}let r_=e=>{if("object"==typeof e&&null!==e){if("string"==typeof e.msg)return e.msg;if("string"==typeof e.message)return e.message;if("string"==typeof e.error_description)return e.error_description;if("string"==typeof e.error)return e.error}return JSON.stringify(e)},rk=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function rS(e){var t;let r,s;if(!("object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json))throw new tD(r_(e),0);try{r=await e.json()}catch(t){if(rk.includes(e.status))throw new tD(e.statusText||`HTTP ${e.status}`,e.status);throw new tx(r_(t),t)}if(rk.includes(e.status))throw new tD(r_(r),e.status);let i=function(e){let t=e.headers.get(tk);if(!t||!t.match(rf))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=tS["2024-01-01"].timestamp&&"object"==typeof r&&r&&"string"==typeof r.code?s=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(s=r.error_code),s){if("weak_password"===s)throw new tH(r_(r),e.status,(null==(t=r.weak_password)?void 0:t.reasons)||[]);else if("session_not_found"===s)throw new tP}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>
11e&&"string"==typeof t,!0))throw new tH(r_(r),e.status,r.weak_password.reasons);throw new tO(r_(r),e.status||500,s)}async function rE(e,t,r,s){var i;let n=Object.assign({},null==s?void 0:s.headers);n[tk]||(n[tk]=tS["2024-01-01"].name),(null==s?void 0:s.jwt)&&(n.Authorization=`Bearer ${s.jwt}`);let a=null!=(i=null==s?void 0:s.query)?i:{};(null==s?void 0:s.redirectTo)&&(a.redirect_to=s.redirectTo);let o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await rT(e,t,r+o,{headers:n,noResolveJson:null==s?void 0:s.noResolveJson},{},null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(l):{data:Object.assign({},l),error:null}}async function rT(e,t,r,s,i,n){let a,o,l=(o={method:t,headers:(null==s?void 0:s.headers)||{}},"GET"===t?o:(o.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==s?void 0:s.headers),o.body=JSON.stringify(n),Object.assign(Object.assign({},o),i)));try{a=await e(r,Object.assign({},l))}catch(e){throw new tD(r_(e),0)}if(a.ok||await rS(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await rS(e)}}function rA(e){var t,r;let s=null;return(r=e).access_token&&r.refresh_token&&r.expires_in&&(s=Object.assign({},e),e.expires_at||(s.expires_at=tZ(e.expires_in))),{data:{session:s,user:null!=(t=e.user)?t:"string"==typeof(null==e?void 0:e.id)?e:null},error:null}}function rR(e){let t=rA(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function rO(e){var t;return{data:{user:null!=(t=e.user)?t:e},error:null}}function rC(e){return{data:e,error:null}}function rx(e){let{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n}=e;return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n},user:Object.assign({},T(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]))},error:null}}function rj(e){return e}let rP=["global","local","others"];class rI{constructor({url:e="",headers:t={},fetch:r,experimental:s}){this.url=e,this.headers=t,this.fetch=t6(r),this.experimental=null!=s?s:{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,t=rP[0]){if(0>rP.indexOf(t))throw Error(`@supabase/auth-js: Parameter scope must be one of ${rP.join(", ")}`);try{return await rE(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tR(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await rE(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:rO})}catch(e){if(tR(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,r=T(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=null==r?void 0:r.newEmail,delete s.newEmail),await rE(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:rx,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(tR(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await rE(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:rO})}catch(e){if(tR(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,i,n,a,o;try{let l={nextPage:null,lastPage:0,total:0},h=await rE(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!=(r=null==(t=null==e?void 0:e.page)?void 0:t.toString())?r:"",per_page:null!=(i=null==(s=null==e?void 0:e.perPage)?void 0:s.toString())?i:""},xform:rj});if(h.error)throw h.error;let u=await h.json(),c=null!=(n=h.headers.get("x-total-count"))?n:0,d=null!=(o=null==(a=h.headers.get("link"))?void 0:a.split(","))?o:[];return d.length>
110&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(c)),{data:Object.assign(Object.assign({},u),l),error:null}}catch(e){if(tR(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){rm(e);try{return await rE(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:rO})}catch(e){if(tR(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){rm(e);try{return await rE(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:rO})}catch(e){if(tR(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){rm(e);try{return await rE(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:rO})}catch(e){if(tR(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){rm(e.userId);try{let{data:t,error:r}=await rE(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(tR(e))return{data:null,error:e};throw e}}async _deleteFactor(e){rm(e.userId),rm(e.id);try{return{data:await rE(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(tR(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,s,i,n,a,o;try{let l={nextPage:null,lastPage:0,total:0},h=await rE(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!=(r=null==(t=null==e?void 0:e.page)?void 0:t.toString())?r:"",per_page:null!=(i=null==(s=null==e?void 0:e.perPage)?void 0:s.toString())?i:""},xform:rj});if(h.error)throw h.error;let u=await h.json(),c=null!=(n=h.headers.get("x-total-count"))?n:0,d=null!=(o=null==(a=h.headers.get("link"))?void 0:a.split(","))?o:[];return d.length>0&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(c)),{data:Object.assign(Object.assign({},u),l),error:null}}catch(e){if(tR(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await rE(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tR(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await rE(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tR(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await rE(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tR(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await rE(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tR(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await rE(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tR(e))return{data:null,error:e};throw e}}async _listCustomProviders(e){try{let t={};return(null==e?void 0:e.type)&&(t.type=e.type),await rE(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:e=>{var t;return{data:{providers:null!=(t=null==e?void 0:e.providers)?t:[]},error:null}}})}catch(e){if(tR(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await rE(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tR(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await rE(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tR(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await rE(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tR(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await rE(this.fetch,"DELET
11E",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tR(e))return{data:null,error:e};throw e}}async _adminListPasskeys(e){ry(this.experimental),rm(e.userId);try{return await rE(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(tR(e))return{data:null,error:e};throw e}}async _adminDeletePasskey(e){ry(this.experimental),rm(e.userId),rm(e.passkeyId);try{return await rE(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(tR(e))return{data:null,error:e};throw e}}}function r$(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}globalThis&&t2()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class rN extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}function rU(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}class rL extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!=(i=null!=s?s:r instanceof Error?r.name:void 0)?i:"Unknown Error",this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class rB extends rL{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}let rD=new class{createNewAbortSignal(){if(this.controller){let e=Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function rq(e){if(!e)throw Error("Credential creation options are required");if("u">typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:r,excludeCredentials:s}=e,i=T(e,["challenge","user","excludeCredentials"]),n=tX(t).buffer,a=Object.assign(Object.assign({},r),{id:tX(r.id).buffer}),o=Object.assign(Object.assign({},i),{challenge:n,user:a});if(s&&s.length>0){o.excludeCredentials=Array(s.length);for(let e=0;e<s.length;e++){let t=s[e];o.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:tX(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function rM(e){if(!e)throw Error("Credential request options are required");if("u">typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:r}=e,s=T(e,["challenge","allowCredentials"]),i=tX(t).buffer,n=Object.assign(Object.assign({},s),{challenge:i});if(r&&r.length>0){n.allowCredentials=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e];n.allowCredentials[e]=Object.assign(Object.assign({},t),{id:tX(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return n}function rF(e){var t;return"toJSON"in e&&"function"==typeof e.toJSON?e.toJSON():{id:e.id,rawId:e.id,response:{attestationObject:tQ(new Uint8Array(e.response.attestationObject)),clientDataJSON:tQ(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!=(t=e.authenticatorAttachment)?t:void 0}}function rH(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();let r=e.getClientExtensionResults(),s=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:tQ(new Uint8Array(s.authenticatorData)),clientDataJSON:tQ(new Uint8Array(s.clientDataJSON)),signature:tQ(new Uint8Array(s.signature)),userHandle:s.userHandle?tQ(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!=(t=e.authenticatorAttachment)?t:void 0}}function rW(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function rK(){var e,t;return!!(t0()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null==(e=null==navigator?void 0:navigator.credentials)?void 0:e.create)&&"function"==typeof(null==(t=null==navigator?void 0:navigator.credentials)?void 0:t.get))}async function rz(e){try{let t=await navigator.credentials.create(e);if(!t)return{data:null,error:new rB("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new rB("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function({error:e,options:t}){var r,s,i;let{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new rL({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if((null==(r=n.authenticatorSelection)?void 0:r.requireResidentKey)===!0)return new rL({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});else if("conditional"===t.mediation&&(null==(s=n.authenticatorSelection)?void 0:s.userVerification)==="required")return new rL({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});else if((null==(i=n.authenticatorSelection)?void 0:i.userVerification)==="required")return new rL({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else if("InvalidStateError"===e.name)return new rL({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});else if("NotAllowedError"===e.name)return new rL({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if("NotSupportedError"===e.name)return new rL(0===n.pubKeyCredParams.filter(e=>"public-key"===e.type).length?{message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}:{message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});else if("SecurityError"===e.name){let t=window.location.hostname;if(!rW(t))return new rL({message:`${window.location.hostname}
11 is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new rL({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new rL({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new rL({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e});return new rL({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}({error:t,options:e})}}}async function rJ(e){try{let t=await navigator.credentials.get(e);if(!t)return{data:null,error:new rB("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new rB("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new rL({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("NotAllowedError"===e.name)return new rL({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if("SecurityError"===e.name){let t=window.location.hostname;if(!rW(t))return new rL({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new rL({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new rL({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e});return new rL({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}({error:t,options:e})}}}let rG={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},rV={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function rY(...e){let t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),s={};for(let i of e)if(i)for(let e in i){let n=i[e];if(void 0!==n)if(Array.isArray(n))s[e]=n;else if(r(n))s[e]=n;else if(t(n)){let r=s[e];t(r)?s[e]=rY(r,n):s[e]=rY(n)}else s[e]=n}return s}class rX{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){var n,a,o,l,h;try{let{data:u,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!u)return{data:null,error:c};let d=null!=s?s:rD.createNewAbortSignal();if("create"===u.webauthn.type){let{user:e}=u.webauthn.credential_options.publicKey;if(!e.name)if(r)e.name=`${e.id}:${r}`;else{let t=(await this.client.getUser()).data.user,r=(null==(n=null==t?void 0:t.user_metadata)?void 0:n.name)||(null==t?void 0:t.email)||(null==t?void 0:t.id)||"User";e.name=`${e.id}:${r}`}e.displayName||(e.displayName=e.name)}switch(u.webauthn.type){case"create":{let t=(a=u.webauthn.credential_options.publicKey,o=null==i?void 0:i.create,rY(rG,a,o||{})),{data:r,error:s}=await rz({publicKey:t,signal:d});if(r)return{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:r}},error:null};return{data:null,error:s}}case"request":{let t=(l=u.webauthn.credential_options.publicKey,h=null==i?void 0:i.request,rY(rV,l,h||{})),{data:r,error:s}=await rJ(Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:t,signal:d}));if(r)return{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:r}},error:null};return{data:null,error:s}}}}catch(e){if(tR(e))return{data:null,error:e};return{data:null,error:new tx("Unexpected error in challenge",e)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t="u">typeof window?window.location.hostname:void 0,rpOrigins:r="u">typeof window?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new tA("rpId is required for WebAuthn authentication")};try{if(!rK())return{data:null,error:new tx("Browser does not support WebAuthn",null)};let{data:n,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!n)return{data:null,error:a};let{webauthn:o}=n;return this._verify({factorId:e,challengeId:n.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:r,credential_response:o.credential_response}})}catch(e){if(tR(e))return{data:null,error:e};return{data:null,error:new tx("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t="u">typeof window?window.location.hostname:void 0,rpOrigins:r="u">typeof window?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new tA("rpId is required for WebAuthn registration")};try{if(!rK())return{data:null,error:new tx("Browser does not support WebAuthn",null)};let{data:n,error:a}=await this._enroll({friendlyName:e});if(!n)return await this.client.mfa.listFactors().then(t=>{var r;return null==(r=t.data)?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"===t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:a};let{data:o,error:l}=await this._challenge({factorId:n.id,friendlyName:n.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});if(!o)return{data:null,error:l};return this._verify({factorId:n.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:r,type:o.webauthn.type,credential_response:o.webauthn.credential_response}})}catch(e){if(tR(e))return{data:null,error:e};return{data:null,error:new tx("Unexpected error in register",e)}}}}if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"u">typeof self&&(self.globalThis=self)}let rQ={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:t_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},rZ={},r0=!1;class r1{get jwks(){var e,t;return null!=(t=null==(e=rZ[this.storageKey])?void 0:e.jwks)?t:{keys:[]}}set jwks(e){rZ[this.storageKey]=Object.assign(Object.assign({},rZ[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!=(t=null==(e=rZ[this.storageKey])?void 0:e.cachedAt)?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){rZ[this.storageKey]=Object.assign(Object.assign({},rZ[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},rQ),e);if(this.storageKey=i.storageKey,this.instanceID=null!=(t=r1.nextInstanceID[this.storageKey])?t:0,r1.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,"function"==typeof i.debug&&(this.logger=i.debug),this.instanceID>0&&t0()){const e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=null!=(r=i.experimental)?r:{},this.admin=new rI({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=t6(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,null!=i.lock&&(this.lock=i.lock,r0||(r0=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),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 rX(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(this)}}
11,this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:t2()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=r$(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=r$(this.memoryStorage)),t0()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null==(s=this.broadcastChannel)||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),("TOKEN_REFRESHED"===e.data.event||"SIGNED_IN"===e.data.event)&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug("#broadcastChannel","error",e)}})}i.skipAutoInitialize||this.initialize().catch(e=>{this._debug("#initialize()","error",e)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${tv}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let t=await this.initializePromise,r=null!=(e=this._pendingInitNotifications)?e:[];for(let e of(this._pendingInitNotifications=null,r))await this._notifyAllSubscribers(e.event,e.session,e.broadcast);return t}async _initialize(){var e;try{let t={},r="none";if(t0()&&(t=t5(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),t0()&&this.detectSessionInUrl&&"none"!==r){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){(this._debug("#_initialize()","error detecting session from URL",i),tR(i)&&"AuthImplicitGrantRedirectError"===i.name)&&(null==(e=i.details)||e.code);return{error:i}}let{session:n,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",n,"redirect type",a),await this._saveSession(n),setTimeout(async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){if(tR(e))return this._returnResult({error:e});return this._returnResult({error:new tx("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let{data:i,error:n}=await rE(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!=(r=null==(t=null==e?void 0:e.options)?void 0:t.data)?r:{},gotrue_meta_security:{captcha_token:null==(s=null==e?void 0:e.options)?void 0:s.captchaToken}},xform:rA});if(n||!i)return this._returnResult({data:{user:null,session:null},error:n});let a=i.session,o=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:o,session:a},error:null})}catch(e){if(tR(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,s;let i=null;try{let n;if("email"in e){let{email:r,password:s,options:a}=e,o=null,l=null;"pkce"===this.flowType&&([o,l,i]=await this._getCodeChallengeAndMethod()),n=await rE(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(null==a?void 0:a.emailRedirectTo,i),body:{email:r,password:s,data:null!=(t=null==a?void 0:a.data)?t:{},gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}
11,code_challenge:o,code_challenge_method:l},xform:rA})}else if("phone"in e){let{phone:t,password:i,options:a}=e;n=await rE(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:i,data:null!=(r=null==a?void 0:a.data)?r:{},channel:null!=(s=null==a?void 0:a.channel)?s:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:rA})}else throw new tN("You must provide either an email or phone number and a password");let{data:a,error:o}=n;if(o||!a)return await rc(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:o});let l=a.session,h=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:h,session:l},error:null})}catch(e){if(await rc(this.storage,this.storageKey,i),tR(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){let{email:r,password:s,options:i}=e;t=await rE(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:rR})}else if("phone"in e){let{phone:r,password:s,options:i}=e;t=await rE(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:rR})}else throw new tN("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let e=new t$;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(e){if(tR(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:null==(t=e.options)?void 0:t.redirectTo,scopes:null==(r=e.options)?void 0:r.scopes,queryParams:null==(s=e.options)?void 0:s.queryParams,skipBrowserRedirect:null==(i=e.options)?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return(await this.initializePromise,null!=this.lock)?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t)):this._exchangeCodeForSession(e,t)}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,n,a,o,l,h,u,c,d;let p,f;if("message"in e)p=e.message,f=e.signature;else{let u,{chain:c,wallet:g,statement:m,options:y}=e;if(t0())if("object"==typeof g)u=g;else{let e=window;if("ethereum"in e&&"object"==typeof e.ethereum&&"request"in e.ethereum&&"function"==typeof e.ethereum.request)u=e.ethereum;else throw Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if("object"!=typeof g||!(null==y?void 0:y.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");u=g}let b=new URL(null!=(t=null==y?void 0:y.url)?t:window.location.href),w=await u.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!w||0===w.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let v=rU(w[0]),_=null==(r=null==y?void 0:y.signInWithEthereum)?void 0:r.chainId;_||(_=parseInt(await u.request({method:"eth_chainId"}),16)),p=function(e){var t;let{chainId:r,domain:s,expirationTime:i,issuedAt:n=new Date,nonce:a,notBefore:o,requestId:l,resources:h,scheme:u,uri:c,version:d}=e;if(!Number.isInteger(r))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!c)throw Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null==(t=e.statement)?void 0:t.includes("\n"))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);let p=rU(e.address),f=u?`${u}://${s}`:s,g=e.statement?`${e.statement} 12`:"",m=`${f} wants you to sign in with your Ethereum account: 13${p} 14 15${g}`,y=`URI: ${c} 16Version: ${d}
17Chain ID: ${r}${a?` 18Nonce: ${a}`:""} 19Issued At: ${n.toISOString()}`;if(i&&(y+=` 20Expiration Time: ${i.toISOString()}`),o&&(y+=` 21Not Before: ${o.toISOString()}`),l&&(y+=` 22Request ID: ${l}`),h){let e="\nResources:";for(let t of h){if(!t||"string"!=typeof t)throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=` 23- ${t}`}y+=e}return`${m} 24${y}`}({domain:b.host,address:v,statement:m,uri:b.href,version:"1",chainId:_,nonce:null==(s=null==y?void 0:y.signInWithEthereum)?void 0:s.nonce,issuedAt:null!=(n=null==(i=null==y?void 0:y.signInWithEthereum)?void 0:i.issuedAt)?n:new Date,expirationTime:null==(a=null==y?void 0:y.signInWithEthereum)?void 0:a.expirationTime,notBefore:null==(o=null==y?void 0:y.signInWithEthereum)?void 0:o.notBefore,requestId:null==(l=null==y?void 0:y.signInWithEthereum)?void 0:l.requestId,resources:null==(h=null==y?void 0:y.signInWithEthereum)?void 0:h.resources}),f=await u.request({method:"personal_sign",params:[(d=p,"0x"+Array.from(new TextEncoder().encode(d),e=>e.toString(16).padStart(2,"0")).join("")),v]})}try{let{data:t,error:r}=await rE(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:f},(null==(u=e.options)?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null==(c=e.options)?void 0:c.captchaToken}}:null),xform:rA});if(r)throw r;if(!t||!t.session||!t.user){let e=new t$;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(tR(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,r,s,i,n,a,o,l,h,u,c,d;let p,f;if("message"in e)p=e.message,f=e.signature;else{let c,{chain:d,wallet:g,statement:m,options:y}=e;if(t0())if("object"==typeof g)c=g;else{let e=window;if("solana"in e&&"object"==typeof e.solana&&("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))c=e.solana;else throw Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if("object"!=typeof g||!(null==y?void 0:y.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");c=g}let b=new URL(null!=(t=null==y?void 0:y.url)?t:window.location.href);if("signIn"in c&&c.signIn){let e,t=await c.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},null==y?void 0:y.signInWithSolana),{version:"1",domain:b.host,uri:b.href}),m?{statement:m}:null));if(Array.isArray(t)&&t[0]&&"object"==typeof t[0])e=t[0];else if(t&&"object"==typeof t&&"signedMessage"in t&&"signature"in t)e=t;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in e&&"signature"in e&&("string"==typeof e.signedMessage||e.signedMessage instanceof Uint8Array)&&e.signature instanceof Uint8Array)p="string"==typeof e.signedMessage?e.signedMessage:new TextDecoder().decode(e.signedMessage),f=e.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in c)||"function"!=typeof c.signMessage||!("publicKey"in c)||"object"!=typeof c||!c.publicKey||!("toBase58"in c.publicKey)||"function"!=typeof c.publicKey.toBase58)throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${b.host} wants you to sign in with your Solana account:`,c.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1",`URI: ${b.href}`,`Issued At: ${null!=(s=null==(r=null==y?void 0:y.signInWithSolana)?void 0:r.issuedAt)?s:new Date().toISOString()}`,...(null==(i=null==y?void 0:y.signInWithSolana)?void 0:i.notBefore)?[`Not Before: ${y.signInWithSolana.notBefore}`]:[],...(null==(n=null==y?void 0:y.signInWithSolana)?void 0:n.expirationTime)?[`Expiration Time: ${y.signInWithSolana.expirationTime}`]:[],...(null==(a=null==y?void 0:y.signInWithSolana)?void 0:a.chainId)?[`Chain ID: ${y.signInWithSolana.chainId}`]:[],...(null==(o=null==y?void 0:y.signInWithSolana)?void 0:o.nonce)?[`Nonce: ${y.signInWithSolana.nonce}`]:[],...(null==(l=null==y?void 0:y.signInWithSolana)?void 0:l.requestId)?[`Request ID: ${y.signInWithSolana.requestId}`]:[],...(null==(u=null==(h=null==y?void 0:y.signInWithSolana)?void 0:h.resources)?void 0:u.length)?["Resources",...y.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");let e=await c.signMessage(new TextEncoder().encode(p),"utf8");if(!e||!(e instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");f=e}}try{let{data:t,error:r}=await rE(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:tQ(f)},(null==(c=e.options)?void 0:c.captchaToken)?{gotrue_meta_security:{captcha_token:null==(d=e.options)?void 0:d.captchaToken}}:null),xform:rA});if(r)throw r;if(!t||!t.session||!t.user){let e=new t$;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(tR(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e,t){let r=(null==t?void 0:t.flowId)!=null,s=r?rn(null==t?void 0:t.flowId):t0()?rn(t5(window.location.href)[tT]):null;r&&!s&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",null==t?void 0:t.flowId);let{verifier:i,flowId:n}=r&&!s?{verifier:null,flowId:null}:await ru(this.storage,this.storageKey,s),[a,o]=(null!=i?i:"").split("/");try{if(!a&&"pkce"===this.flowType)throw new tB;let{data:t,error:r}=await rE(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:a},xform:rA});if(await rc(this.storage,this.storageKey,n),r)throw r;if(!t||!t.session||!t.user){let e=new t$;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("recovery"===o?"PASSWORD_RECOVERY":"SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=o?o:null}),error:r})}catch(e){if(await rc(this.storage,this.storageKey,n),tR(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:n}=e,{data:a,error:o}=await rE(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:n,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:rA});if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!a||!a.session||!a.user){let e=new t$;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:a,error:o})}catch(e){if(tR(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,s,i,n;let a=null;try{if("email"in e){let{email:s,options:i}=e,n=null,o=null;"pkce"===this.flowType&&([n,o,a]=await this._getCodeChallengeAndMethod());let{error:l}=await rE(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!=(t=null==i?void 0:i.data)?t:{},create_user:null==(r=null==i?void 0:i.shouldCreateUser)||r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:n,code_challenge_method:o},redirectTo:this._maybeAppendFlowIdToRedirect(null==i?void 0:i.emailRedirectTo,a)});return this._returnResult({data:{user:null,session:null},error:l})}if("phone"in e){let{phone:t,options:r}=e,{data:a,error:o}=await rE(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!=(s=null==r?void 0:r.data)?s:{},create_user:null==(i=null==r?void 0:r.shouldCreateUser)||i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!=(n=null==r?void 0:r.channel)?n:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o})}throw new tN("You must provide either an email or phone number.")}catch(e){if(await rc(this.storage,this.storageKey,a),tR(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=null==(t=e.options)?void 0:t.redirectTo,i=null==(r=e.options)?void 0:r.captchaToken);let{data:n,error:a}=await rE(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:rA});if(a)throw a;if(!n)throw Error("An error occurred on token verification.");let o=n.session,l=n.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(e){if(tR(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,s,i;let n=null;try{let a=null,o=null;"pkce"===this.flowType&&([a,o,n]=await this._getCodeChallengeAndMethod());let l=await rE(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect(null==(t=e.options)?void 0:t.redirectTo,n)}),(null==(r=null==e?void 0:e.options)?void 0:r.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:o}),headers:this.headers,xform:rC});return(null==(s=l.data)?void 0:s.url)&&t0()&&!(null==(i=e.options)?void 0:i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await rc(this.storage,this.storageKey,n),tR(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new tP;let{error:s}=await rE(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(tR(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let r=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:n}=e,a=null,o=null;"pkce"===this.flowType&&([a,o,t]=await this._getCodeChallengeAndMethod());let{error:l}=await rE(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:a,code_challenge_method:o},redirectTo:this._maybeAppendFlowIdToRedirect(null==n?void 0:n.emailRedirectTo,t)});return l&&await rc(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:l})}if("phone"in e){let{phone:t,type:s,options:i}=e,{data:n,error:a}=await rE(this.fetch,"POST",r,{headers:this.headers,body:{phone:t,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==n?void 0:n.message_id},error:a})}throw new tN("You must provide either an email or phone number and a type")}catch(e){if(await rc(this.storage,this.storageKey,t),tR(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),null==this.lock||this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let t=null,r=await t3(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),null!==r&&(this._isValidSession(r)?t=r:(this._debug("#getSession()","session from storage is not val
24id"),await this._removeSession())),!t)return{data:{session:null},error:null};let s=!!t.expires_at&&1e3*t.expires_at-Date.now()<9e4;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",t.expires_at),!s){if(this.userStorage){let e=await t3(this.userStorage,this.storageKey+"-user");(null==e?void 0:e.user)?t.user=e.user:t.user=rw()}if(this.storage.isServer&&t.user&&!t.user.__isUserNotAvailableProxy){var e;let r={value:this.suppressGetSessionWarning};t.user=(e=t.user,new Proxy(e,{get:(e,t,s)=>{if("__isInsecureUserWarningProxy"===t)return!0;if("symbol"==typeof t){let r=t.toString();if("Symbol(Symbol.toPrimitive)"===r||"Symbol(Symbol.toStringTag)"===r||"Symbol(util.inspect.custom)"===r||"Symbol(nodejs.util.inspect.custom)"===r)return Reflect.get(e,t,s)}return r.value||"string"!=typeof t||(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),r.value=!0),Reflect.get(e,t,s)}})),r.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:t},error:null}}let{data:i,error:n}=await this._callRefreshToken(t.refresh_token);if(n){if(t.expires_at&&1e3*t.expires_at>Date.now()){let e=await t3(this.storage,this.storageKey);if(e&&e.refresh_token===t.refresh_token)return this._returnResult({data:{session:t},error:null})}return this._returnResult({data:{session:null},error:n})}return this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){let t;return e?await this._getUser(e):(await this.initializePromise,(t=null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):await this._getUser()).data.user&&(this.suppressGetSessionWarning=!0),t)}async _getUser(e){try{if(e)return await rE(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:rO});return await this._useSession(async e=>{var t,r,s;let{data:i,error:n}=e;if(n)throw n;return(null==(t=i.session)?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await rE(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!=(s=null==(r=i.session)?void 0:r.access_token)?s:void 0,xform:rO}):{data:{user:null},error:new tP}})}catch(e){if(tR(e))return tI(e)&&await this._removeSession(),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t)):await this._updateUser(e,t)}async _updateUser(e,t={}){let r=null;try{return await this._useSession(async s=>{let{data:i,error:n}=s;if(n)throw n;if(!i.session)throw new tP;let a=i.session,o=null,l=null;"pkce"===this.flowType&&null!=e.email&&([o,l,r]=await this._getCodeChallengeAndMethod());let{data:h,error:u}=await rE(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(null==t?void 0:t.emailRedirectTo,r),body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:l}),jwt:a.access_token,xform:rO});if(u)throw u;return a.user=h.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(e){if(await rc(this.storage,this.storageKey,r),tR(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new tP;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:n}=t7(e.access_token);if(n.exp&&(s=(r=n.exp)<=t),s){let{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:s,error:n}=await this._getUser(e.access_token);if(n)return this._returnResult({data:{user:null,session:null},error:n});i={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(e){if(tR(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:s,error:i}=t;if(i)throw i;e=null!=(r=s.session)?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new tP;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(tR(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){var r;try{if(!t0())throw new tU("No browser detected.");
24if(e.error||e.error_description||e.error_code)throw new tU(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new tL("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new tU("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new tL("No code detected.");let{data:t,error:s}=await this._exchangeCodeForSession(e.code,{flowId:e[tT]});if(s)throw s;let i=new URL(window.location.href);return i.searchParams.delete("code"),i.searchParams.delete(tT),window.history.replaceState(window.history.state,"",i.toString()),{data:{session:t.session,redirectType:null!=(r=t.redirectType)?r:null},error:null}}let{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:a,expires_in:o,expires_at:l,token_type:h}=e;if(!n||!o||!a||!h)throw new tU("No session defined in URL");let u=Math.round(Date.now()/1e3),c=parseInt(o),d=u+c;l&&(d=parseInt(l));let p=d-u;1e3*p<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${c}s`);let f=d-c;u-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,d,u):u-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,d,u);let{data:g,error:m}=await this._getUser(n);if(m)throw m;let y={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:c,expires_at:d,refresh_token:a,token_type:h,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(e){if(tR(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=rn(e[tT]);return!!(t&&await t3(this.storage,ra(this.storageKey,t)))||!!await t3(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:"global"}){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let s=async()=>{await this._removeSession()},{data:i,error:n}=t;if(n&&!tI(n))return this._returnResult({error:n});let a=null==(r=i.session)?void 0:r.access_token;if(a){let{error:t}=await this.admin.signOut(a,e);if(t&&!(tC(t)&&(404===t.status||401===t.status||403===t.status)||tI(t)))return"others"!==e&&await s(),this._returnResult({error:t})}return"others"!==e&&await s(),this._returnResult({error:null})})}onAuthStateChange(e){let t=Symbol("auth-callback"),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)}):await this._emitInitialSession(t)})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:s},error:i}=t;if(i)throw i;await (null==(r=this.stateChangeEmitters.get(e))?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(t){if(await (null==(s=this.stateChangeEmitters.get(e))?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),tF(t))return;tI(t)||tq(t)||tC(t)&&("refresh_token_not_found"===t.code||"refresh_token_already_used"===t.code||"session_expired"===t.code)?console.warn(t):console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null,i=null;"pkce"===this.flowType&&([r,s,i]=await this._getCodeChallengeAndMethod(!0));try{return await rE(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,i)})}catch(e){if(await rc(this.storage,this.storageKey,i),tR(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!=(e=t.user.identities)?e:[]},error:null})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;let r=null;try{let{data:s,error:i}=await this._useSession(async t=>{var s,i,n,a,o;let{data:l,error:h}=t;if(h)throw h;let{url:u,flowId:c}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null==(s=e.options)?void 0:s.redirectTo,scopes:null==(i=e.options)?void 0:i.scopes,queryParams:null==(n=e.options)?void 0:n.queryParams,skipBrowserRedirect:!0});return r=c,await rE(this.fetch,"GET",u,{headers:this.headers,jwt:null!=(o=null==(a=l.session)?void 0:a.access_token)?o:void 0})});if(i)throw i;return!t0()||(null==(t=e.options)?void 0:t.skipBrowserRedirect)||window.location.assign(null==s?void 0:s.url),this._returnResult({data:{provider:e.provider,url:null==s?void 0:s.url,flowId:r},error:null})}catch(t){if(tR(t))return this._returnResult({data:{provider:e.provider,url:null,flowId:r},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:n,provider:a,token:o,access_token:l,nonce:h}=e,{data:u,error:c}=await rE(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!=(r=null==i?void 0:i.access_token)?r:void 0,body:{provider:a,id_token:o,access_token:l,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:rA});if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!u||!u.session||!u.user)return this._returnResult({data:{user:null,session:null},error:new t$});return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:c})}catch(e){if(await rc(this.storage,this.storageKey,null),tR(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:n}=t;if(n)throw n;
24return await rE(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!=(s=null==(r=i.session)?void 0:r.access_token)?s:void 0})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t="#_refreshAccessToken()";this._debug(t,"begin");try{var r,s;let i=Date.now();return await (r=async r=>(r>0&&await re(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await rE(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:rA})),s=(e,t)=>{let r=200*Math.pow(2,e);return t&&tq(t)&&Date.now()+r-i<3e4},new Promise((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{let t=await r(i);if(!s(i,null))return void e(t)}catch(e){if(!s(i,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),tR(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let{url:r,flowId:s}=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),t0()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r,flowId:s},error:null}}async _recoverAndRefresh(){var e,t;let r="#_recoverAndRefresh()";this._debug(r,"begin");try{let s=await t3(this.storage,this.storageKey);if(s&&this.userStorage){let t=await t3(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!t&&(t={user:s.user},await t8(this.userStorage,this.storageKey+"-user",t)),s.user=null!=(e=null==t?void 0:t.user)?e:rw()}else if(s&&!s.user&&!s.user){let e=await t3(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await t4(this.storage,this.storageKey+"-user"),await t8(this.storage,this.storageKey,s)):s.user=rw()}if(this._debug(r,"session from storage",s),!this._isValidSession(s)){this._debug(r,"session is not valid"),null!==s&&await this._removeSession();return}let i=(null!=(t=s.expires_at)?t:1/0)*1e3-Date.now()<9e4;if(this._debug(r,`session has${i?"":" not"} expired with margin of 90000s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:e}=await this._callRefreshToken(s.refresh_token);e&&(tF(e)?this._debug(r,"refresh discarded by commit guard",e):this._debug(r,"refresh failed",e))}}else if(s.user&&!0===s.user.__isUserNotAvailableProxy)try{let{data:e,error:t}=await this._getUser(s.access_token);!t&&(null==e?void 0:e.user)?(s.user=e.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){this._debug(r,"error",e),tq(e)?console.warn(e):console.error(e);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new tP;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===e&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning cached failure (cooldown active)"),this.lastRefreshFailure.result;let s="#_callRefreshToken()";this._debug(s,"begin");try{this.refreshingDeferred=new t9,this.refreshingDeferred.promise.then(void 0,()=>{});let t=await t3(this.storage,this.storageKey),{data:r,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!r.session)throw new tP;let n=await t3(this.storage,this.storageKey);if(null!==t&&(null===n||n.refresh_token!==t.refresh_token)){this._debug(s,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:n?"replaced":"cleared"});let e={data:null,error:new tM};return this.refreshingDeferred.resolve(e),e}let a=this._sessionRemovalEpoch;if(await this._saveSession(r.session),this._sessionRemovalEpoch!==a){this._debug(s,"commit guard (post-save): _removeSession ran during _saveSession, und
24oing write"),await t4(this.storage,this.storageKey),this.userStorage&&await t4(this.userStorage,this.storageKey+"-user");let e={data:null,error:new tM};return this.refreshingDeferred.resolve(e),e}await this._notifyAllSubscribers("TOKEN_REFRESHED",r.session);let o={data:r.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(o),o}catch(i){if(this._debug(s,"error",i),tR(i)){let r={data:null,error:i};if(!tq(i)){let e=await t3(this.storage,this.storageKey);(null==e?void 0:e.expires_at)&&1e3*e.expires_at>Date.now()?this._debug(s,"proactive refresh failed, access token still valid â preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:r,expiresAt:Date.now()+6e4},null==(t=this.refreshingDeferred)||t.resolve(r),r}throw null==(r=this.refreshingDeferred)||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){if(null!==this._pendingInitNotifications&&r)return void this._pendingInitNotifications.push({event:e,session:t,broadcast:r});let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){s.push(e)}});if(await Promise.all(i),s.length>0){for(let e=0;e<s.length;e+=1)console.error(s[e]);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;let t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await t8(this.userStorage,this.storageKey+"-user",{user:t.user});let e=Object.assign({},t);delete e.user;let s=rv(e);await t8(this.storage,this.storageKey,s)}else{let e=rv(t);await t8(this.storage,this.storageKey,e)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await t4(this.storage,this.storageKey),await rd(this.storage,this.storageKey),await t4(this.storage,this.storageKey+"-user"),this.userStorage&&await t4(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&t0()&&(null==window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),3e4);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),null==(e=this.broadcastChannel)||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),null!=this.lock){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let s=Math.floor((1e3*r.expires_at-e)/3e4);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof rN)this._debug("auto refresh token tick lock not available");else throw e}return}if(null!==this.refreshingDeferred)return void this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let s=Math.floor((1e3*r.expires_at-e)/3e4);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!t0()||!(null==window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,null!=this.lock)await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"!==document.visibilityState?this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting"):await this._recoverAndRefresh()});else{if("visible"!==document.visibilityState)return void this._debug(t,"visibilityState is no longer visible, skipping recovery");await this._recoverAndRefresh()}}else"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=null==r?void 0:r.redirectTo,i=null,n=null,a=null;"pkce"===this.flowType&&([i,n,a]=await this._getCodeChallengeAndMethod(),s=this._maybeAppendFlowIdToRedirect(s,a));let o=[`provider=${encodeURIComponent(t)}`];if(s&&o.push(`redirect_to=${encodeURIComponent(s)}`),(null==r?void 0:r.scopes)&&o.push(`scopes=${encodeURIComponent(r.scopes)}`),null!=i&&null!=n){let e=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(n)}`});o.push(e.toString())}if(null==r?void 0:r.queryParams){let e=new URLSearchParams(r.queryParams);o.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&o.push(`skip_http_redirect=${r.skipBrowserRedirect}`),{url:`${e}?${o.join("&")}`,flowId:a}}_maybeAppendFlowIdToRedirect(e,t){return e&&t&&this.experimental.appendPkceFlowIdToRedirects?function(e,t){let r=e.indexOf("#"),s=-1===r?e:e.slice(0,r),i=-1===r?"":e.slice(r),n=s.indexOf("?");if(-1!==n){let e=s.slice(0,n),t=s.slice(n+1).split("&").filter(e=>""!==e&&e!==tT&&!e.startsWith(`${tT}=`));s=t.length>0?`${e}?${t.join("&")}`:e}let a=s.includes("?")?"&":"?";return`${s}${a}${tT}=${encodeURIComponent(t)}${i}`}(e,t):null!=e?e:void 0}async _getCodeChallengeAndMethod(e=!1){return rp(this.storage,this.storageKey,e,e=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",e))}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}
24):await rE(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:n}=t;if(n)return this._returnResult({data:null,error:n});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:l}=await rE(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:null==(r=null==i?void 0:i.session)?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):("totp"===e.factorType&&"totp"===o.type&&(null==(s=null==o?void 0:o.totp)?void 0:s.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),this._returnResult({data:o,error:null}))})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){let t=async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let n=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?rF(e.webauthn.credential_response):rH(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await rE(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:n,headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:o}))})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}};return null!=this.lock?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challenge(e){let t=async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let n=await rE(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token});if(n.error)return n;let{data:a}=n;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:rq(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:rM(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}};return null!=this.lock?this._acquireLock(this.lockAcquireTimeout,t):t()}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;let{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let r of null!=(e=null==t?void 0:t.factors)?e:[])s.all.push(r),"verified"===r.status&&r.factor_type in s&&Array.isArray(s[r.factor_type])&&s[r.factor_type].push(r);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,r,s,i;if(e)try{let{payload:s}=t7(e),i=null;s.aal&&(i=s.aal);let n=i,{data:{user:a},error:o}=await this.getUser(e);if(o)return this._returnResult({data:null,error:o});(null!=(r=null==(t=null==a?void 0:a.factors)?void 0:t.filter(e=>"verified"===e.status))?r:[]).length>0&&(n="aal2");let l=s.amr||[];return{data:{currentLevel:i,nextLevel:n,currentAuthenticationMethods:l},error:null}}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:n},error:a}
24=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:o}=t7(n.access_token),l=null;o.aal&&(l=o.aal);let h=l;return(null!=(i=null==(s=n.user.factors)?void 0:s.filter(e=>"verified"===e.status))?i:[]).length>0&&(h="aal2"),{data:{currentLevel:l,nextLevel:h,currentAuthenticationMethods:o.amr||[]},error:null}}async _getRecoveryCodesStatus(){rb(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:n}=await rE(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:null==(t=null==r?void 0:r.session)?void 0:t.access_token});return n?this._returnResult({data:null,error:n}):this._returnResult({data:i,error:null})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){rb(this.experimental);try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let{data:n,error:a}=await rE(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:(null==e?void 0:e.friendlyName)?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token});return a?this._returnResult({data:null,error:a}):this._returnResult({data:n,error:null})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _verifyRecoveryCode(e){rb(this.experimental);let t=async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let{data:n,error:a}=await rE(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token});if(a)return this._returnResult({data:null,error:a});let o=Object.assign({expires_at:tZ(n.expires_in)},n);return await this._saveSession(o),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:n,error:null})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}};return null!=this.lock?this._acquireLock(this.lockAcquireTimeout,t):t()}async _regenerateRecoveryCodes(){rb(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:n}=await rE(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:null==(t=null==r?void 0:r.session)?void 0:t.access_token});return n?this._returnResult({data:null,error:n}):this._returnResult({data:i,error:null})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){rb(this.experimental);try{return await this._useSession(async e=>{var t;let{data:r,error:s}=e;if(s)return this._returnResult({data:null,error:s});let{data:i,error:n}=await rE(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:null==(t=null==r?void 0:r.session)?void 0:t.access_token});return n?this._returnResult({data:null,error:n}):this._returnResult({data:i,error:null})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await rE(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new tP})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new tP});let n=await rE(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return n.data&&n.data.redirect_url&&t0()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(n.data.redirect_url),n})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new tP});let n=await rE(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return n.data&&n.data.redirect_url&&t0()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(n.data.redirect_url),n})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await rE(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new tP})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}
24):r?(await rE(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new tP})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;let s=Date.now();if((r=this.jwks.keys.find(t=>t.kid===e))&&this.jwks_cached_at+6e5>s)return r;let{data:i,error:n}=await rE(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(n)throw n;return i.keys&&0!==i.keys.length&&(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(t=>t.kid===e))?r:null}async getClaims(e,t={}){try{let i,n=e;if(!n){let{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});n=e.session.access_token}let{header:a,payload:o,signature:l,raw:{header:h,payload:u}}=t7(n);if(!(null==t?void 0:t.allowExpired))try{var r,s=o.exp;if(!s)throw Error("Missing exp claim");if(s<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}catch(e){throw new tW(e instanceof Error?e.message:"JWT validation failed")}let c=!a.alg||a.alg.startsWith("HS")||!a.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(a.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks);if(!c){let{error:e}=await this.getUser(n);if(e)throw e;return{data:{claims:o,header:a,signature:l},error:null}}let d=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw Error("Invalid alg claim")}}(a.alg),p=await crypto.subtle.importKey("jwk",c,d,!0,["verify"]);if(!await crypto.subtle.verify(d,p,l,(r=`${h}.${u}`,i=[],!function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127)return t(e);if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}(s,t)}}(r,e=>i.push(e)),new Uint8Array(i))))throw new tW("Invalid JWT signature");return{data:{claims:o,header:a,signature:l},error:null}}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async signInWithPasskey(e){var t,r,s;ry(this.experimental);try{if(!rK())return this._returnResult({data:null,error:new tx("Browser does not support WebAuthn",null)});let{data:i,error:n}=await this._startPasskeyAuthentication({options:{captchaToken:null==(t=null==e?void 0:e.options)?void 0:t.captchaToken}});if(n||!i)return this._returnResult({data:null,error:n});let a=rM(i.options),o=null!=(s=null==(r=null==e?void 0:e.options)?void 0:r.signal)?s:rD.createNewAbortSignal(),{data:l,error:h}=await rJ({publicKey:a,signal:o});if(h||!l)return this._returnResult({data:null,error:null!=h?h:new tx("WebAuthn ceremony failed",null)});let u=rH(l);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:u})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async registerPasskey(e){var t,r;ry(this.experimental);try{if(!rK())return this._returnResult({data:null,error:new tx("Browser does not support WebAuthn",null)});let{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});let n=rq(s.options),a=null!=(r=null==(t=null==e?void 0:e.options)?void 0:t.signal)?r:rD.createNewAbortSignal(),{data:o,error:l}=await rz({publicKey:n,signal:a});if(l||!o)return this._returnResult({data:null,error:null!=l?l:new tx("WebAuthn ceremony failed",null)});let h=rF(o);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:h})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyRegistration(){ry(this.experimental);try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new tP});let{data:s,error:i}=await rE(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){ry(this.experimental);try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new tP});let{data:i,error:n}=await rE(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:i,error:null})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyAuthentication(e){var t;ry(this.experimental);try{let{data:r,error:s}=await rE(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:null==(t=null==e?void 0:e.options)?void 0:t.captchaToken}}});if(s)return this._returnResult({data:null,error:s});return this._returnResult({data:r,error:null})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyAuthentication(e){ry(this.experimental);try{let{data:t,error:r}=await rE(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:rA});if(r)return this._returnResult({data:null,error:r});return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:t,error:null})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _listPasskeys(){ry(this.experimental);try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!t)return this._returnResult({data:null,error:new tP});let{data:s,error:i}=await rE(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){ry(this.experimental);try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new tP});let{data:i,error:n}=await rE(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:i,error:null})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}async _deletePasskey(e){ry(this.experimental);try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new tP});let{error:i}
24=await rE(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(e){if(tR(e))return this._returnResult({data:null,error:e});throw e}}}r1.nextInstanceID={};let r2=r1,r5="";if("u">typeof Deno)r5="deno",s=null==(y=Deno.version)?void 0:y.deno;else if("u">typeof document)r5="web";else if("u">typeof navigator&&"ReactNative"===navigator.product)r5="react-native";else{r5="node";let e=globalThis.process;s=null==e||null==(b=e.version)?void 0:b.replace(/^v/,"")}let r6=[`runtime=${r5}`];s&&r6.push(`runtime-version=${s}`);let r8={headers:{"X-Client-Info":`supabase-js/2.116.0; ${r6.join("; ")}`}},r3={schema:"public"},r4={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},r9={},r7={enabled:!1,respectSamplingDecision:!0};function se(e){return(se="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function st(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function sr(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?st(Object(r),!0).forEach(function(t){!function(e,t,r){var s;(s=function(e,t){if("object"!=se(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=se(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==se(s)?s:s+"")in e)?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):st(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}let ss=e=>e.startsWith("sb_publishable_")||e.startsWith("sb_secret_"),si=new Set,sn=(e,t,r,s,i,n)=>{let a=s?(...e)=>s(...e):(...e)=>fetch(...e),o=Headers,l=(null==i?void 0:i.enabled)===!0,h=(null==i?void 0:i.respectSamplingDecision)!==!1,u=l?function(e){let t=[];try{let r=new URL(e);t.push(r.hostname)}catch(e){}return t.push("*.supabase.co","*.supabase.in"),t.push("localhost","127.0.0.1","[::1]"),t}(t):null,c=!((null==n?void 0:n.omitApiKeyAsBearer)&&ss(e));return async(t,s)=>{let i=await r(),n=new o(null==s?void 0:s.headers);if(n.has("apikey")||n.set("apikey",e),!n.has("Authorization")){let t=null!=i?i:c?e:null;t&&n.set("Authorization",`Bearer ${t}`)}if(u){let e=function(e,t,r){let s=globalThis[v];if(!s)return sa||(sa=!0,console.warn("@supabase/supabase-js: tracePropagation is enabled but the tracing runtime is not loaded, so trace headers will not be attached. Add `import '@supabase/supabase-js/tracing'` at your application entry point (requires the OpenTelemetry API package to be installed). The CDN/UMD build does not support trace propagation.")),null;if(!function(e,t){let r;if(!e||!t||0===t.length)return!1;if(e instanceof URL)r=e;else try{r=new URL(e)}catch(e){return!1}for(let e of t)try{if("string"==typeof e){if(function(e,t){if(t===e)return!0;if(t.startsWith("*.")){let r=t.slice(2);if(e.endsWith(r)&&(e===r||e.endsWith("."+r)))return!0}return!1}(r.hostname,e))return!0}else if(e instanceof RegExp){if(e.test(r.hostname))return!0}else if("function"==typeof e&&e(r))return!0}catch(e){continue}return!1}("string"==typeof e||e instanceof URL?e:e.url,t))return null;let i=s();if(!i||!i.traceparent){var n;if((null==i||null==(n=i.carrierKeys)?void 0:n.length)&&!so){so=!0;let e=i.carrierKeys.includes("sentry-trace")?" Sentry detected: set `propagateTraceparent: true` in Sentry.init() to emit it.":" Configure your tracing SDK to emit W3C trace context on outgoing requests.";console.warn(`@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its propagator wrote [${i.carrierKeys.join(", ")}] and no W3C traceparent header, so trace headers will not be attached.`+e)}return null}if(r){let e=function(e){if(!e||"string"!=typeof e)return null;let t=e.split("-");if(4!==t.length)return null;let[r,s,i,n]=t;if(2!==r.length||32!==s.length||16!==i.length||2!==n.length)return null;let a=/^[0-9a-f]+$/i;return a.test(r)&&a.test(s)&&a.test(i)&&a.test(n)&&"00000000000000000000000000000000"!==s&&"0000000000000000"!==i?{version:r,traceId:s,parentId:i,traceFlags:n,isSampled:(1&parseInt(n,16))==1}:null}(i.traceparent);if(e&&!e.isSampled)return{traceparent:i.traceparent}}return i}(t,u,h);e&&(e.traceparent&&!n.has("traceparent")&&n.set("traceparent",e.traceparent),e.tracestate&&!n.has("tracestate")&&n.set("tracestate",e.tracestate),e.baggage&&!n.has("baggage")&&n.set("baggage",e.baggage))}return a(t,sr(sr({},s),{},{headers:n}))}},sa=!1,so=!1;function sl(e){return"boolean"==typeof e?{enabled:e}:e}let sh=!1;var su=class extends r2{constructor(e){super(e)}},sc=class{constructor(e,t,r){var s,i,n;this.supabaseUrl=e,this.supabaseKey=t;const a=function(e){let t=null==e?void 0:e.trim();if(!t)throw Error("supabaseUrl is required.");
24if(!t.match(/^https?:\/\//i))throw Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(t.endsWith("/")?t:t+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}(e);if(!t)throw Error("supabaseKey is required.");(e=>{var t,r;if(!e.startsWith("sb_")||ss(e)||e.startsWith("sb_temp_"))return;let s=null!=(t=null==(r=e.match(/^sb_[a-zA-Z0-9]+_/))?void 0:r[0])?t:"unknown";si.has(s)||(si.add(s),console.warn("@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is; if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type."))})(t),function(e){sh||"object"==typeof e&&null!==e&&"schema"in e&&void 0!==e.schema&&(sh=!0,console.warn('@supabase/supabase-js: The "schema" option must be nested under "db", e.g. createClient(url, key, { db: { schema: \'myschema\' } }). A top-level "schema" is ignored and queries go to the default schema.'))}(r),this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const o=`sb-${a.hostname.split(".")[0]}-auth-token`,l=function(e,t){var r,s,i,n,a,o;let{db:l,auth:h,realtime:u,global:c}=e,{db:d,auth:p,realtime:f,global:g}=t,m=sl(e.tracePropagation),y=sl(t.tracePropagation),b={db:sr(sr({},d),l),auth:sr(sr({},p),h),realtime:sr(sr({},f),u),storage:{},global:sr(sr(sr({},g),c),{},{headers:sr(sr({},null!=(r=null==g?void 0:g.headers)?r:{}),null!=(s=null==c?void 0:c.headers)?s:{})}),tracePropagation:{enabled:null!=(i=null!=(n=null==m?void 0:m.enabled)?n:null==y?void 0:y.enabled)&&i,respectSamplingDecision:null==(a=null!=(o=null==m?void 0:m.respectSamplingDecision)?o:null==y?void 0:y.respectSamplingDecision)||a},accessToken:async()=>""};return e.accessToken?b.accessToken=e.accessToken:delete b.accessToken,b}(null!=r?r:{},{db:r3,realtime:r9,auth:sr(sr({},r4),{},{storageKey:o}),global:r8,tracePropagation:r7});this.settings=l,this.storageKey=null!=(s=l.auth.storageKey)?s:"",this.headers=null!=(i=l.global.headers)?i:{},l.accessToken?(this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!=(n=l.auth)?n:{},this.headers,l.global.fetch),this.fetch=sn(t,e,this._getSessionToken.bind(this),l.global.fetch,l.tracePropagation),this.functionsFetch=sn(t,e,this._getSessionToken.bind(this),l.global.fetch,l.tracePropagation,{omitApiKeyAsBearer:!0}),this.realtime=this._initRealtimeClient(sr({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new F(new URL("rest/v1",a).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit,retry:l.db.retry}),this.storage=new tw(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new A(this.functionsUrl.href,{headers:this.headers,customFetch:this.functionsFetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}getOpenApiSpec(){return this.rest.getOpenApiSpec()}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getSessionToken(){var e,t;if(this.accessToken)return await this.accessToken();let{data:r}=await this.auth.getSession();return null!=(e=null==(t=r.session)?void 0:t.access_token)?e:null}async _getAccessToken(){var e;return null!=(e=await this._getSessionToken())?e:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,storageKey:n,flowType:a,lock:o,debug:l,throwOnError:h,experimental:u,lockAcquireTimeout:c,skipAutoInitialize:d},p,f){let g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new su({url:this.authUrl.href,headers:sr(sr({},g),p),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,flowType:a,lock:o,debug:l,throwOnError:h,experimental:u,fetch:f,lockAcquireTimeout:c,skipAutoInitialize:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new eD(this.realtimeUrl.href,sr(sr({},e),{},{params:sr(sr({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){("TOKEN_REFRESHED"===e||"SIGNED_IN"===e||"INITIAL_SESSION"===e)&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0)}};(function(){if("u">typeof window||void 0!==globalThis.Deno)return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(null==t)return!1;let r=t.match(/^v(\d+)\./);return!!r&&20>=parseInt(r[1],10)})()&&console.warn("â ï¸ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to N
24ode.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");var sd=e.i(51516);let sp={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4},sf=/^(.*)[.](0|[1-9][0-9]*)$/;function sg(e,t){if(e===t)return!0;let r=e.match(sf);return!!r&&r[1]===t}function sm(e,t,r){let s=r??3180,i=encodeURIComponent(t);if(i.length<=s)return[{name:e,value:t}];let n=[];for(;i.length>0;){let e=i.slice(0,s),t=e.lastIndexOf("%");t>s-3&&(e=e.slice(0,t));let r="";for(;e.length>0;)try{r=decodeURIComponent(e);break}catch(t){if(t instanceof URIError&&"%"===e.at(-3)&&e.length>3)e=e.slice(0,e.length-3);else throw t}n.push(r),i=i.slice(e.length)}return n.map((t,r)=>({name:`${e}.${r}`,value:t}))}async function sy(e,t){let r=await t(e);if(r)return r;let s=[];for(let r=0;;r++){let i=`${e}.${r}`,n=await t(i);if(!n)break;s.push(n)}return s.length>0?s.join(""):null}function sb(){return"u">typeof window&&void 0!==window.document}sd.parse,sd.serialize;let sw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),sv=" \n\r=".split(""),s_=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<sv.length;t+=1)e[sv[t].charCodeAt(0)]=-2;for(let t=0;t<sw.length;t+=1)e[sw[t].charCodeAt(0)]=t;return e})();function sk(e){let t=[],r=0,s=0;if(function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127)return t(e);if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}(s,t)}}(e,e=>{for(r=r<<8|e,s+=8;s>=6;){let e=r>>s-6&63;t.push(sw[e]),s-=6}}),s>0)for(r<<=6-s,s=6;s>=6;){let e=r>>s-6&63;t.push(sw[e]),s-=6}return t.join("")}let sS="base64-",sE=/-flow-[A-Za-z0-9_-]{8,64}-code-verifier$/;function sT(e){let t;if(!e.startsWith(sS))return e;try{t=function(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},i=0,n=0;for(let t=0;t<e.length;t+=1){let a=s_[e.charCodeAt(t)];if(a>-1)for(i=i<<6|a,n+=6;n>=8;)(function(e,t,r){if(0===t.utf8seq){if(e<=127)return r(e);for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else if(4===t.utf8seq)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}})(i>>n-8&255,s,r),n-=8;else if(-2===a)continue;else throw Error(`Invalid Base64-URL character "${e.at(t)}" at position ${t}`)}return t.join("")}(e.substring(sS.length))}catch(e){return console.warn("@supabase/ssr: could not base64url-decode chunked cookie value, treating as absent. Cookie chunks may have been written partially across responses.",e),null}try{JSON.parse(t)}catch{return console.warn("@supabase/ssr: chunked cookie decoded to invalid JSON, treating as absent. This usually indicates that cookie chunks from different writes were combined (e.g. response committed before all Set-Cookie headers were sent)."),null}return t}async function sA({getAll:e,setAll:t,setItems:r,removedItems:s},i){let n=i.cookieEncoding,a=i.cookieOptions??null,o=await e([...r?Object.keys(r):[],...s?Object.keys(s):[]]),l=o?.map(({name:e})=>e)||[],h=new Map(o?.map(({name:e,value:t})=>[e,t])||[]),u=Object.keys(s).flatMap(e=>l.filter(t=>sg(t,e))),c=Object.keys(r).flatMap(e=>{let t=new Set(l.filter(t=>sg(t,e))),s=r[e];"base64url"===n&&(s=sS+sk(s));let i=sm(e,s);return i.forEach(e=>{t.delete(e.name)}),u.push(...t),i}).filter(({name:e,value:t})=>h.get(e)!==t),d=u.filter(e=>h.has(e)),p={...sp,...a,maxAge:0},f={...sp,...a,maxAge:sp.maxAge};delete p.name,delete f.name;let g=p.domain&&d.length>0?(()=>{let{domain:e,...t}=p;return t})():null;(0!==d.length||0!==c.length)&&await t([...g?d.map(e=>({name:e,value:"",options:g})):[],...d.map(e=>({name:e,value:"",options:p})),...c.map(({name:e,value:t})=>({name:e,value:t,options:f}))],{"Cache-Control":"private, no-cache, no-store, must-revalidate, max-age=0",Expires:"0",Pragma:"no-cache"})}let sR=!1,sO=["@supabase/auth-helpers-nextjs","@supabase/auth-helpers-react","@supabase/auth-helpers-remix","@supabase/auth-helpers-sveltekit"];e.s(["createClient",0,function(){return function(e,t){!function(){if(sR||void 0===w.default||!w.default.env?.npm_package_name)return;let e=w.default.env.npm_package_name;sO.includes(e)&&(sR=!0,console.warn(` 25ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 26â â ï¸ IMPORTANT: Package Consolidation Notice â 27â â 28â The ${e.padEnd(35)} package name is deprecated. â 29â â 30â You are now using @supabase/ssr - a unified solution for all frameworks. â 31â â 32â The auth-helpers packages have been consolidated into @supabase/ssr â 33â to provide better maintenance and consistent APIs across frameworks. â 34â â 35â Please update your package.json to use @supabase/ssr directly: â 36â npm uninstall ${e.padEnd(42)} â 37â npm install @supabase/ssr â 38â â 39â For more information, visit: â 40â https://supabase.com/docs/guides/auth/server-side â 41ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ 42 `))}();let r=sb();if(r&&i)return i;if(!e||!t)throw Error(`@supabase/ssr: Your project's URL and API key are required to create a Supabase client! 43 44Check your Supabase project's API settings to find these values 45 46https://supabase.com/dashboard/project/_/settings/api`);let{storage:s}=function(e,t){let r,s,i=e.cookies&&("get"in e.cookies||"getAll"in e.cookies)?e.cookies:null,n=e.cookieEncoding,a={},o={};if(i)if("get"in i){let e=async e=>{let t=e.flatMap(e=>[e,...Array.from({length:5}).map((t,r)=>`${e}.${r}`)]),r=[];for(let e=0;e<t.length;e+=1){let s=await i.get(t[e]);(s||"string"==typeof s)&&r.push({name:t[e],value:s})}return r};if(r=async t=>await e(t),"set"in i&&"remove"in i)s=async e=>{for(let t=0;t<e.length;t+=1){let{name:r,value:s,options:n}=e[t];s?await i.set(r,s,n):await i.remove(r,n)}};else if(t)s=async()=>{console.warn("@supabase/ssr: createServerClient was configured without set and remove cookie methods, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for c
46orrectness. Consider switching to the getAll and setAll cookie methods instead of get, set and remove which are deprecated and can be difficult to use correctly.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring a getAll and setAll cookie method (deprecated: alternatively both get, set and remove can be used)")}else if("getAll"in i)if(r=async()=>await i.getAll(),"setAll"in i)s=i.setAll;else if(t)s=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: ${t?"createServerClient":"createBrowserClient"} requires configuring getAll and setAll cookie methods (deprecated: alternatively use get, set and remove).${sb()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""}`);else if(!t&&sb())r=()=>{let e;return Object.keys(e=(0,sd.parse)(document.cookie)).map(t=>({name:t,value:e[t]??""}))},s=e=>{e.forEach(({name:e,value:t,options:r})=>{document.cookie=(0,sd.serialize)(e,t,r)})};else if(t)throw Error("@supabase/ssr: createServerClient must be initialized with cookie options that specify getAll and setAll functions (deprecated, not recommended: alternatively use get, set and remove)");else r=()=>[],s=()=>{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")};if(!t)return{getAll:r,setAll:s,setItems:a,removedItems:o,storage:{isServer:!1,getItem:async e=>{let t=await r([e]),s=await sy(e,async e=>{let r=t?.find(({name:t})=>t===e)||null;return r?r.value:null});return s?sT(s):null},setItem:async(t,i)=>{let a=await r([t]),o=new Set((a?.map(({name:e})=>e)||[]).filter(e=>sg(e,t))),l=i;"base64url"===n&&(l=sS+sk(i));let h=sm(t,l);h.forEach(({name:e})=>{o.delete(e)});let u={...sp,...e?.cookieOptions,maxAge:0},c={...sp,...e?.cookieOptions,maxAge:sp.maxAge};delete u.name,delete c.name;let d=u.domain?(()=>{let{domain:e,...t}=u;return t})():null,p=[...d?[...o].map(e=>({name:e,value:"",options:d})):[],...[...o].map(e=>({name:e,value:"",options:u})),...h.map(({name:e,value:t})=>({name:e,value:t,options:c}))];p.length>0&&await s(p,{})},removeItem:async t=>{let i=await r([t]),n=(i?.map(({name:e})=>e)||[]).filter(e=>sg(e,t));if(0===n.length)return;let a={...sp,...e?.cookieOptions,maxAge:0};delete a.name;let o=a.domain?(()=>{let{domain:e,...t}=a;return t})():null,l=[...o?n.map(e=>({name:e,value:"",options:o})):[],...n.map(e=>({name:e,value:"",options:a}))];await s(l,{})}}};let l=s,h=!1;return{getAll:r,setAll:s=async(e,t)=>{let r=!h&&Object.keys(t).length>0;await l(e,r?t:{}),r&&(h=!0)},setItems:a,removedItems:o,storage:{isServer:!0,getItem:async e=>{if("string"==typeof a[e])return a[e];if(o[e])return null;let t=await r([e]),s=await sy(e,async e=>{let r=t?.find(({name:t})=>t===e)||null;return r?r.value:null});return s?"string"!=typeof s?s:sT(s):null},setItem:async(t,i)=>{t.endsWith("-code-verifier")&&await sA({getAll:r,setAll:s,setItems:{[t]:i},removedItems:{}},{cookieOptions:e?.cookieOptions??null,cookieEncoding:n}),a[t]=i,delete o[t]},removeItem:async t=>{(sE.test(t)||t.endsWith("-flows-code-verifier"))&&await sA({getAll:r,setAll:s,setItems:{},removedItems:{[t]:!0}},{cookieOptions:e?.cookieOptions??null,cookieEncoding:n}),delete a[t],o[t]=!0}}}}({...void 0,cookieEncoding:(void 0)??"base64url"},!1),n=new sc(e,t,{...void 0,global:{...void 0,headers:{...void 0,"X-Client-Info":"supabase-ssr/0.12.7 createBrowserClient"}},auth:{...void 0,...null,flowType:"pkce",autoRefreshToken:(void 0)??sb(),detectSessionInUrl:(void 0)??sb(),persistSession:(void 0)??!0,storage:s,...null}});return r&&(i=n),n}("https://nklgifnczdncwdlasuzc.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im5rbGd
46pZm5jemRuY3dkbGFzdXpjIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODA5MTY3NzgsImV4cCI6MjA5NjQ5Mjc3OH0.qWy1FSPuYIEWCxXsGKAQYnH5N7RQib9JQobC_RfK8OQ")}],97648);let sC=e.i(55418).default.overrides;function sx(e){let t=sC[e.slug]?.logo_url;return t&&t!==e.logo_url?{...e,logo_url:t}:e}e.s(["withIntegrationLogo",0,sx,"withIntegrationLogos",0,function(e){return e.map(sx)}],39177)},89984,(e,t,r)=>{var s={872:function(e,t){"use strict";t.byteLength=function(e){var t=l(e),r=t[0],s=t[1];return(r+s)*3/4-s},t.toByteArray=function(e){var t,r,n=l(e),a=n[0],o=n[1],h=new i((a+o)*3/4-o),u=0,c=o>0?a-4:a;for(r=0;r<c;r+=4)t=s[e.charCodeAt(r)]<<18|s[e.charCodeAt(r+1)]<<12|s[e.charCodeAt(r+2)]<<6|s[e.charCodeAt(r+3)],h[u++]=t>>16&255,h[u++]=t>>8&255,h[u++]=255&t;return 2===o&&(t=s[e.charCodeAt(r)]<<2|s[e.charCodeAt(r+1)]>>4,h[u++]=255&t),1===o&&(t=s[e.charCodeAt(r)]<<10|s[e.charCodeAt(r+1)]<<4|s[e.charCodeAt(r+2)]>>2,h[u++]=t>>8&255,h[u++]=255&t),h},t.fromByteArray=function(e){for(var t,s=e.length,i=s%3,n=[],a=0,o=s-i;a<o;a+=16383)n.push(function(e,t,s){for(var i,n=[],a=t;a<s;a+=3)i=(e[a]<<16&0xff0000)+(e[a+1]<<8&65280)+(255&e[a+2]),n.push(r[i>>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return n.join("")}(e,a,a+16383>o?o:a+16383));return 1===i?n.push(r[(t=e[s-1])>>2]+r[t<<4&63]+"=="):2===i&&n.push(r[(t=(e[s-2]<<8)+e[s-1])>>10]+r[t>>4&63]+r[t<<2&63]+"="),n.join("")};for(var r=[],s=[],i="u">typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,o=n.length;a<o;++a)r[a]=n[a],s[n.charCodeAt(a)]=a;function l(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");-1===r&&(r=t);var s=r===t?0:4-r%4;return[r,s]}s[45]=62,s[95]=63},230:function(e,t,r){"use strict";var s=r(872),i=r(321),n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function a(e){if(e>0x7fffffff)throw RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,o.prototype),t}function o(e,t,r){if("number"==typeof e){if("string"==typeof t)throw TypeError('The "string" argument must be of type string. Received type number');return u(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e){var s=e,i=t;if(("string"!=typeof i||""===i)&&(i="utf8"),!o.isEncoding(i))throw TypeError("Unknown encoding: "+i);var n=0|p(s,i),l=a(n),h=l.write(s,i);return h!==n&&(l=l.slice(0,h)),l}if(ArrayBuffer.isView(e))return c(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(C(e,ArrayBuffer)||e&&C(e.buffer,ArrayBuffer)||"u">typeof SharedArrayBuffer&&(C(e,SharedArrayBuffer)||e&&C(e.buffer,SharedArrayBuffer)))return function(e,t,r){var s;if(t<0||e.byteLength<t)throw RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw RangeError('"length" is outside of buffer bounds');return Object.setPrototypeOf(s=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),o.prototype),s}(e,t,r);if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type number');var u=e.valueOf&&e.valueOf();if(null!=u&&u!==e)return o.from(u,t,r);var f=function(e){if(o.isBuffer(e)){var t=0|d(e.length),r=a(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||function(e){return e!=e}(e.length)?a(0):c(e):"Buffer"===e.type&&Array.isArray(e.data)?c(e.data):void 0}(e);if(f)return f;if("u">typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,r);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function h(e){if("number"!=typeof e)throw TypeError('"size" argument must be of type number');if(e<0)throw RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return h(e),a(e<0?0:0|d(e))}function c(e){for(var t=e.length<0?0:0|d(e.length),r=a(t),s=0;s<t;s+=1)r[s]=255&e[s];return r}t.Buffer=o,t.SlowBuffer=function(e){return+e!=e&&(e=0),o.alloc(+e)}
vendor: 16,232 bytes, line 46
46,t.INSPECT_MAX_BYTES=50,t.kMaxLength=0x7fffffff,o.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!o.TYPED_ARRAY_SUPPORT&&"u">typeof console&&"function"==typeof console.error&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(e,t,r){return l(e,t,r)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(e,t,r){return(h(e),e<=0)?a(e):void 0!==t?"string"==typeof r?a(e).fill(t,r):a(e).fill(t):a(e)},o.allocUnsafe=function(e){return u(e)},o.allocUnsafeSlow=function(e){return u(e)};function d(e){if(e>=0x7fffffff)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|e}function p(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||C(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,s=arguments.length>2&&!0===arguments[2];if(!s&&0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return T(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return R(e).length;default:if(i)return s?-1:T(e).length;t=(""+t).toLowerCase(),i=!0}}function f(e,t,r){var i,n,a,o=!1;if((void 0===t||t<0)&&(t=0),t>this.length||((void 0===r||r>this.length)&&(r=this.length),r<=0||(r>>>=0)<=(t>>>=0)))return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,r){var s=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>s)&&(r=s);for(var i="",n=t;n<r;++n)i+=x[e[n]];return i}(this,t,r);case"utf8":case"utf-8":return b(this,t,r);case"ascii":return function(e,t,r){var s="";r=Math.min(e.length,r);for(var i=t;i<r;++i)s+=String.fromCharCode(127&e[i]);return s}(this,t,r);case"latin1":case"binary":return function(e,t,r){var s="";r=Math.min(e.length,r);for(var i=t;i<r;++i)s+=String.fromCharCode(e[i]);return s}(this,t,r);case"base64":return i=this,n=t,a=r,0===n&&a===i.length?s.fromByteArray(i):s.fromByteArray(i.slice(n,a));case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return function(e,t,r){for(var s=e.slice(t,r),i="",n=0;n<s.length;n+=2)i+=String.fromCharCode(s[n]+256*s[n+1]);return i}(this,t,r);default:if(o)throw TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function g(e,t,r){var s=e[t];e[t]=e[r],e[r]=s}function m(e,t,r,s,i){var n;if(0===e.length)return -1;if("string"==typeof r?(s=r,r=0):r>0x7fffffff?r=0x7fffffff:r<-0x80000000&&(r=-0x80000000),(n=r*=1)!=n&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length)if(i)return -1;else r=e.length-1;else if(r<0)if(!i)return -1;else r=0;if("string"==typeof t&&(t=o.from(t,s)),o.isBuffer(t))return 0===t.length?-1:y(e,t,r,s,i);if("number"==typeof t){if(t&=255,"function"==typeof Uint8Array.prototype.indexOf)if(i)return Uint8Array.prototype.indexOf.call(e,t,r);else return Uint8Array.prototype.lastIndexOf.call(e,t,r);return y(e,[t],r,s,i)}throw TypeError("val must be string, number or Buffer")}function y(e,t,r,s,i){var n,a=1,o=e.length,l=t.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(e.length<2||t.length<2)return -1;a=2,o/=2,l/=2,r/=2}function h(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var u=-1;for(n=r;n<o;n++)if(h(e,n)===h(t,-1===u?0:n-u)){if(-1===u&&(u=n),n-u+1===l)return u*a}else -1!==u&&(n-=n-u),u=-1}else for(r+l>o&&(r=o-l),n=r;n>=0;n--){for(var c=!0,d=0;d<l;d++)if(h(e,n+d)!==h(t,d)){c=!1;break}if(c)return n}return -1}o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.compare=function(e,t){if(C(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),C(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var r=e.length,s=t.length,i=0,n=Math.min(r,s);i<n;++i)if(e[i]!==t[i]){r=e[i],s=t[i];break}return r<s?-1:+(s<r)},o.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!Array.isArray(e))throw TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);if(void 0===t)for(r=0,t=0;r<e.length;++r)t+=e[r].length;var r,s=o.allocUnsafe(t),i=0;for(r=0;r<e.length;++r){var n=e[r];if(C(n,Uint8Array)&&(n=o.from(n)),!o.isBuffer(n))throw TypeError('"list" argument must be an Array of Buffers');n.copy(s,i),i+=n.length}return s},o.byteLength=p,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)g(this,t,t+1);return this},o.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},o.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},o.prototype.toString=function(){var e=this.length;return 0===e?"":0==arguments.length?b(this,0,e):f.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){var e="",r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(e,t,r,s,i){if(C(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===s&&(s=0),void 0===i&&(i=this.length),t<0||r>e.length||s<0||i>this.length)throw RangeError("out of range index");if(s>=i&&t>=r)return 0;if(s>=i)return -1;if(t>=r)return 1;if(t>>>=0,r>>>=0,s>>>=0,i>>>=0,this===e)return 0;for(var n=i-s,a=r-t,l=Math.min(n,a),h=this.slice(s,i),u=e.slice(t,r),c=0;c<l;++c)if(h[c]!==u[c]){n=h[c],a=u[c];break}return n<a?-1:+(a<n)},o.prototype.includes=function(e,t,r){return -1!==this.indexOf(e,t,r)},o.prototype.indexOf=function(e,t,r){return m(this,e,t,r,!0)},o.prototype.lastIndexOf=function(e,t,r){return m(this,e,t,r,!1)};function b(e,t,r){r=Math.min(e.length,r);for(var s=[],i=t;i<r;){var n,a,o,l,h=e[i],u=null,c=h>239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(u=h);break;case 2:(192&(n=e[i+1]))==128&&(l=(31&h)<<6|63&n)>127&&(u=l);break;case 3:n=e[i+1],a=e[i+2],(192&n)==128&&(192&a)==128&&(l=(15&h)<<12|(63&n)<<6|63&a)>2047&&(l<55296||l>57343)&&(u=l);break;case 4:n=e[i+1],a=e[i+2],o=e[i+3],(192&n)==128&&(192&a)==128&&(192&o)==128&&(l=(15&h)<<18|(63&n)<<12|(63&a)<<6|63&o)>65535&&l<1114112&&(u=l)}null===u?(u=65533,c=1):u>65535&&(u-=65536,s.push(u>>>10&1023|55296),u=56320|1023&u),s.push(u),i+=c}var d=s,p=d.length;if(p<=4096)return String.fromCharCode.apply(String,d);for(var f="",g=0;g<p;)f+=String.fromCharCode.apply(String,d.slice(g,g+=4096));return f}function w(e,t,r){if(e%1!=0||e<0)throw RangeError("offset is not uint");if(e+t>r)throw RangeError("Trying to access beyond buffer length")}function v(e,t,r,s,i,n){if(!o.isBuffer(e))throw TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<n)throw RangeError('"value" argument is out of bounds');if(r+s>e.length)throw RangeError("Index out of range")}function _(e,t,r,s,i,n){if(r+s>e.length||r<0)throw RangeError("Index out of range")}function k(e,t,r,s,n){return t*=1,r>>>=0,n||_(e,t,r,4,34028234663852886e22,-34028234663852886e22),i.write(e,t,r,s,23,4),r+4}function S(e,t,r,s,n){return t*=1,r>>>=0,n||_(e,t,r,8,17976931348623157e292,-17976931348623157e292),i.write(e,t,r,s,52,8),r+8}o.prototype.write=function(e,t,r,s){if(void 0===t)s="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)s=t,r=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(r)?(r>>>=0,void 0===s&&(s="utf8")):(s=r,r=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var i,n,a,o,l,h,u,c,d=this.length-t;if((void 0===r||r>d)&&(r=d),e.length>0&&(r<0||t<0)||t>this.length)throw RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var p=!1;;)switch(s){case"hex":return function(e,t,r,s){r=Number(r)||0;var i=e.length-r;s?(s=Number(s))>i&&(s=i):s=i;var n=t.length;s>n/2&&(s=n/2);for(var a=0;a<s;++a){var o,l=parseInt(t.substr(2*a,2),16);if((o=l)!=o)break;e[r+a]=l}return a}(this,e,t,r);case"utf8":case"utf-8":return i=t,n=r,O(T(e,this.length-i),this,i,n);case"ascii":return a=t,o=r,O(A(e),this,a,o);case"latin1":case"binary":return function(e,t,r,s){return O(A(t),e,r,s)}(this,e,t,r);case"base64":return l=t,h=r,O(R(e),this,l,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return u=t,c=r,O(function(e,t){for(var r,s,i=[],n=0;n<e.length&&!((t-=2)<0);++n)s=(r=e.charCodeAt(n))>>8,i.push(r%256),i.push(s);return i}(e,this.length-u),this,u,c);default:if(p)throw TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),p=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},o.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);var s=this.subarray(e,t);return Object.setPrototypeOf(s,o.prototype),s},o.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||w(e,t,this.length);for(var s=this[e],i=1,n=0;++n<t&&(i*=256);)s+=this[e+n]*i;return s},o.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||w(e,t,this.length);for(var s=this[e+--t],i=1;t>0&&(i*=256);)s+=this[e+--t]*i;return s},o.prototype.readUInt8=function(e,t){return e>>>=0,t||w(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||w(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||w(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||w(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+0x1000000*this[e+3]},o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||w(e,4,this.length),0x1000000*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||w(e,t,this.length);for(var s=this[e],i=1,n=0;++n<t&&(i*=256);)s+=this[e+n]*i;return s>=(i*=128)&&(s-=Math.pow(2,8*t)),s},o.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||w(e,t,this.length);for(var s=t,i=1,n=this[e+--s];s>0&&(i*=256);)n+=this[e+--s]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*t)),n},o.prototype.readInt8=function(e,t){return(e>>>=0,t||w(e,1,this.length),128&this[e])?-((255-this[e]+1)*1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||w(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?0xffff0000|r:r},o.prototype.readInt16BE=function(e,t){e>>>=0,t||w(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?0xffff0000|r:r},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||w(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||w(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return e>>>=0,t||w(e,4,this.length),i.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||w(e,4,this.length),i.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||w(e,8,this.length),i.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||w(e,8,this.length),i.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,r,s){if(e*=1,t>>>=0,r>>>=0,!s){var i=Math.pow(2,8*r)-1;v(this,e,t,r,i,0)}var n=1,a=0;for(this[t]=255&e;++a<r&&(n*=256);)this[t+a]=e/n&255;return t+r},o.prototype.writeUIntBE=function(e,t,r,s){if(e*=1,t>>>=0,r>>>=0,!s){var i=Math.pow(2,8*r)-1;v(this,e,t,r,i,0)}var n=r-1,a=1;for(this[t+n]=255&e;--n>=0&&(a*=256);)this[t+n]=e/a&255;return t+r},o.prototype.writeUInt8=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUInt16BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUInt32LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0xffffffff,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUInt32BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0xffffffff,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeIntLE=function(e,t,r,s){if(e*=1,t>>>=0,!s){var i=Math.pow(2,8*r-1);v(this,e,t,r,i-1,-i)}var n=0,a=1,o=0;for(this[t]=255&e;++n<r&&(a*=256);)e<0&&0===o&&0!==this[t+n-1]&&(o=1),this[t+n]=(e/a|0)-o&255;return t+r},o.prototype.writeIntBE=function(e,t,r,s){if(e*=1,t>>>=0,!s){var i=Math.pow(2,8*r-1);v(this,e,t,r,i-1,-i)}var n=r-1,a=1,o=0;for(this[t+n]=255&e;--n>=0&&(a*=256);)e<0&&0===o&&0!==this[t+n+1]&&(o=1),this[t+n]=(e/a|0)-o&255;return t+r},o.prototype.writeInt8=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0x7fffffff,-0x80000000),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0x7fffffff,-0x80000000),e<0&&(e=0xffffffff+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeFloatLE=function(e,t,r){return k(this,e,t,!0,r)},o.prototype.writeFloatBE=function(e,t,r){return k(this,e,t,!1,r)},o.prototype.writeDoubleLE=function(e,t,r){return S(this,e,t,!0,r)},o.prototype.writeDoubleBE=function(e,t,r){return S(this,e,t,!1,r)},o.prototype.copy=function(e,t,r,s){if(!o.isBuffer(e))throw TypeError("argument should be a Buffer");if(r||(r=0),s||0===s||(s=this.length),t>=e.length&&(t=e.length),t||(t=0),s>0&&s<r&&(s=r),s===r||0===e.length||0===this.length)return 0;if(t<0)throw RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw RangeError("Index out of range");if(s<0)throw RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),e.length-t<s-r&&(s=e.length-t+r);var i=s-r;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,r,s);else if(this===e&&r<t&&t<s)for(var n=i-1;n>=0;--n)e[n+t]=this[n+r];else Uint8Array.prototype.set.call(e,this.subarray(r,s),t);return i},o.prototype.fill=function(e,t,r,s){if("string"==typeof e){if("string"==typeof t?(s=t,t=0,r=this.length):"string"==typeof r&&(s=r,r=this.length),void 0!==s&&"string"!=typeof s)throw TypeError("encoding must be a string");if("string"==typeof s&&!o.isEncoding(s))throw TypeError("Unknown encoding: "+s);if(1===e.length){var i,n=e.charCodeAt(0);("utf8"===s&&n<128||"latin1"===s)&&(e=n)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw RangeError("Out of range index");if(r<=t)return this;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{var a=o.isBuffer(e)?e:o.from(e,s),l=a.length;
46if(0===l)throw TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=a[i%l]}return this};var E=/[^+/0-9A-Za-z-_]/g;function T(e,t){t=t||1/0;for(var r,s=e.length,i=null,n=[],a=0;a<s;++a){if((r=e.charCodeAt(a))>55295&&r<57344){if(!i){if(r>56319||a+1===s){(t-=3)>-1&&n.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(t-=3)>-1&&n.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else if(r<1114112){if((t-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}else throw Error("Invalid code point")}return n}function A(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}function R(e){return s.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(E,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function O(e,t,r,s){for(var i=0;i<s&&!(i+r>=t.length)&&!(i>=e.length);++i)t[i+r]=e[i];return i}function C(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}var x=function(){for(var e="0123456789abcdef",t=Array(256),r=0;r<16;++r)for(var s=16*r,i=0;i<16;++i)t[s+i]=e[r]+e[i];return t}()},321:function(e,t){t.read=function(e,t,r,s,i){var n,a,o=8*i-s-1,l=(1<<o)-1,h=l>>1,u=-7,c=r?i-1:0,d=r?-1:1,p=e[t+c];for(c+=d,n=p&(1<<-u)-1,p>>=-u,u+=o;u>0;n=256*n+e[t+c],c+=d,u-=8);for(a=n&(1<<-u)-1,n>>=-u,u+=s;u>0;a=256*a+e[t+c],c+=d,u-=8);if(0===n)n=1-h;else{if(n===l)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,s),n-=h}return(p?-1:1)*a*Math.pow(2,n-s)},t.write=function(e,t,r,s,i,n){var a,o,l,h=8*n-i-1,u=(1<<h)-1,c=u>>1,d=5960464477539062e-23*(23===i),p=s?0:n-1,f=s?1:-1,g=+(t<0||0===t&&1/t<0);for(isNaN(t=Math.abs(t))||t===1/0?(o=+!!isNaN(t),a=u):(a=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-a))<1&&(a--,l*=2),a+c>=1?t+=d/l:t+=d*Math.pow(2,1-c),t*l>=2&&(a++,l/=2),a+c>=u?(o=0,a=u):a+c>=1?(o=(t*l-1)*Math.pow(2,i),a+=c):(o=t*Math.pow(2,c-1)*Math.pow(2,i),a=0));i>=8;e[r+p]=255&o,p+=f,o/=256,i-=8);for(a=a<<i|o,h+=i;h>0;e[r+p]=255&a,p+=f,a/=256,h-=8);e[r+p-f]|=128*g}}},i={};function n(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={exports:{}},a=!0;try{s[e](r,r.exports,n),a=!1}finally{a&&delete i[e]}return r.exports}n.ab="/ROOT/website/node_modules/next/dist/compiled/buffer/",t.exports=n(230)},51516,(e,t,r)=>{"use strict";let s;Object.defineProperty(r,"__esModule",{value:!0}),r.parseCookie=c,r.parse=c,r.stringifyCookie=function(e,t){let r=t?.encode||encodeURIComponent,s=[];for(let t of Object.keys(e)){let a=e[t];if(void 0===a)continue;if(!i.test(t))throw TypeError(`cookie name is invalid: ${t}`);let o=r(a);if(!n.test(o))throw TypeError(`cookie val is invalid: ${a}`);s.push(`${t}=${o}`)}return s.join("; ")},r.stringifySetCookie=d,r.serialize=d,r.parseSetCookie=function(e,t){let r=t?.decode||m,s=e.length,i=p(e,0,s),n=f(e,0,i),a=-1===n?{name:"",value:r(g(e,0,i))}:{name:g(e,0,n),value:r(g(e,n+1,i))},o=i+1;for(;o<s;){let t=p(e,o,s),r=f(e,o,t),i=-1===r?g(e,o,t):g(e,o,r),n=-1===r?void 0:g(e,r+1,t);switch(i.toLowerCase()){case"httponly":a.httpOnly=!0;break;case"secure":a.secure=!0;break;case"partitioned":a.partitioned=!0;break;case"domain":a.domain=n;break;case"path":a.path=n;break;case"max-age":n&&l.test(n)&&(a.maxAge=Number(n));break;case"expires":if(!n)break;let h=new Date(n);Number.isFinite(h.valueOf())&&(a.expires=h);break;case"priority":if(!n)break;let u=n.toLowerCase();("low"===u||"medium"===u||"high"===u)&&(a.priority=u);break;case"samesite":if(!n)break;let c=n.toLowerCase();("lax"===c||"strict"===c||"none"===c)&&(a.sameSite=c)}o=t+1}return a},r.stringifySetCookie=d,r.serialize=d;let i=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,n=/^[\u0021-\u003A\u003C-\u007E]*$/,a=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,o=/^[\u0020-\u003A\u003D-\u007E]*$/,l=/^-?\d+$/,h=Object.prototype.toString,u=((s=function(){}).prototype=Object.create(null),s);function c(e,t){let r=new u,s=e.length;if(s<2)return r;let i=t?.decode||m,n=0;do{let t=f(e,n,s);if(-1===t)break;let a=p(e,n,s);if(t>a){n=e.lastIndexOf(";",t-1)+1;continue}let o=g(e,n,t);void 0===r[o]&&(r[o]=i(g(e,t+1,a))),n=a+1}while(n<s)return r}function d(e,t,r){let s="object"==typeof e?e:{...r,name:e,value:String(t)},l=("object"==typeof t?t:r)?.encode||encodeURIComponent;
46if(!i.test(s.name))throw TypeError(`argument name is invalid: ${s.name}`);let u=s.value?l(s.value):"";if(!n.test(u))throw TypeError(`argument val is invalid: ${s.value}`);let c=s.name+"="+u;if(void 0!==s.maxAge){if(!Number.isInteger(s.maxAge))throw TypeError(`option maxAge is invalid: ${s.maxAge}`);c+="; Max-Age="+s.maxAge}if(s.domain){if(!a.test(s.domain))throw TypeError(`option domain is invalid: ${s.domain}`);c+="; Domain="+s.domain}if(s.path){if(!o.test(s.path))throw TypeError(`option path is invalid: ${s.path}`);c+="; Path="+s.path}if(s.expires){var d;if(d=s.expires,"[object Date]"!==h.call(d)||!Number.isFinite(s.expires.valueOf()))throw TypeError(`option expires is invalid: ${s.expires}`);c+="; Expires="+s.expires.toUTCString()}if(s.httpOnly&&(c+="; HttpOnly"),s.secure&&(c+="; Secure"),s.partitioned&&(c+="; Partitioned"),s.priority)switch("string"==typeof s.priority?s.priority.toLowerCase():void 0){case"low":c+="; Priority=Low";break;case"medium":c+="; Priority=Medium";break;case"high":c+="; Priority=High";break;
46default:throw TypeError(`option priority is invalid: ${s.priority}`)}if(s.sameSite)switch("string"==typeof s.sameSite?s.sameSite.toLowerCase():s.sameSite){case!0:case"strict":c+="; SameSite=Strict";break;case"lax":c+="; SameSite=Lax";break;case"none":c+="; SameSite=None";break;default:throw TypeError(`option sameSite is invalid: ${s.sameSite}`)}return c}function p(e,t,r){let s=e.indexOf(";",t);return -1===s?r:s}function f(e,t,r){let s=e.indexOf("=",t);return s<r?s:-1}function g(e,t,r){let s=t,i=r;do{let t=e.charCodeAt(s);if(32!==t&&9!==t)break}while(++s<i)for(;i>s;){let t=e.charCodeAt(i-1);if(32!==t&&9!==t)break;i--}return e.slice(s,i)}function m(e){if(-1===e.indexOf("%"))return e;try{return decodeURIComponent(e)}catch(t){return e}}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.