@tanay-wispr/webflow-package 6.4.2 → 6.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";(()=>{var yr=Object.create;var He=Object.defineProperty;var wr=Object.getOwnPropertyDescriptor;var vr=Object.getOwnPropertyNames;var br=Object.getPrototypeOf,kr=Object.prototype.hasOwnProperty;var Sr=(i,e)=>()=>(i&&(e=i(i=0)),e);var $=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Er=(i,e)=>{for(var t in e)He(i,t,{get:e[t],enumerable:!0})},ts=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of vr(e))!kr.call(i,r)&&r!==t&&He(i,r,{get:()=>e[r],enumerable:!(s=wr(e,r))||s.enumerable});return i};var ss=(i,e,t)=>(t=i!=null?yr(br(i)):{},ts(e||!i||!i.__esModule?He(t,"default",{value:i,enumerable:!0}):t,i)),Tr=i=>ts(He({},"__esModule",{value:!0}),i);var G={};Er(G,{Headers:()=>bt,Request:()=>Or,Response:()=>Rr,default:()=>vt,fetch:()=>Ar});var xr,ie,Ar,vt,bt,Or,Rr,V=Sr(()=>{"use strict";xr=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},ie=xr(),Ar=ie.fetch,vt=ie.fetch.bind(ie),bt=ie.Headers,Or=ie.Request,Rr=ie.Response});var cs=$(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});var kt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};St.default=kt});var Tt=$(ye=>{"use strict";var ls=ye&&ye.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ye,"__esModule",{value:!0});var Cr=ls((V(),Tr(G))),jr=ls(cs()),Et=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=Cr.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,r=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let h=null,l=null,u=null,d=n.status,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let b=await n.text();b===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=b:l=JSON.parse(b))}let y=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),m=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");y&&m&&m.length>1&&(u=parseInt(m[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(h={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,u=null,d=406,f="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let y=await n.text();try{h=JSON.parse(y),Array.isArray(h)&&n.status===404&&(l=[],h=null,d=200,f="OK")}catch{n.status===404&&y===""?(d=204,f="No Content"):h={message:y}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new jr.default(h)}return{error:h,data:l,count:u,status:d,statusText:f}});return this.shouldThrowOnError||(r=r.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}};ye.default=Et});var At=$(we=>{"use strict";var $r=we&&we.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(we,"__esModule",{value:!0});var Ir=$r(Tt()),xt=class extends Ir.default{select(e){let t=!1,s=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:r,referencedTable:n=r}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let r=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){let n=typeof r>"u"?"offset":`${r}.offset`,o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:r=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,n?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};we.default=xt});var Ke=$(ve=>{"use strict";var Lr=ve&&ve.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ve,"__esModule",{value:!0});var Ur=Lr(At()),Ot=class extends Ur.default{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}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(r=>typeof r=="string"&&new RegExp("[,()]").test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?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 typeof t=="string"?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 typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:r}={}){let n="";r==="plain"?n="pl":r==="phrase"?n="ph":r==="websearch"&&(n="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};ve.default=Ot});var Pt=$(ke=>{"use strict";var Dr=ke&&ke.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ke,"__esModule",{value:!0});var be=Dr(Ke()),Rt=class{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=t,this.schema=s,this.fetch=r}select(e,{head:t=!1,count:s}={}){let r=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new be.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let r="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new be.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),r&&a.push(`count=${r}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((h,l)=>h.concat(Object.keys(l)),[]);if(c.length>0){let h=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",h.join(","))}}return new be.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",r=[];return this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new be.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new be.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ke.default=Rt});var hs=$(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.version=void 0;Ye.version="0.0.0-automated"});var us=$(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.DEFAULT_HEADERS=void 0;var Nr=hs();Qe.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Nr.version}`}});var fs=$(Se=>{"use strict";var ds=Se&&Se.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Se,"__esModule",{value:!0});var Fr=ds(Pt()),qr=ds(Ke()),Mr=us(),Ct=class i{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=Object.assign(Object.assign({},Mr.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=r}from(e){let t=new URL(`${this.url}/${e}`);return new Fr.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new i(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:r=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||r?(o=s?"HEAD":"GET",Object.entries(t).filter(([l,u])=>u!==void 0).map(([l,u])=>[l,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([l,u])=>{a.searchParams.append(l,u)})):(o="POST",c=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new qr.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};Se.default=Ct});var ws=$(T=>{"use strict";var Ee=T&&T.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(T,"__esModule",{value:!0});T.PostgrestBuilder=T.PostgrestTransformBuilder=T.PostgrestFilterBuilder=T.PostgrestQueryBuilder=T.PostgrestClient=void 0;var ps=Ee(fs());T.PostgrestClient=ps.default;var gs=Ee(Pt());T.PostgrestQueryBuilder=gs.default;var ms=Ee(Ke());T.PostgrestFilterBuilder=ms.default;var _s=Ee(At());T.PostgrestTransformBuilder=_s.default;var ys=Ee(Tt());T.PostgrestBuilder=ys.default;T.default={PostgrestClient:ps.default,PostgrestQueryBuilder:gs.default,PostgrestFilterBuilder:ms.default,PostgrestTransformBuilder:_s.default,PostgrestBuilder:ys.default}});var Os=$((fn,As)=>{"use strict";As.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var I="https://api.wisprflow.ai",wt=class{static async signupUser(e){try{let t=`${I}/signup`,r=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=r&&r.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${I}/signup_raw_email`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Adding raw user failed with status ${t.status}`);return console.log("Added raw user successfully"),await t.json()}catch(t){throw console.error("Error during raw user signup:",t),t}}static async addToWaitlist(e){try{let t=await fetch(`${I}/add_to_waitlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying waitlist failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async applyReferralCode(e){try{let t=await fetch(`${I}/api/v1/referral/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying referral code failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async associateAppSumoLicense(e){try{let t=await fetch("https://api.wisprflow.ai/app_sumo/associate_license_key",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}static async checkUserStatus(e){return await(await fetch(`${I}/user_status?email=${encodeURIComponent(e)}`)).json()}static async getSubscriptionStatus(e){return await fetch(`${I}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${I}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s){let r=`${I}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(r+=`&currency=${s}`),await(await fetch(r,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${I}/api/v1/referral/download-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:e,recipient_email:t})})}static async getAndroidWaitlistStats(e){return await fetch("https://api-east.wisprflow.ai/api/v1/promos/android_waitlist_rank",{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${I}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}};function rs(i){let[e,...t]=i.split(" "),s=t.join(" ");return[e,s]}var ge=wt;var is=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var ns=()=>{let i=window.location.hash.substring(1),e=new URLSearchParams(i);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var os=()=>{let{access_token:i,refresh_token:e}=ns(),t=i,s=e;if(!t||!s){let r=is();t=r.access_token,s=r.refresh_token}return{accessToken:t,refreshToken:s}};var as=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(V(),G)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var me=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},ze=class extends me{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Ge=class extends me{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Je=class extends me{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},We;(function(i){i.Any="any",i.ApNortheast1="ap-northeast-1",i.ApNortheast2="ap-northeast-2",i.ApSouth1="ap-south-1",i.ApSoutheast1="ap-southeast-1",i.ApSoutheast2="ap-southeast-2",i.CaCentral1="ca-central-1",i.EuCentral1="eu-central-1",i.EuWest1="eu-west-1",i.EuWest2="eu-west-2",i.EuWest3="eu-west-3",i.SaEast1="sa-east-1",i.UsEast1="us-east-1",i.UsWest1="us-west-1",i.UsWest2="us-west-2"})(We||(We={}));var Pr=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},_e=class{constructor(e,{headers:t={},customFetch:s,region:r=We.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=as(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Pr(this,void 0,void 0,function*(){try{let{headers:r,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let h;o&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData<"u"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),r),body:h}).catch(p=>{throw new ze(p)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new Ge(l);if(!l.ok)throw new Je(l);let d=((s=l.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield l.json():d==="application/octet-stream"?f=yield l.blob():d==="text/event-stream"?f=l:d==="multipart/form-data"?f=yield l.formData():f=yield l.text(),{data:f,error:null}}catch(r){return{data:null,error:r}}})}};var vs=ss(ws(),1),{PostgrestClient:bs,PostgrestQueryBuilder:Ji,PostgrestFilterBuilder:Wi,PostgrestTransformBuilder:Ki,PostgrestBuilder:Yi}=vs.default;var ks="2.10.2";var Ss={"X-Client-Info":`realtime-js/${ks}`},Es="1.0.0",Ze=1e4,Ts=1e3,J;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(J||(J={}));var A;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})(A||(A={}));var R;(function(i){i.close="phx_close",i.error="phx_error",i.join="phx_join",i.reply="phx_reply",i.leave="phx_leave",i.access_token="access_token"})(R||(R={}));var Xe;(function(i){i.websocket="websocket"})(Xe||(Xe={}));var B;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(B||(B={}));var Te=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let r=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+r));o=o+r;let c=s.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:h}}};var W=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}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))}};var w;(function(i){i.abstime="abstime",i.bool="bool",i.date="date",i.daterange="daterange",i.float4="float4",i.float8="float8",i.int2="int2",i.int4="int4",i.int4range="int4range",i.int8="int8",i.int8range="int8range",i.json="json",i.jsonb="jsonb",i.money="money",i.numeric="numeric",i.oid="oid",i.reltime="reltime",i.text="text",i.time="time",i.timestamp="timestamp",i.timestamptz="timestamptz",i.timetz="timetz",i.tsrange="tsrange",i.tstzrange="tstzrange"})(w||(w={}));var $t=(i,e,t={})=>{var s;let r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Vr(o,i,e,r),n),{})},Vr=(i,e,t,s)=>{let r=e.find(a=>a.name===i),n=r?.type,o=t[i];return n&&!s.includes(n)?xs(n,o):jt(o)},xs=(i,e)=>{if(i.charAt(0)==="_"){let t=i.slice(1,i.length);return Gr(e,t)}switch(i){case w.bool:return Br(e);case w.float4:case w.float8:case w.int2:case w.int4:case w.int8:case w.numeric:case w.oid:return Hr(e);case w.json:case w.jsonb:return zr(e);case w.timestamp:return Jr(e);case w.abstime:case w.date:case w.daterange:case w.int4range:case w.int8range:case w.money:case w.reltime:case w.text:case w.time:case w.timestamptz:case w.timetz:case w.tsrange:case w.tstzrange:return jt(e);default:return jt(e)}},jt=i=>i,Br=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},Hr=i=>{if(typeof i=="string"){let e=parseFloat(i);if(!Number.isNaN(e))return e}return i},zr=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},Gr=(i,e)=>{if(typeof i!="string")return i;let t=i.length-1,s=i[t];if(i[0]==="{"&&s==="}"){let n,o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>xs(e,a))}return i},Jr=i=>typeof i=="string"?i.replace(" ","T"):i,et=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var K=class{constructor(e,t,s={},r=Ze){this.channel=e,this.event=t,this.payload=s,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,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()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var It;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(It||(It={}));var ne=class i{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=i.syncState(this.state,r,n,o),this.pendingDiffs.forEach(c=>{this.state=i.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=i.syncDiff(this.state,r,n,o),a())}),this.onJoin((r,n,o)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:n,newPresences:o})}),this.onLeave((r,n,o)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(h,l)=>{o[h]||(c[h]=l)}),this.map(o,(h,l)=>{let u=n[h];if(u){let d=l.map(m=>m.presence_ref),f=u.map(m=>m.presence_ref),p=l.filter(m=>f.indexOf(m.presence_ref)<0),y=u.filter(m=>d.indexOf(m.presence_ref)<0);p.length>0&&(a[h]=p),y.length>0&&(c[h]=y)}else a[h]=l}),this.syncDiff(n,{joins:a,leaves:c},s,r)}static syncDiff(e,t,s,r){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(n,(a,c)=>{var h;let l=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(c),l.length>0){let u=e[a].map(f=>f.presence_ref),d=l.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}s(a,l,c)}),this.map(o,(a,c)=>{let h=e[a];if(!h)return;let l=c.map(u=>u.presence_ref);h=h.filter(u=>l.indexOf(u.presence_ref)<0),e[a]=h,r(a,h,c),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let r=e[s];return"metas"in r?t[s]=r.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=r,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var Lt;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(Lt||(Lt={}));var Ut;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes"})(Ut||(Ut={}));var Dt;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(Dt||(Dt={}));var oe=class i{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=A.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new K(this,R.join,this.params,this.timeout),this.rejoinTimer=new W(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=A.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=A.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=A.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=A.errored,this.rejoinTimer.scheduleTimeout())}),this._on(R.reply,{},(r,n)=>{this._trigger(this._replyEventName(n),r)}),this.presence=new ne(this),this.broadcastEndpointURL=et(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,r;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},h={broadcast:n,presence:o,postgres_changes:(r=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(l=>l.filter))!==null&&r!==void 0?r:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:h},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,f=(u=d?.length)!==null&&u!==void 0?u:0,p=[];for(let y=0;y<f;y++){let m=d[y],{filter:{event:b,schema:P,table:O,filter:x}}=m,S=l&&l[y];if(S&&S.event===b&&S.schema===P&&S.table===O&&S.filter===x)p.push(Object.assign(Object.assign({},m),{id:S.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=p,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,r;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((r=c.body)===null||r===void 0?void 0:r.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),h.receive("ok",()=>n("ok")),h.receive("error",()=>n("error")),h.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=A.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(R.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let r=new K(this,R.leave,{},e);r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let r=new AbortController,n=setTimeout(()=>r.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new K(this,e,t,s);return this._canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:h,join:l}=R;if(s&&[a,c,h,l].indexOf(o)>=0&&s!==this._joinRef())return;let d=this._onMessage(o,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(r=this.bindings.postgres_changes)===null||r===void 0||r.filter(f=>{var p,y,m;return((p=f.filter)===null||p===void 0?void 0:p.event)==="*"||((m=(y=f.filter)===null||y===void 0?void 0:y.event)===null||m===void 0?void 0:m.toLocaleLowerCase())===o}).map(f=>f.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var p,y,m,b,P,O;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let x=f.id,S=(p=f.filter)===null||p===void 0?void 0:p.event;return x&&((y=t.ids)===null||y===void 0?void 0:y.includes(x))&&(S==="*"||S?.toLocaleLowerCase()===((m=t.data)===null||m===void 0?void 0:m.type.toLocaleLowerCase()))}else{let x=(P=(b=f?.filter)===null||b===void 0?void 0:b.event)===null||P===void 0?void 0:P.toLocaleLowerCase();return x==="*"||x===((O=t?.event)===null||O===void 0?void 0:O.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let p=d.data,{schema:y,table:m,commit_timestamp:b,type:P,errors:O}=p;d=Object.assign(Object.assign({},{schema:y,table:m,commit_timestamp:b,eventType:P,new:{},old:{},errors:O}),this._getPayloadRecords(p))}f.callback(d,s)})}_isClosed(){return this.state===A.closed}_isJoined(){return this.state===A.joined}_isJoining(){return this.state===A.joining}_isLeaving(){return this.state===A.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let r=e.toLocaleLowerCase(),n={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(n):this.bindings[r]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(r=>{var n;return!(((n=r.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&i.isEqual(r.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(R.close,{},e)}_onError(e){this._on(R.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=A.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=$t(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=$t(e.columns,e.old_record)),t}};var Kr=()=>{},Yr=typeof WebSocket<"u",ae=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Ss,this.params={},this.timeout=Ze,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Kr,this.conn=null,this.sendBuffer=[],this.serializer=new Te,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(V(),G)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Xe.websocket}`,this.httpEndpoint=et(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let r=(s=t?.params)===null||s===void 0?void 0:s.apikey;r&&(this.accessToken=r,this.apiKey=r),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new W(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(Yr){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Nt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>ss(Os())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case J.connecting:return B.Connecting;case J.open:return B.Open;case J.closing:return B.Closing;default:return B.Closed}}isConnected(){return this.connectionState()===B.Open}channel(e,t={config:{}}){let s=new oe(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:r,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${s} (${n})`,r),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(R.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",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))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Es}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:r,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||r===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${r} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(r,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(R.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",r=new URLSearchParams(t);return`${e}${s}${r}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Ts,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Nt=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=J.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var ce=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function k(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}var tt=class extends ce{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},xe=class extends ce{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Qr=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},st=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(V(),G)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Rs=()=>Qr(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(V(),G))).Response:Response});var le=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},Ft=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Xr=(i,e)=>le(void 0,void 0,void 0,function*(){let t=yield Rs();i instanceof t?i.json().then(s=>{e(new tt(Ft(s),i.status||500))}).catch(s=>{e(new xe(Ft(s),s))}):e(new xe(Ft(i),i))}),Zr=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};function rt(i,e,t,s,r,n){return le(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,Zr(e,s,r,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Xr(c,a))})})}function Ae(i,e,t,s){return le(this,void 0,void 0,function*(){return rt(i,"GET",e,t,s)})}function L(i,e,t,s,r){return le(this,void 0,void 0,function*(){return rt(i,"POST",e,s,r,t)})}function Ps(i,e,t,s,r){return le(this,void 0,void 0,function*(){return rt(i,"PUT",e,s,r,t)})}function it(i,e,t,s,r){return le(this,void 0,void 0,function*(){return rt(i,"DELETE",e,s,r,t)})}var C=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},ei={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Cs={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Oe=class{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=st(r)}uploadOrUpdate(e,t,s,r){return C(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Cs),r),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),h=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield l.json();return l.ok?{data:{path:c,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(k(n))return{data:null,error:n};throw n}})}upload(e,t,s){return C(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return C(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,h=Object.assign({upsert:Cs.upsert},r),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",h.cacheControl)):(c=s,l["cache-control"]=`max-age=${h.cacheControl}`,l["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(k(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return C(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),r=Object.assign({},this.headers);t?.upsert&&(r["x-upsert"]="true");let n=yield L(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new ce("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}update(e,t,s){return C(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return C(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}copy(e,t,s){return C(this,void 0,void 0,function*(){try{return{data:{path:(yield L(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return C(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),n=yield L(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return C(this,void 0,void 0,function*(){try{let r=yield L(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:r.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}download(e,t){return C(this,void 0,void 0,function*(){let r=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield Ae(this.fetch,`${this.url}/${r}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(k(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),r=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&r.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&r.push(c);let h=r.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${h}`)}}}remove(e){return C(this,void 0,void 0,function*(){try{return{data:yield it(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}list(e,t,s){return C(this,void 0,void 0,function*(){try{let r=Object.assign(Object.assign(Object.assign({},ei),t),{prefix:e||""});return{data:yield L(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var js="2.6.0";var $s={"X-Client-Info":`storage-js/${js}`};var he=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},Re=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},$s),t),this.fetch=st(s)}listBuckets(){return he(this,void 0,void 0,function*(){try{return{data:yield Ae(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(k(e))return{data:null,error:e};throw e}})}getBucket(e){return he(this,void 0,void 0,function*(){try{return{data:yield Ae(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return he(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return he(this,void 0,void 0,function*(){try{return{data:yield Ps(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}emptyBucket(e){return he(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}deleteBucket(e){return he(this,void 0,void 0,function*(){try{return{data:yield it(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}};var Pe=class extends Re{constructor(e,t={},s){super(e,t,s)}from(e){return new Oe(this.url,this.headers,e,this.fetch)}};var Is="2.44.4";var Ce="";typeof Deno<"u"?Ce="deno":typeof document<"u"?Ce="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ce="react-native":Ce="node";var ti={"X-Client-Info":`supabase-js-${Ce}/${Is}`},Ls={headers:ti},Us={schema:"public"},Ds={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ns={};V();var si=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},ri=i=>{let e;return i?e=i:typeof fetch>"u"?e=vt:e=fetch,(...t)=>e(...t)},ii=()=>typeof Headers>"u"?bt:Headers,Fs=(i,e,t)=>{let s=ri(t),r=ii();return(n,o)=>si(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:i,h=new r(o?.headers);return h.has("apikey")||h.set("apikey",i),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:h}))})};function qs(i){return i.replace(/\/$/,"")}function Ms(i,e){let{db:t,auth:s,realtime:r,global:n}=i,{db:o,auth:a,realtime:c,global:h}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),r),global:Object.assign(Object.assign({},h),n)}}var nt="2.64.4";var Vs="http://localhost:9999",Bs="supabase.auth.token";var Hs={"X-Client-Info":`gotrue-js/${nt}`},qt=10;var je="X-Supabase-Api-Version",Mt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function zs(i){return Math.round(Date.now()/1e3)+i}function Gs(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){let e=Math.random()*16|0;return(i=="x"?e:e&3|8).toString(16)})}var j=()=>typeof document<"u",Y={tested:!1,writable:!1},H=()=>{if(!j())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Y.tested)return Y.writable;let i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),Y.tested=!0,Y.writable=!0}catch{Y.tested=!0,Y.writable=!1}return Y.writable};function ot(i){let e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,n)=>{e[n]=r})}catch{}return t.searchParams.forEach((s,r)=>{e[r]=s}),e}var at=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(V(),G)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Js=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",Vt=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},Ie=async(i,e)=>{let t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},ct=async(i,e)=>{await i.removeItem(e)};function ni(i){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,r,n,o,a,c,h,l=0;for(i=i.replace("-","+").replace("_","/");l<i.length;)o=e.indexOf(i.charAt(l++)),a=e.indexOf(i.charAt(l++)),c=e.indexOf(i.charAt(l++)),h=e.indexOf(i.charAt(l++)),s=o<<2|a>>4,r=(a&15)<<4|c>>2,n=(c&3)<<6|h,t=t+String.fromCharCode(s),c!=64&&r!=0&&(t=t+String.fromCharCode(r)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var $e=class i{constructor(){this.promise=new i.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};$e.promiseConstructor=Promise;function Bt(i){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=i.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let s=t[1];return JSON.parse(ni(s))}async function Ws(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function Ks(i,e){return new Promise((s,r)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await i(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){r(o);return}}})()})}function oi(i){return("0"+i.toString(16)).substr(-2)}function ai(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,r="";for(let n=0;n<56;n++)r+=t.charAt(Math.floor(Math.random()*s));return r}return crypto.getRandomValues(e),Array.from(e,oi).join("")}async function ci(i){let t=new TextEncoder().encode(i),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(n=>String.fromCharCode(n)).join("")}function li(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function hi(i){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),i;let t=await ci(i);return li(t)}async function Q(i,e,t=!1){let s=ai(),r=s;t&&(r+="/PASSWORD_RECOVERY"),await Vt(i,`${e}-code-verifier`,r);let n=await hi(s);return[n,s===n?"plain":"s256"]}var ui=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ys(i){let e=i.headers.get(je);if(!e||!e.match(ui))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Le=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function g(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}var lt=class extends Le{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function Qs(i){return g(i)&&i.name==="AuthApiError"}var ue=class extends Le{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},F=class extends Le{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}},U=class extends F{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},de=class extends F{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},X=class extends F{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Z=class extends F{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},Ue=class extends F{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},fe=class extends F{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function ht(i){return g(i)&&i.name==="AuthRetryableFetchError"}var De=class extends F{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var di=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},ee=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),fi=[502,503,504];async function Xs(i){var e;if(!Js(i))throw new fe(ee(i),0);if(fi.includes(i.status))throw new fe(ee(i),i.status);let t;try{t=await i.json()}catch(n){throw new ue(ee(n),n)}let s,r=Ys(i);if(r&&r.getTime()>=Mt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new De(ee(t),i.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new De(ee(t),i.status,t.weak_password.reasons);throw new lt(ee(t),i.status||500,s)}var pi=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function _(i,e,t,s){var r;let n=Object.assign({},s?.headers);n[je]||(n[je]=Mt["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(r=s?.query)!==null&&r!==void 0?r:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await gi(i,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function gi(i,e,t,s,r,n){let o=pi(e,s,r,n),a;try{a=await i(t,Object.assign({},o))}catch(c){throw console.error(c),new fe(ee(c),0)}if(a.ok||await Xs(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await Xs(c)}}function q(i){var e;let t=null;mi(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=zs(i.expires_in)));let s=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:s},error:null}}function Ht(i){let e=q(i);return!e.error&&i.weak_password&&typeof i.weak_password=="object"&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.message&&typeof i.weak_password.message=="string"&&i.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=i.weak_password),e}function D(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function Zs(i){return{data:i,error:null}}function er(i){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n}=i,o=di(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function tr(i){return i}function mi(i){return i.access_token&&i.refresh_token&&i.expires_in}var _i=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},te=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=at(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await _(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(g(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await _(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:D})}catch(s){if(g(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=_i(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s?.newEmail,delete r.newEmail),await _(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:er,redirectTo:t?.redirectTo})}catch(t){if(g(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await _(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:D})}catch(t){if(g(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,n,o,a,c;try{let h={nextPage:null,lastPage:0,total:0},l=await _(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(r=e?.perPage)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""},xform:tr});if(l.error)throw l.error;let u=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(p=>{let y=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(p.split(";")[1].split("=")[1]);h[`${m}Page`]=y}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(g(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await _(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:D})}catch(t){if(g(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await _(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:D})}catch(s){if(g(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await _(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:D})}catch(s){if(g(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await _(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:r=>({data:{factors:r},error:null})});return{data:t,error:s}}catch(t){if(g(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await _(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(g(t))return{data:null,error:t};throw t}}};var sr={getItem:i=>H()?globalThis.localStorage.getItem(i):null,setItem:(i,e)=>{H()&&globalThis.localStorage.setItem(i,e)},removeItem:i=>{H()&&globalThis.localStorage.removeItem(i)}};function zt(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function rr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var se={debug:!!(globalThis&&H()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Ne=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},ut=class extends Ne{};async function Gt(i,e,t){se.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),se.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",i)},e),await globalThis.navigator.locks.request(i,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async r=>{if(r){se.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,r.name);try{return await t()}finally{se.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,r.name)}}else{if(e===0)throw se.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new ut(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(se.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}rr();var yi={url:Vs,storageKey:Bs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Hs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Fe=30*1e3,ir=3;async function nr(i,e,t){return await t()}var re=class i{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=i.nextInstanceID,i.nextInstanceID+=1,this.instanceID>0&&j()&&console.warn("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.");let r=Object.assign(Object.assign({},yi),e);if(this.logDebugMessages=!!r.debug,typeof r.debug=="function"&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new te({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=at(r.fetch),this.lock=r.lock||nr,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:j()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Gt:this.lock=nr,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)},this.persistSession?r.storage?this.storage=r.storage:H()?this.storage=sr:(this.memoryStorage={},this.storage=zt(this.memoryStorage)):(this.memoryStorage={},this.storage=zt(this.memoryStorage)),j()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${nt}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=j()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:r,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",r,"redirect type",n),await this._saveSession(r),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",r):await this._notifyAllSubscribers("SIGNED_IN",r)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return g(e)?{error:e}:{error:new ue("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{let n=await _(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}},xform:q}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(g(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,r;try{let n;if("email"in e){let{email:l,password:u,options:d}=e,f=null,p=null;this.flowType==="pkce"&&([f,p]=await Q(this.storage,this.storageKey)),n=await _(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:p},xform:q})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await _(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:u,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(r=d?.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:q})}else throw new X("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(g(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await _(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ht})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await _(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ht})}else throw new X("You must provide either an email or phone number and a password");let{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new de}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r})}catch(t){if(g(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(r=e.options)===null||r===void 0?void 0:r.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Ie(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/"),{data:n,error:o}=await _(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:q});return await ct(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new de}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:r??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:r,access_token:n,nonce:o}=e,a=await _(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:q}),{data:c,error:h}=a;return h?{data:{user:null,session:null},error:h}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new de}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(g(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,n,o;try{if("email"in e){let{email:a,options:c}=e,h=null,l=null;this.flowType==="pkce"&&([h,l]=await Q(this.storage,this.storageKey));let{error:u}=await _(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:h,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:c}=e,{data:h,error:l}=await _(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(r=c?.data)!==null&&r!==void 0?r:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:l}}throw new X("You must provide either an email or phone number.")}catch(a){if(g(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let r,n;"options"in e&&(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await _(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:r,xform:q});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(r){if(g(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Q(this.storage,this.storageKey)),await _(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:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:Zs})}catch(n){if(g(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new U;let{error:r}=await _(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(g(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:r,options:n}=e,{error:o}=await _(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:r,options:n}=e,{data:o,error:a}=await _(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new X("You must provide either an email or phone number and a type")}catch(t){if(g(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch{}})()),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 s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let r=[...this.pendingInLock];await Promise.all(r),this.pendingInLock.splice(0,r.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Ie(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,h,l)=>(!o&&h==="user"&&(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 many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,h,l))})}return{data:{session:e},error:null}}let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await _(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:D}):await this._useSession(async t=>{var s,r,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new U}:await _(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:void 0,xform:D})})}catch(t){if(g(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:r,error:n}=s;if(n)throw n;if(!r.session)throw new U;let o=r.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await Q(this.storage,this.storageKey));let{data:h,error:l}=await _(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:D});if(l)throw l;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(g(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return Bt(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new U;let t=Date.now()/1e3,s=t,r=!0,n=null,o=Bt(e.access_token);if(o.exp&&(s=o.exp,r=s<=t),r){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(g(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new U;let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(g(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!j())throw new Z("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Z("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Ue("Not a valid PKCE flow url.");let t=ot(window.location.href);if(e){if(!t.code)throw new Ue("No code detected.");let{data:P,error:O}=await this._exchangeCodeForSession(t.code);if(O)throw O;let x=new URL(window.location.href);return x.searchParams.delete("code"),window.history.replaceState(window.history.state,"",x.toString()),{data:{session:P.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Z(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:r,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:h}=t;if(!n||!a||!o||!h)throw new Z("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;c&&(d=parseInt(c));let f=d-l;f*1e3<=Fe&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let p=d-u;l-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,d,l):l-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",p,d,l);let{data:y,error:m}=await this._getUser(n);if(m)throw m;let b={provider_token:s,provider_refresh_token:r,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:b,redirectType:t.type},error:null}}catch(t){if(g(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=ot(window.location.href);return!!(j()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=ot(window.location.href),t=await Ie(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:r,error:n}=t;if(n)return{error:n};let o=(s=r.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Qs(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await ct(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Gs(),s={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,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;try{let{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;this.flowType==="pkce"&&([s,r]=await Q(this.storage,this.storageKey,!0));try{return await _(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(g(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(g(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:r}=await this._useSession(async n=>{var o,a,c,h,l;let{data:u,error:d}=n;if(d)throw d;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await _(this.fetch,"GET",f,{headers:this.headers,jwt:(l=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&l!==void 0?l:void 0})});if(r)throw r;return j()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(g(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;let{data:n,error:o}=t;if(o)throw o;return await _(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(r=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&r!==void 0?r:void 0})})}catch(t){if(g(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await Ks(async r=>(r>0&&await Ws(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await _(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:q})),(r,n)=>{let o=200*Math.pow(2,r);return n&&ht(n)&&Date.now()+o-s<Fe})}catch(s){if(this._debug(t,"error",s),g(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let 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",s),j()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await Ie(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let r=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<r+qt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${qt}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),ht(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new U;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new $e;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new U;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(r,"error",n),g(n)){let o={session:null,error:n};return ht(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){let r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Vt(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await ct(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&j()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Fe);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let r=Math.floor((s.expires_at*1e3-e)/Fe);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${Fe}ms, refresh threshold is ${ir} ticks`),r<=ir&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Ne)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!j()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let r=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await Q(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);r.push(n.toString())}return s?.skipBrowserRedirect&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await _(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(g(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,r;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await _(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((r=a?.totp)===null||r===void 0)&&r.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(g(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await _(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(g(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await _(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(g(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],r=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:r},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:r},error:n}=e;if(n)return{data:null,error:n};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(r.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=r.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};re.nextInstanceID=0;var wi=re,Jt=wi;var dt=class extends Jt{constructor(e){super(e)}};var vi=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},qe=class{constructor(e,t,s){var r,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=qs(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:Us,realtime:Ns,auth:Object.assign(Object.assign({},Ds),{storageKey:c}),global:Ls},l=Ms(s??{},h);this.storageKey=(r=l.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=Fs(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new bs(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new _e(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Pe(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}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()}_getAccessToken(){var e,t;return vi(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,storageKey:n,flowType:o,debug:a},c,h){var l;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new dt({url:this.authUrl,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new ae(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var or=(i,e,t)=>new qe(i,e,t);var M={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var ft=class{constructor(){this.sessionData=null;this.supabase=or(M.supaBaseUrl,M.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||M.redirectUri}}),console.log("Signed in with Google")}catch(t){throw console.error("Error signing in with Google:",t),t}}async signInWithApple(e){try{await this.supabase.auth.signInWithOAuth({provider:"apple",options:{redirectTo:e||M.redirectUri}}),console.log("Signed in with Apple")}catch(t){throw console.error("Error signing in with Apple:",t),t}}async signInWithMicrosoft(e){try{await this.supabase.auth.signInWithOAuth({provider:"azure",options:{redirectTo:e||M.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:r}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(r)throw r;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw this.signOut(),console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let r=new Date;r.setTime(r.getTime()+s*24*60*60*1e3);let n=`expires=${r.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,s=e.refresh_token;if(t&&s)try{await this.setSession(t,s)}catch(r){throw r}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,r]=t.split("=");return e[s]=r,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||M.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,r,n){try{let{error:o}=await this.supabase.auth.signUp({email:e,password:t,options:{emailRedirectTo:r||M.redirectUri,data:{full_name:s},captchaToken:n}});if(o)throw o;console.log("Signup successful, verification email sent to:",e)}catch(o){throw console.error("Error signing up:",o),o}}async signInWithPassword(e,t,s){try{let{data:r,error:n}=await this.supabase.auth.signInWithPassword({email:e,password:t,options:{captchaToken:s}});if(n)throw n;if(!r.session)throw new Error("No session returned from sign in");return console.log("Sign in successful for:",e),{accessToken:r.session.access_token,refreshToken:r.session.refresh_token}}catch(r){throw console.error("Error signing in with password:",r),r}}async resendVerificationEmail(e,t){try{let{error:s}=await this.supabase.auth.resend({type:"signup",email:e,options:{emailRedirectTo:t||M.redirectUri}});if(s)throw s;console.log("Verification email resent to:",e)}catch(s){throw console.error("Error resending verification email:",s),s}}async getUser(){let{data:e,error:t}=await this.supabase.auth.getUser();if(t)throw t;return e.user}async getSession(){let{data:e,error:t}=await this.supabase.auth.getSession();if(t)throw t;return e.session}};var pt=function(){return pt=Object.assign||function(i){for(var e,t=1,s=arguments.length;t<s;t++)for(var r in e=arguments[t])Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r]);return i},pt.apply(this,arguments)},ar=function(){function i(e,t,s){var r=this;this.endVal=t,this.options=s,this.version="2.9.0",this.defaults={startVal:0,decimalPlaces:0,duration:2,useEasing:!0,useGrouping:!0,useIndianSeparators:!1,smartEasingThreshold:999,smartEasingAmount:333,separator:",",decimal:".",prefix:"",suffix:"",enableScrollSpy:!1,scrollSpyDelay:200,scrollSpyOnce:!1},this.finalEndVal=null,this.useEasing=!0,this.countDown=!1,this.error="",this.startVal=0,this.paused=!0,this.once=!1,this.count=function(n){r.startTime||(r.startTime=n);var o=n-r.startTime;r.remaining=r.duration-o,r.useEasing?r.countDown?r.frameVal=r.startVal-r.easingFn(o,0,r.startVal-r.endVal,r.duration):r.frameVal=r.easingFn(o,r.startVal,r.endVal-r.startVal,r.duration):r.frameVal=r.startVal+(r.endVal-r.startVal)*(o/r.duration);var a=r.countDown?r.frameVal<r.endVal:r.frameVal>r.endVal;r.frameVal=a?r.endVal:r.frameVal,r.frameVal=Number(r.frameVal.toFixed(r.options.decimalPlaces)),r.printValue(r.frameVal),o<r.duration?r.rAF=requestAnimationFrame(r.count):r.finalEndVal!==null?r.update(r.finalEndVal):r.options.onCompleteCallback&&r.options.onCompleteCallback()},this.formatNumber=function(n){var o,a,c,h,l=n<0?"-":"";o=Math.abs(n).toFixed(r.options.decimalPlaces);var u=(o+="").split(".");if(a=u[0],c=u.length>1?r.options.decimal+u[1]:"",r.options.useGrouping){h="";for(var d=3,f=0,p=0,y=a.length;p<y;++p)r.options.useIndianSeparators&&p===4&&(d=2,f=1),p!==0&&f%d==0&&(h=r.options.separator+h),f++,h=a[y-p-1]+h;a=h}return r.options.numerals&&r.options.numerals.length&&(a=a.replace(/[0-9]/g,function(m){return r.options.numerals[+m]}),c=c.replace(/[0-9]/g,function(m){return r.options.numerals[+m]})),l+r.options.prefix+a+c+r.options.suffix},this.easeOutExpo=function(n,o,a,c){return a*(1-Math.pow(2,-10*n/c))*1024/1023+o},this.options=pt(pt({},this.defaults),s),this.formattingFn=this.options.formattingFn?this.options.formattingFn:this.formatNumber,this.easingFn=this.options.easingFn?this.options.easingFn:this.easeOutExpo,this.el=typeof e=="string"?document.getElementById(e):e,t=t??this.parse(this.el.innerHTML),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.endVal=this.validateValue(t),this.options.decimalPlaces=Math.max(this.options.decimalPlaces),this.resetDuration(),this.options.separator=String(this.options.separator),this.useEasing=this.options.useEasing,this.options.separator===""&&(this.options.useGrouping=!1),this.el?this.printValue(this.startVal):this.error="[CountUp] target is null or undefined",typeof window<"u"&&this.options.enableScrollSpy&&(this.error?console.error(this.error,e):(window.onScrollFns=window.onScrollFns||[],window.onScrollFns.push(function(){return r.handleScroll(r)}),window.onscroll=function(){window.onScrollFns.forEach(function(n){return n()})},this.handleScroll(this)))}return i.prototype.handleScroll=function(e){if(e&&window&&!e.once){var t=window.innerHeight+window.scrollY,s=e.el.getBoundingClientRect(),r=s.top+window.pageYOffset,n=s.top+s.height+window.pageYOffset;n<t&&n>window.scrollY&&e.paused?(e.paused=!1,setTimeout(function(){return e.start()},e.options.scrollSpyDelay),e.options.scrollSpyOnce&&(e.once=!0)):(window.scrollY>n||r>t)&&!e.paused&&e.reset()}},i.prototype.determineDirectionAndSmartEasing=function(){var e=this.finalEndVal?this.finalEndVal:this.endVal;this.countDown=this.startVal>e;var t=e-this.startVal;if(Math.abs(t)>this.options.smartEasingThreshold&&this.options.useEasing){this.finalEndVal=e;var s=this.countDown?1:-1;this.endVal=e+s*this.options.smartEasingAmount,this.duration=this.duration/2}else this.endVal=e,this.finalEndVal=null;this.finalEndVal!==null?this.useEasing=!1:this.useEasing=this.options.useEasing},i.prototype.start=function(e){this.error||(this.options.onStartCallback&&this.options.onStartCallback(),e&&(this.options.onCompleteCallback=e),this.duration>0?(this.determineDirectionAndSmartEasing(),this.paused=!1,this.rAF=requestAnimationFrame(this.count)):this.printValue(this.endVal))},i.prototype.pauseResume=function(){this.paused?(this.startTime=null,this.duration=this.remaining,this.startVal=this.frameVal,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count)):cancelAnimationFrame(this.rAF),this.paused=!this.paused},i.prototype.reset=function(){cancelAnimationFrame(this.rAF),this.paused=!0,this.resetDuration(),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.printValue(this.startVal)},i.prototype.update=function(e){cancelAnimationFrame(this.rAF),this.startTime=null,this.endVal=this.validateValue(e),this.endVal!==this.frameVal&&(this.startVal=this.frameVal,this.finalEndVal==null&&this.resetDuration(),this.finalEndVal=null,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count))},i.prototype.printValue=function(e){var t;if(this.el){var s=this.formattingFn(e);!((t=this.options.plugin)===null||t===void 0)&&t.render?this.options.plugin.render(this.el,s):this.el.tagName==="INPUT"?this.el.value=s:this.el.tagName==="text"||this.el.tagName==="tspan"?this.el.textContent=s:this.el.innerHTML=s}},i.prototype.ensureNumber=function(e){return typeof e=="number"&&!isNaN(e)},i.prototype.validateValue=function(e){var t=Number(e);return this.ensureNumber(t)?t:(this.error="[CountUp] invalid start or end value: ".concat(e),null)},i.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},i.prototype.parse=function(e){var t=function(o){return o.replace(/([.,'  ])/g,"\\$1")},s=t(this.options.separator),r=t(this.options.decimal),n=e.replace(new RegExp(s,"g"),"").replace(new RegExp(r,"g"),".");return parseFloat(n)},i}();var cr=!1;function lr(){if(cr)return;cr=!0;let i=document.querySelectorAll("[number-count]"),e=new IntersectionObserver(t=>{t.forEach(s=>{if(s.isIntersecting){let r=s.target;e.unobserve(r);let n=r.dataset.countDirection||"up",o=parseFloat(r.dataset.countOffset||"10")/100,a=parseFloat(r.dataset.countDuration||"2"),c=r.dataset.countTarget||r.textContent?.trim()||"0",h=parseFloat(c.replace(/,/g,""));if(isNaN(h))return;let l=n==="down"?h*(1+o):h*(1-o);new ar(r,h,{startVal:Math.round(l),duration:a,useGrouping:!0}).start()}})},{threshold:0});i.forEach(t=>{t.dataset.countTarget=t.textContent?.trim()||"0",e.observe(t)})}var hr=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var ur=(i,e)=>{window.posthog.capture(i,e)},dr=(i,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(i,e),console.log("ph user identified"))};async function bi(i){let t=new TextEncoder().encode(i.toLowerCase().trim()),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("")}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let i=setTimeout(()=>{document.body.style.visibility="visible"},4e3),e=new ft,{accessToken:t,refreshToken:s}=os(),r=document.querySelector("[stats-skeleton]"),n=document.querySelector("[stats-wrap]"),o=document.querySelector("[error-div]"),a=document.querySelector("[error-text]"),c=document.querySelector("[waitlist-rank]"),h=document.querySelector("[spots]"),l=document.querySelectorAll("[referral-code]"),u=document.querySelector("[referral-count]"),d=document.querySelector("[desktop-bonus-remaining]"),f=document.querySelector("[desktop-bonus-complete]"),p=document.querySelector("[climbed-dropped]"),y=document.querySelector("[keep-moving]"),m=document.querySelector("[rank-arrow-wrap]"),b=document.querySelector("[cohort-text]"),P=document.querySelector("[top-100]"),O=document.querySelector("[top-1000]"),x=document.querySelector("[top-100k]"),S=document.querySelector("[sms-bonus-remaining]"),Me=document.querySelector("[sms-bonus-complete]"),gt=document.querySelector("[social-media]"),Wt=document.querySelector("[social-media-details]");if(Wt&&gt&&Wt.addEventListener("click",()=>{gt.style.display="block",gt.scrollIntoView({behavior:"smooth"})}),localStorage.getItem("sms_submitted")==="true"?(S&&(S.style.display="none"),Me&&(Me.style.display="block")):(S&&(S.style.display="block"),Me&&(Me.style.display="none")),!t||!s){clearTimeout(i),window.location.href="/get-started?redirect=android-waitlist";return}try{e.setCookies(t,s);let mt=e.checkAndSetSession(),fr=new Promise((v,pe)=>setTimeout(()=>pe(new Error("Session timeout")),3e3));await Promise.race([mt,fr]),clearTimeout(i),document.body.style.visibility="visible";let Ve=e.sessionData?.user.email,pr=e.sessionData?.user.user_metadata.full_name||" ",[Kt,Yt]=rs(pr),Be=e.sessionData?.user.id;localStorage.setItem("email",Ve),Be&&localStorage.setItem("user_id",Be),Be&&dr(Be,{email:Ve,firstName:Kt,lastName:Yt});let gr=hr(),{dub_id:Qt,referral:Xt,promo_code:Zt}=gr;if(!localStorage.getItem("conversion_sent")){let v={access_token:t,first_name:Kt,last_name:Yt,dub_click_id:Qt||void 0,referral:Xt||void 0,promo_code:Zt||void 0};await ge.signupUser(v),await ge.ensureReferralCode(t),localStorage.setItem("conversion_sent","true")}let _t=!localStorage.getItem("android_waitlist_joined");if(_t){let v={email:Ve,device_type:"android"};await ge.addToWaitlist(v),localStorage.setItem("android_waitlist_joined","true"),ur("app_waitlist",{device_type:"android",source:"android-waitlist-page"})}let z=await ge.getAndroidWaitlistStats(t),mr=()=>{r&&(r.style.display="none"),n&&(n.style.display="block")};if(z.status===401||z.status===429||!z.ok){try{let v=await z.json();a&&(a.textContent=`Status: ${z.status} | ${JSON.stringify(v)}`)}catch{a&&(a.textContent=`Status: ${z.status} | Could not parse response`)}r&&(r.style.display="none"),o&&(o.style.display="block");return}let E=await z.json();if(_t){let v=await bi(Ve);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:E.current_rank,user_email_hash:v})}let es=localStorage.getItem("android_waitlist_last_rank");if(es&&!_t){let v=parseInt(es,10);E.current_rank<v&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:E.current_rank,positions_gained:v-E.current_rank,referral_count:E.referrals_count}))}if(localStorage.setItem("android_waitlist_last_rank",E.current_rank.toString()),c&&(c.textContent=E.current_rank.toLocaleString()),E.starting_rank!==null){let v=E.starting_rank-E.current_rank;h&&(h.textContent=Math.abs(v).toLocaleString()),v<0&&(p&&(p.textContent="fell"),y&&(y.style.display="none"),m&&m.classList.add("invert"))}let N=E.current_rank;if(N<=100?P&&P.classList.add("active"):N<=1e3?O&&O.classList.add("active"):N<=1e5&&x&&x.classList.add("active"),b)if(N<=100)b.innerHTML="You're in the <strong>top 100!</strong>";else if(N<=1e3){let v=N-100;b.innerHTML=`<strong>Only ${v.toLocaleString()} spots</strong> to top 100`}else if(N<=1e5){let v=N-1e3;b.innerHTML=`<strong>Only ${v.toLocaleString()} spots</strong> to top 1,000`}else{let v=N-1e5;b.innerHTML=`<strong>Only ${v.toLocaleString()} spots</strong> to top 100,000`}l.forEach(v=>{v.textContent=E.referral_code}),u&&(u.textContent=E.referrals_count.toString()),E.desktop_dictation_bonus_earned?(d&&(d.style.display="none"),f&&(f.style.display="block")):(d&&(d.style.display="block"),f&&(f.style.display="none"));let _r=`https://wisprflow.ai/r?${E.referral_code}`;document.querySelectorAll("[share]").forEach(v=>{let pe=v.getAttribute("share");if(!pe)return;let yt=document.querySelector(`[share-content="${pe}"]`)?.textContent||"";v.addEventListener("click",async()=>{switch(pe){case"x":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(yt)}`,"_blank");break;case"linkedin":window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(_r)}`,"_blank");break;case"whatsapp":window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(yt)}`,"_blank");break;case"slack":await navigator.clipboard.writeText(yt),window.open("slack://open","_self");break}})}),mr(),lr()}catch(mt){console.error("Error on android-waitlist page:",mt),clearTimeout(i),window.location.href="/get-started?redirect=android-waitlist"}});})();
1
+ "use strict";(()=>{var wr=Object.create;var He=Object.defineProperty;var vr=Object.getOwnPropertyDescriptor;var br=Object.getOwnPropertyNames;var kr=Object.getPrototypeOf,Sr=Object.prototype.hasOwnProperty;var Er=(i,e)=>()=>(i&&(e=i(i=0)),e);var $=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Tr=(i,e)=>{for(var t in e)He(i,t,{get:e[t],enumerable:!0})},ss=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of br(e))!Sr.call(i,r)&&r!==t&&He(i,r,{get:()=>e[r],enumerable:!(s=vr(e,r))||s.enumerable});return i};var rs=(i,e,t)=>(t=i!=null?wr(kr(i)):{},ss(e||!i||!i.__esModule?He(t,"default",{value:i,enumerable:!0}):t,i)),xr=i=>ss(He({},"__esModule",{value:!0}),i);var G={};Tr(G,{Headers:()=>kt,Request:()=>Rr,Response:()=>Pr,default:()=>bt,fetch:()=>Or});var Ar,ie,Or,bt,kt,Rr,Pr,V=Er(()=>{"use strict";Ar=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},ie=Ar(),Or=ie.fetch,bt=ie.fetch.bind(ie),kt=ie.Headers,Rr=ie.Request,Pr=ie.Response});var ls=$(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});var St=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Et.default=St});var xt=$(ye=>{"use strict";var hs=ye&&ye.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ye,"__esModule",{value:!0});var jr=hs((V(),xr(G))),$r=hs(ls()),Tt=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=jr.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,r=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let h=null,l=null,u=null,d=n.status,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let b=await n.text();b===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=b:l=JSON.parse(b))}let y=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),m=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");y&&m&&m.length>1&&(u=parseInt(m[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(h={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,u=null,d=406,f="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let y=await n.text();try{h=JSON.parse(y),Array.isArray(h)&&n.status===404&&(l=[],h=null,d=200,f="OK")}catch{n.status===404&&y===""?(d=204,f="No Content"):h={message:y}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new $r.default(h)}return{error:h,data:l,count:u,status:d,statusText:f}});return this.shouldThrowOnError||(r=r.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}};ye.default=Tt});var Ot=$(we=>{"use strict";var Ir=we&&we.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(we,"__esModule",{value:!0});var Lr=Ir(xt()),At=class extends Lr.default{select(e){let t=!1,s=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:r,referencedTable:n=r}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let r=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){let n=typeof r>"u"?"offset":`${r}.offset`,o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:r=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,n?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};we.default=At});var Ke=$(ve=>{"use strict";var Ur=ve&&ve.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ve,"__esModule",{value:!0});var Dr=Ur(Ot()),Rt=class extends Dr.default{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}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(r=>typeof r=="string"&&new RegExp("[,()]").test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?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 typeof t=="string"?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 typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:r}={}){let n="";r==="plain"?n="pl":r==="phrase"?n="ph":r==="websearch"&&(n="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};ve.default=Rt});var Ct=$(ke=>{"use strict";var Nr=ke&&ke.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ke,"__esModule",{value:!0});var be=Nr(Ke()),Pt=class{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=t,this.schema=s,this.fetch=r}select(e,{head:t=!1,count:s}={}){let r=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new be.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let r="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new be.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),r&&a.push(`count=${r}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((h,l)=>h.concat(Object.keys(l)),[]);if(c.length>0){let h=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",h.join(","))}}return new be.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",r=[];return this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new be.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new be.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ke.default=Pt});var us=$(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.version=void 0;Ye.version="0.0.0-automated"});var ds=$(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.DEFAULT_HEADERS=void 0;var Fr=us();Qe.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Fr.version}`}});var ps=$(Se=>{"use strict";var fs=Se&&Se.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Se,"__esModule",{value:!0});var qr=fs(Ct()),Mr=fs(Ke()),Vr=ds(),jt=class i{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=Object.assign(Object.assign({},Vr.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=r}from(e){let t=new URL(`${this.url}/${e}`);return new qr.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new i(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:r=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||r?(o=s?"HEAD":"GET",Object.entries(t).filter(([l,u])=>u!==void 0).map(([l,u])=>[l,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([l,u])=>{a.searchParams.append(l,u)})):(o="POST",c=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new Mr.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};Se.default=jt});var vs=$(T=>{"use strict";var Ee=T&&T.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(T,"__esModule",{value:!0});T.PostgrestBuilder=T.PostgrestTransformBuilder=T.PostgrestFilterBuilder=T.PostgrestQueryBuilder=T.PostgrestClient=void 0;var gs=Ee(ps());T.PostgrestClient=gs.default;var ms=Ee(Ct());T.PostgrestQueryBuilder=ms.default;var _s=Ee(Ke());T.PostgrestFilterBuilder=_s.default;var ys=Ee(Ot());T.PostgrestTransformBuilder=ys.default;var ws=Ee(xt());T.PostgrestBuilder=ws.default;T.default={PostgrestClient:gs.default,PostgrestQueryBuilder:ms.default,PostgrestFilterBuilder:_s.default,PostgrestTransformBuilder:ys.default,PostgrestBuilder:ws.default}});var Rs=$((pn,Os)=>{"use strict";Os.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var I="https://api.wisprflow.ai",vt=class{static async signupUser(e){try{let t=`${I}/signup`,r=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=r&&r.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${I}/signup_raw_email`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Adding raw user failed with status ${t.status}`);return console.log("Added raw user successfully"),await t.json()}catch(t){throw console.error("Error during raw user signup:",t),t}}static async addToWaitlist(e){try{let t=await fetch(`${I}/add_to_waitlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying waitlist failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async applyReferralCode(e){try{let t=await fetch(`${I}/api/v1/referral/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying referral code failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async associateAppSumoLicense(e){try{let t=await fetch("https://api.wisprflow.ai/app_sumo/associate_license_key",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}static async checkUserStatus(e){return await(await fetch(`${I}/user_status?email=${encodeURIComponent(e)}`)).json()}static async getSubscriptionStatus(e){return await fetch(`${I}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${I}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s){let r=`${I}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(r+=`&currency=${s}`),await(await fetch(r,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${I}/api/v1/referral/download-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:e,recipient_email:t})})}static async getAndroidWaitlistStats(e){return await fetch("https://api-east.wisprflow.ai/api/v1/promos/android_waitlist_rank",{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${I}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}};function is(i){let[e,...t]=i.split(" "),s=t.join(" ");return[e,s]}var ge=vt;var ns=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var os=()=>{let i=window.location.hash.substring(1),e=new URLSearchParams(i);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var as=()=>{let{access_token:i,refresh_token:e}=os(),t=i,s=e;if(!t||!s){let r=ns();t=r.access_token,s=r.refresh_token}return{accessToken:t,refreshToken:s}};var cs=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(V(),G)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var me=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},ze=class extends me{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Ge=class extends me{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Je=class extends me{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},We;(function(i){i.Any="any",i.ApNortheast1="ap-northeast-1",i.ApNortheast2="ap-northeast-2",i.ApSouth1="ap-south-1",i.ApSoutheast1="ap-southeast-1",i.ApSoutheast2="ap-southeast-2",i.CaCentral1="ca-central-1",i.EuCentral1="eu-central-1",i.EuWest1="eu-west-1",i.EuWest2="eu-west-2",i.EuWest3="eu-west-3",i.SaEast1="sa-east-1",i.UsEast1="us-east-1",i.UsWest1="us-west-1",i.UsWest2="us-west-2"})(We||(We={}));var Cr=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},_e=class{constructor(e,{headers:t={},customFetch:s,region:r=We.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=cs(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Cr(this,void 0,void 0,function*(){try{let{headers:r,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let h;o&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData<"u"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),r),body:h}).catch(p=>{throw new ze(p)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new Ge(l);if(!l.ok)throw new Je(l);let d=((s=l.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield l.json():d==="application/octet-stream"?f=yield l.blob():d==="text/event-stream"?f=l:d==="multipart/form-data"?f=yield l.formData():f=yield l.text(),{data:f,error:null}}catch(r){return{data:null,error:r}}})}};var bs=rs(vs(),1),{PostgrestClient:ks,PostgrestQueryBuilder:Wi,PostgrestFilterBuilder:Ki,PostgrestTransformBuilder:Yi,PostgrestBuilder:Qi}=bs.default;var Ss="2.10.2";var Es={"X-Client-Info":`realtime-js/${Ss}`},Ts="1.0.0",Ze=1e4,xs=1e3,J;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(J||(J={}));var A;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})(A||(A={}));var R;(function(i){i.close="phx_close",i.error="phx_error",i.join="phx_join",i.reply="phx_reply",i.leave="phx_leave",i.access_token="access_token"})(R||(R={}));var Xe;(function(i){i.websocket="websocket"})(Xe||(Xe={}));var B;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(B||(B={}));var Te=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let r=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+r));o=o+r;let c=s.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:h}}};var W=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}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))}};var w;(function(i){i.abstime="abstime",i.bool="bool",i.date="date",i.daterange="daterange",i.float4="float4",i.float8="float8",i.int2="int2",i.int4="int4",i.int4range="int4range",i.int8="int8",i.int8range="int8range",i.json="json",i.jsonb="jsonb",i.money="money",i.numeric="numeric",i.oid="oid",i.reltime="reltime",i.text="text",i.time="time",i.timestamp="timestamp",i.timestamptz="timestamptz",i.timetz="timetz",i.tsrange="tsrange",i.tstzrange="tstzrange"})(w||(w={}));var It=(i,e,t={})=>{var s;let r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Br(o,i,e,r),n),{})},Br=(i,e,t,s)=>{let r=e.find(a=>a.name===i),n=r?.type,o=t[i];return n&&!s.includes(n)?As(n,o):$t(o)},As=(i,e)=>{if(i.charAt(0)==="_"){let t=i.slice(1,i.length);return Jr(e,t)}switch(i){case w.bool:return Hr(e);case w.float4:case w.float8:case w.int2:case w.int4:case w.int8:case w.numeric:case w.oid:return zr(e);case w.json:case w.jsonb:return Gr(e);case w.timestamp:return Wr(e);case w.abstime:case w.date:case w.daterange:case w.int4range:case w.int8range:case w.money:case w.reltime:case w.text:case w.time:case w.timestamptz:case w.timetz:case w.tsrange:case w.tstzrange:return $t(e);default:return $t(e)}},$t=i=>i,Hr=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},zr=i=>{if(typeof i=="string"){let e=parseFloat(i);if(!Number.isNaN(e))return e}return i},Gr=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},Jr=(i,e)=>{if(typeof i!="string")return i;let t=i.length-1,s=i[t];if(i[0]==="{"&&s==="}"){let n,o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>As(e,a))}return i},Wr=i=>typeof i=="string"?i.replace(" ","T"):i,et=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var K=class{constructor(e,t,s={},r=Ze){this.channel=e,this.event=t,this.payload=s,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,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()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Lt;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(Lt||(Lt={}));var ne=class i{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=i.syncState(this.state,r,n,o),this.pendingDiffs.forEach(c=>{this.state=i.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},r=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=i.syncDiff(this.state,r,n,o),a())}),this.onJoin((r,n,o)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:n,newPresences:o})}),this.onLeave((r,n,o)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(h,l)=>{o[h]||(c[h]=l)}),this.map(o,(h,l)=>{let u=n[h];if(u){let d=l.map(m=>m.presence_ref),f=u.map(m=>m.presence_ref),p=l.filter(m=>f.indexOf(m.presence_ref)<0),y=u.filter(m=>d.indexOf(m.presence_ref)<0);p.length>0&&(a[h]=p),y.length>0&&(c[h]=y)}else a[h]=l}),this.syncDiff(n,{joins:a,leaves:c},s,r)}static syncDiff(e,t,s,r){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(n,(a,c)=>{var h;let l=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(c),l.length>0){let u=e[a].map(f=>f.presence_ref),d=l.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}s(a,l,c)}),this.map(o,(a,c)=>{let h=e[a];if(!h)return;let l=c.map(u=>u.presence_ref);h=h.filter(u=>l.indexOf(u.presence_ref)<0),e[a]=h,r(a,h,c),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let r=e[s];return"metas"in r?t[s]=r.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=r,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var Ut;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(Ut||(Ut={}));var Dt;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes"})(Dt||(Dt={}));var Nt;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(Nt||(Nt={}));var oe=class i{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=A.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new K(this,R.join,this.params,this.timeout),this.rejoinTimer=new W(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=A.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=A.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=A.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=A.errored,this.rejoinTimer.scheduleTimeout())}),this._on(R.reply,{},(r,n)=>{this._trigger(this._replyEventName(n),r)}),this.presence=new ne(this),this.broadcastEndpointURL=et(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,r;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},h={broadcast:n,presence:o,postgres_changes:(r=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(l=>l.filter))!==null&&r!==void 0?r:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:h},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,f=(u=d?.length)!==null&&u!==void 0?u:0,p=[];for(let y=0;y<f;y++){let m=d[y],{filter:{event:b,schema:P,table:O,filter:x}}=m,S=l&&l[y];if(S&&S.event===b&&S.schema===P&&S.table===O&&S.filter===x)p.push(Object.assign(Object.assign({},m),{id:S.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=p,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,r;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((r=c.body)===null||r===void 0?void 0:r.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),h.receive("ok",()=>n("ok")),h.receive("error",()=>n("error")),h.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=A.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(R.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let r=new K(this,R.leave,{},e);r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let r=new AbortController,n=setTimeout(()=>r.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new K(this,e,t,s);return this._canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:h,join:l}=R;if(s&&[a,c,h,l].indexOf(o)>=0&&s!==this._joinRef())return;let d=this._onMessage(o,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(r=this.bindings.postgres_changes)===null||r===void 0||r.filter(f=>{var p,y,m;return((p=f.filter)===null||p===void 0?void 0:p.event)==="*"||((m=(y=f.filter)===null||y===void 0?void 0:y.event)===null||m===void 0?void 0:m.toLocaleLowerCase())===o}).map(f=>f.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var p,y,m,b,P,O;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let x=f.id,S=(p=f.filter)===null||p===void 0?void 0:p.event;return x&&((y=t.ids)===null||y===void 0?void 0:y.includes(x))&&(S==="*"||S?.toLocaleLowerCase()===((m=t.data)===null||m===void 0?void 0:m.type.toLocaleLowerCase()))}else{let x=(P=(b=f?.filter)===null||b===void 0?void 0:b.event)===null||P===void 0?void 0:P.toLocaleLowerCase();return x==="*"||x===((O=t?.event)===null||O===void 0?void 0:O.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let p=d.data,{schema:y,table:m,commit_timestamp:b,type:P,errors:O}=p;d=Object.assign(Object.assign({},{schema:y,table:m,commit_timestamp:b,eventType:P,new:{},old:{},errors:O}),this._getPayloadRecords(p))}f.callback(d,s)})}_isClosed(){return this.state===A.closed}_isJoined(){return this.state===A.joined}_isJoining(){return this.state===A.joining}_isLeaving(){return this.state===A.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let r=e.toLocaleLowerCase(),n={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(n):this.bindings[r]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(r=>{var n;return!(((n=r.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&i.isEqual(r.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(R.close,{},e)}_onError(e){this._on(R.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=A.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=It(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=It(e.columns,e.old_record)),t}};var Yr=()=>{},Qr=typeof WebSocket<"u",ae=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Es,this.params={},this.timeout=Ze,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Yr,this.conn=null,this.sendBuffer=[],this.serializer=new Te,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(V(),G)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Xe.websocket}`,this.httpEndpoint=et(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let r=(s=t?.params)===null||s===void 0?void 0:s.apikey;r&&(this.accessToken=r,this.apiKey=r),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new W(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(Qr){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Ft(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>rs(Rs())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case J.connecting:return B.Connecting;case J.open:return B.Open;case J.closing:return B.Closing;default:return B.Closed}}isConnected(){return this.connectionState()===B.Open}channel(e,t={config:{}}){let s=new oe(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:r,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${s} (${n})`,r),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(R.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",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))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Ts}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:r,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||r===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${r} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(r,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(R.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",r=new URLSearchParams(t);return`${e}${s}${r}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(xs,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Ft=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=J.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var ce=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function k(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}var tt=class extends ce{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},xe=class extends ce{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Xr=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},st=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(V(),G)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Ps=()=>Xr(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(V(),G))).Response:Response});var le=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},qt=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Zr=(i,e)=>le(void 0,void 0,void 0,function*(){let t=yield Ps();i instanceof t?i.json().then(s=>{e(new tt(qt(s),i.status||500))}).catch(s=>{e(new xe(qt(s),s))}):e(new xe(qt(i),i))}),ei=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};function rt(i,e,t,s,r,n){return le(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,ei(e,s,r,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Zr(c,a))})})}function Ae(i,e,t,s){return le(this,void 0,void 0,function*(){return rt(i,"GET",e,t,s)})}function L(i,e,t,s,r){return le(this,void 0,void 0,function*(){return rt(i,"POST",e,s,r,t)})}function Cs(i,e,t,s,r){return le(this,void 0,void 0,function*(){return rt(i,"PUT",e,s,r,t)})}function it(i,e,t,s,r){return le(this,void 0,void 0,function*(){return rt(i,"DELETE",e,s,r,t)})}var C=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},ti={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},js={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Oe=class{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=st(r)}uploadOrUpdate(e,t,s,r){return C(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},js),r),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),h=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield l.json();return l.ok?{data:{path:c,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(k(n))return{data:null,error:n};throw n}})}upload(e,t,s){return C(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return C(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,h=Object.assign({upsert:js.upsert},r),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",h.cacheControl)):(c=s,l["cache-control"]=`max-age=${h.cacheControl}`,l["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(k(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return C(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),r=Object.assign({},this.headers);t?.upsert&&(r["x-upsert"]="true");let n=yield L(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new ce("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}update(e,t,s){return C(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return C(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}copy(e,t,s){return C(this,void 0,void 0,function*(){try{return{data:{path:(yield L(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return C(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),n=yield L(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return C(this,void 0,void 0,function*(){try{let r=yield L(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:r.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}download(e,t){return C(this,void 0,void 0,function*(){let r=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield Ae(this.fetch,`${this.url}/${r}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(k(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),r=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&r.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&r.push(c);let h=r.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${h}`)}}}remove(e){return C(this,void 0,void 0,function*(){try{return{data:yield it(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}list(e,t,s){return C(this,void 0,void 0,function*(){try{let r=Object.assign(Object.assign(Object.assign({},ti),t),{prefix:e||""});return{data:yield L(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var $s="2.6.0";var Is={"X-Client-Info":`storage-js/${$s}`};var he=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},Re=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},Is),t),this.fetch=st(s)}listBuckets(){return he(this,void 0,void 0,function*(){try{return{data:yield Ae(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(k(e))return{data:null,error:e};throw e}})}getBucket(e){return he(this,void 0,void 0,function*(){try{return{data:yield Ae(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return he(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return he(this,void 0,void 0,function*(){try{return{data:yield Cs(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}emptyBucket(e){return he(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}deleteBucket(e){return he(this,void 0,void 0,function*(){try{return{data:yield it(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}};var Pe=class extends Re{constructor(e,t={},s){super(e,t,s)}from(e){return new Oe(this.url,this.headers,e,this.fetch)}};var Ls="2.44.4";var Ce="";typeof Deno<"u"?Ce="deno":typeof document<"u"?Ce="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ce="react-native":Ce="node";var si={"X-Client-Info":`supabase-js-${Ce}/${Ls}`},Us={headers:si},Ds={schema:"public"},Ns={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Fs={};V();var ri=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},ii=i=>{let e;return i?e=i:typeof fetch>"u"?e=bt:e=fetch,(...t)=>e(...t)},ni=()=>typeof Headers>"u"?kt:Headers,qs=(i,e,t)=>{let s=ii(t),r=ni();return(n,o)=>ri(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:i,h=new r(o?.headers);return h.has("apikey")||h.set("apikey",i),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:h}))})};function Ms(i){return i.replace(/\/$/,"")}function Vs(i,e){let{db:t,auth:s,realtime:r,global:n}=i,{db:o,auth:a,realtime:c,global:h}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),r),global:Object.assign(Object.assign({},h),n)}}var nt="2.64.4";var Bs="http://localhost:9999",Hs="supabase.auth.token";var zs={"X-Client-Info":`gotrue-js/${nt}`},Mt=10;var je="X-Supabase-Api-Version",Vt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Gs(i){return Math.round(Date.now()/1e3)+i}function Js(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){let e=Math.random()*16|0;return(i=="x"?e:e&3|8).toString(16)})}var j=()=>typeof document<"u",Y={tested:!1,writable:!1},H=()=>{if(!j())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Y.tested)return Y.writable;let i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),Y.tested=!0,Y.writable=!0}catch{Y.tested=!0,Y.writable=!1}return Y.writable};function ot(i){let e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,n)=>{e[n]=r})}catch{}return t.searchParams.forEach((s,r)=>{e[r]=s}),e}var at=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(V(),G)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Ws=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",Bt=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},Ie=async(i,e)=>{let t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},ct=async(i,e)=>{await i.removeItem(e)};function oi(i){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,r,n,o,a,c,h,l=0;for(i=i.replace("-","+").replace("_","/");l<i.length;)o=e.indexOf(i.charAt(l++)),a=e.indexOf(i.charAt(l++)),c=e.indexOf(i.charAt(l++)),h=e.indexOf(i.charAt(l++)),s=o<<2|a>>4,r=(a&15)<<4|c>>2,n=(c&3)<<6|h,t=t+String.fromCharCode(s),c!=64&&r!=0&&(t=t+String.fromCharCode(r)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var $e=class i{constructor(){this.promise=new i.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};$e.promiseConstructor=Promise;function Ht(i){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=i.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let s=t[1];return JSON.parse(oi(s))}async function Ks(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function Ys(i,e){return new Promise((s,r)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await i(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){r(o);return}}})()})}function ai(i){return("0"+i.toString(16)).substr(-2)}function ci(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,r="";for(let n=0;n<56;n++)r+=t.charAt(Math.floor(Math.random()*s));return r}return crypto.getRandomValues(e),Array.from(e,ai).join("")}async function li(i){let t=new TextEncoder().encode(i),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(n=>String.fromCharCode(n)).join("")}function hi(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ui(i){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),i;let t=await li(i);return hi(t)}async function Q(i,e,t=!1){let s=ci(),r=s;t&&(r+="/PASSWORD_RECOVERY"),await Bt(i,`${e}-code-verifier`,r);let n=await ui(s);return[n,s===n?"plain":"s256"]}var di=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Qs(i){let e=i.headers.get(je);if(!e||!e.match(di))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Le=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function g(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}var lt=class extends Le{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function Xs(i){return g(i)&&i.name==="AuthApiError"}var ue=class extends Le{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},F=class extends Le{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}},U=class extends F{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},de=class extends F{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},X=class extends F{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Z=class extends F{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},Ue=class extends F{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},fe=class extends F{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function ht(i){return g(i)&&i.name==="AuthRetryableFetchError"}var De=class extends F{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var fi=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},ee=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),pi=[502,503,504];async function Zs(i){var e;if(!Ws(i))throw new fe(ee(i),0);if(pi.includes(i.status))throw new fe(ee(i),i.status);let t;try{t=await i.json()}catch(n){throw new ue(ee(n),n)}let s,r=Qs(i);if(r&&r.getTime()>=Vt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new De(ee(t),i.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new De(ee(t),i.status,t.weak_password.reasons);throw new lt(ee(t),i.status||500,s)}var gi=(i,e,t,s)=>{let r={method:i,headers:e?.headers||{}};return i==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function _(i,e,t,s){var r;let n=Object.assign({},s?.headers);n[je]||(n[je]=Vt["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(r=s?.query)!==null&&r!==void 0?r:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await mi(i,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function mi(i,e,t,s,r,n){let o=gi(e,s,r,n),a;try{a=await i(t,Object.assign({},o))}catch(c){throw console.error(c),new fe(ee(c),0)}if(a.ok||await Zs(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await Zs(c)}}function q(i){var e;let t=null;_i(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=Gs(i.expires_in)));let s=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:s},error:null}}function zt(i){let e=q(i);return!e.error&&i.weak_password&&typeof i.weak_password=="object"&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.message&&typeof i.weak_password.message=="string"&&i.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=i.weak_password),e}function D(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function er(i){return{data:i,error:null}}function tr(i){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n}=i,o=fi(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function sr(i){return i}function _i(i){return i.access_token&&i.refresh_token&&i.expires_in}var yi=function(i,e){var t={};for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&e.indexOf(s)<0&&(t[s]=i[s]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(i);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(i,s[r])&&(t[s[r]]=i[s[r]]);return t},te=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=at(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await _(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(g(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await _(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:D})}catch(s){if(g(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=yi(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s?.newEmail,delete r.newEmail),await _(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:tr,redirectTo:t?.redirectTo})}catch(t){if(g(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await _(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:D})}catch(t){if(g(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,n,o,a,c;try{let h={nextPage:null,lastPage:0,total:0},l=await _(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(r=e?.perPage)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""},xform:sr});if(l.error)throw l.error;let u=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(p=>{let y=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(p.split(";")[1].split("=")[1]);h[`${m}Page`]=y}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(g(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await _(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:D})}catch(t){if(g(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await _(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:D})}catch(s){if(g(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await _(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:D})}catch(s){if(g(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await _(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:r=>({data:{factors:r},error:null})});return{data:t,error:s}}catch(t){if(g(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await _(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(g(t))return{data:null,error:t};throw t}}};var rr={getItem:i=>H()?globalThis.localStorage.getItem(i):null,setItem:(i,e)=>{H()&&globalThis.localStorage.setItem(i,e)},removeItem:i=>{H()&&globalThis.localStorage.removeItem(i)}};function Gt(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function ir(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var se={debug:!!(globalThis&&H()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Ne=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},ut=class extends Ne{};async function Jt(i,e,t){se.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),se.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",i)},e),await globalThis.navigator.locks.request(i,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async r=>{if(r){se.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,r.name);try{return await t()}finally{se.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,r.name)}}else{if(e===0)throw se.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new ut(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(se.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}ir();var wi={url:Bs,storageKey:Hs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:zs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Fe=30*1e3,nr=3;async function or(i,e,t){return await t()}var re=class i{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=i.nextInstanceID,i.nextInstanceID+=1,this.instanceID>0&&j()&&console.warn("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.");let r=Object.assign(Object.assign({},wi),e);if(this.logDebugMessages=!!r.debug,typeof r.debug=="function"&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new te({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=at(r.fetch),this.lock=r.lock||or,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:j()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Jt:this.lock=or,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)},this.persistSession?r.storage?this.storage=r.storage:H()?this.storage=rr:(this.memoryStorage={},this.storage=Gt(this.memoryStorage)):(this.memoryStorage={},this.storage=Gt(this.memoryStorage)),j()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${nt}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=j()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:r,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",r,"redirect type",n),await this._saveSession(r),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",r):await this._notifyAllSubscribers("SIGNED_IN",r)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return g(e)?{error:e}:{error:new ue("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{let n=await _(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}},xform:q}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(g(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,r;try{let n;if("email"in e){let{email:l,password:u,options:d}=e,f=null,p=null;this.flowType==="pkce"&&([f,p]=await Q(this.storage,this.storageKey)),n=await _(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:p},xform:q})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await _(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:u,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(r=d?.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:q})}else throw new X("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(g(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await _(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:zt})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await _(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:zt})}else throw new X("You must provide either an email or phone number and a password");let{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new de}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r})}catch(t){if(g(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(r=e.options)===null||r===void 0?void 0:r.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Ie(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/"),{data:n,error:o}=await _(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:q});return await ct(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new de}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:r??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:r,access_token:n,nonce:o}=e,a=await _(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:q}),{data:c,error:h}=a;return h?{data:{user:null,session:null},error:h}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new de}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(g(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,n,o;try{if("email"in e){let{email:a,options:c}=e,h=null,l=null;this.flowType==="pkce"&&([h,l]=await Q(this.storage,this.storageKey));let{error:u}=await _(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:h,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:c}=e,{data:h,error:l}=await _(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(r=c?.data)!==null&&r!==void 0?r:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:l}}throw new X("You must provide either an email or phone number.")}catch(a){if(g(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let r,n;"options"in e&&(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await _(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:r,xform:q});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(r){if(g(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Q(this.storage,this.storageKey)),await _(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:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:er})}catch(n){if(g(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new U;let{error:r}=await _(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(g(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:r,options:n}=e,{error:o}=await _(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:r,options:n}=e,{data:o,error:a}=await _(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new X("You must provide either an email or phone number and a type")}catch(t){if(g(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch{}})()),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 s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let r=[...this.pendingInLock];await Promise.all(r),this.pendingInLock.splice(0,r.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Ie(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,h,l)=>(!o&&h==="user"&&(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 many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,h,l))})}return{data:{session:e},error:null}}let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await _(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:D}):await this._useSession(async t=>{var s,r,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new U}:await _(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:void 0,xform:D})})}catch(t){if(g(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:r,error:n}=s;if(n)throw n;if(!r.session)throw new U;let o=r.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await Q(this.storage,this.storageKey));let{data:h,error:l}=await _(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:D});if(l)throw l;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(g(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return Ht(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new U;let t=Date.now()/1e3,s=t,r=!0,n=null,o=Ht(e.access_token);if(o.exp&&(s=o.exp,r=s<=t),r){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(g(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new U;let{session:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(g(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!j())throw new Z("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Z("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Ue("Not a valid PKCE flow url.");let t=ot(window.location.href);if(e){if(!t.code)throw new Ue("No code detected.");let{data:P,error:O}=await this._exchangeCodeForSession(t.code);if(O)throw O;let x=new URL(window.location.href);return x.searchParams.delete("code"),window.history.replaceState(window.history.state,"",x.toString()),{data:{session:P.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Z(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:r,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:h}=t;if(!n||!a||!o||!h)throw new Z("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;c&&(d=parseInt(c));let f=d-l;f*1e3<=Fe&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let p=d-u;l-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,d,l):l-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",p,d,l);let{data:y,error:m}=await this._getUser(n);if(m)throw m;let b={provider_token:s,provider_refresh_token:r,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:b,redirectType:t.type},error:null}}catch(t){if(g(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=ot(window.location.href);return!!(j()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=ot(window.location.href),t=await Ie(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:r,error:n}=t;if(n)return{error:n};let o=(s=r.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Xs(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await ct(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Js(),s={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,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;try{let{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;this.flowType==="pkce"&&([s,r]=await Q(this.storage,this.storageKey,!0));try{return await _(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(g(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(g(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:r}=await this._useSession(async n=>{var o,a,c,h,l;let{data:u,error:d}=n;if(d)throw d;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await _(this.fetch,"GET",f,{headers:this.headers,jwt:(l=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&l!==void 0?l:void 0})});if(r)throw r;return j()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(g(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;let{data:n,error:o}=t;if(o)throw o;return await _(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(r=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&r!==void 0?r:void 0})})}catch(t){if(g(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await Ys(async r=>(r>0&&await Ks(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await _(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:q})),(r,n)=>{let o=200*Math.pow(2,r);return n&&ht(n)&&Date.now()+o-s<Fe})}catch(s){if(this._debug(t,"error",s),g(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let 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",s),j()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await Ie(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let r=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<r+Mt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Mt}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),ht(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new U;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new $e;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new U;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(r,"error",n),g(n)){let o={session:null,error:n};return ht(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){let r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Bt(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await ct(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&j()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Fe);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let r=Math.floor((s.expires_at*1e3-e)/Fe);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${Fe}ms, refresh threshold is ${nr} ticks`),r<=nr&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Ne)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!j()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let r=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await Q(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);r.push(n.toString())}return s?.skipBrowserRedirect&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await _(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(g(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,r;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await _(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((r=a?.totp)===null||r===void 0)&&r.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(g(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await _(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(g(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:r,error:n}=t;return n?{data:null,error:n}:await _(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(g(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],r=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:r},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:r},error:n}=e;if(n)return{data:null,error:n};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(r.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=r.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};re.nextInstanceID=0;var vi=re,Wt=vi;var dt=class extends Wt{constructor(e){super(e)}};var bi=function(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):r(l.value).then(a,c)}h((s=s.apply(i,e||[])).next())})},qe=class{constructor(e,t,s){var r,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=Ms(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:Ds,realtime:Fs,auth:Object.assign(Object.assign({},Ns),{storageKey:c}),global:Us},l=Vs(s??{},h);this.storageKey=(r=l.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=qs(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new ks(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new _e(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Pe(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}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()}_getAccessToken(){var e,t;return bi(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,storageKey:n,flowType:o,debug:a},c,h){var l;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new dt({url:this.authUrl,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new ae(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var ar=(i,e,t)=>new qe(i,e,t);var M={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var ft=class{constructor(){this.sessionData=null;this.supabase=ar(M.supaBaseUrl,M.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||M.redirectUri}}),console.log("Signed in with Google")}catch(t){throw console.error("Error signing in with Google:",t),t}}async signInWithApple(e){try{await this.supabase.auth.signInWithOAuth({provider:"apple",options:{redirectTo:e||M.redirectUri}}),console.log("Signed in with Apple")}catch(t){throw console.error("Error signing in with Apple:",t),t}}async signInWithMicrosoft(e){try{await this.supabase.auth.signInWithOAuth({provider:"azure",options:{redirectTo:e||M.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:r}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(r)throw r;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw this.signOut(),console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let r=new Date;r.setTime(r.getTime()+s*24*60*60*1e3);let n=`expires=${r.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,s=e.refresh_token;if(t&&s)try{await this.setSession(t,s)}catch(r){throw r}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,r]=t.split("=");return e[s]=r,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||M.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,r,n){try{let{error:o}=await this.supabase.auth.signUp({email:e,password:t,options:{emailRedirectTo:r||M.redirectUri,data:{full_name:s},captchaToken:n}});if(o)throw o;console.log("Signup successful, verification email sent to:",e)}catch(o){throw console.error("Error signing up:",o),o}}async signInWithPassword(e,t,s){try{let{data:r,error:n}=await this.supabase.auth.signInWithPassword({email:e,password:t,options:{captchaToken:s}});if(n)throw n;if(!r.session)throw new Error("No session returned from sign in");return console.log("Sign in successful for:",e),{accessToken:r.session.access_token,refreshToken:r.session.refresh_token}}catch(r){throw console.error("Error signing in with password:",r),r}}async resendVerificationEmail(e,t){try{let{error:s}=await this.supabase.auth.resend({type:"signup",email:e,options:{emailRedirectTo:t||M.redirectUri}});if(s)throw s;console.log("Verification email resent to:",e)}catch(s){throw console.error("Error resending verification email:",s),s}}async getUser(){let{data:e,error:t}=await this.supabase.auth.getUser();if(t)throw t;return e.user}async getSession(){let{data:e,error:t}=await this.supabase.auth.getSession();if(t)throw t;return e.session}};var pt=function(){return pt=Object.assign||function(i){for(var e,t=1,s=arguments.length;t<s;t++)for(var r in e=arguments[t])Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=e[r]);return i},pt.apply(this,arguments)},cr=function(){function i(e,t,s){var r=this;this.endVal=t,this.options=s,this.version="2.9.0",this.defaults={startVal:0,decimalPlaces:0,duration:2,useEasing:!0,useGrouping:!0,useIndianSeparators:!1,smartEasingThreshold:999,smartEasingAmount:333,separator:",",decimal:".",prefix:"",suffix:"",enableScrollSpy:!1,scrollSpyDelay:200,scrollSpyOnce:!1},this.finalEndVal=null,this.useEasing=!0,this.countDown=!1,this.error="",this.startVal=0,this.paused=!0,this.once=!1,this.count=function(n){r.startTime||(r.startTime=n);var o=n-r.startTime;r.remaining=r.duration-o,r.useEasing?r.countDown?r.frameVal=r.startVal-r.easingFn(o,0,r.startVal-r.endVal,r.duration):r.frameVal=r.easingFn(o,r.startVal,r.endVal-r.startVal,r.duration):r.frameVal=r.startVal+(r.endVal-r.startVal)*(o/r.duration);var a=r.countDown?r.frameVal<r.endVal:r.frameVal>r.endVal;r.frameVal=a?r.endVal:r.frameVal,r.frameVal=Number(r.frameVal.toFixed(r.options.decimalPlaces)),r.printValue(r.frameVal),o<r.duration?r.rAF=requestAnimationFrame(r.count):r.finalEndVal!==null?r.update(r.finalEndVal):r.options.onCompleteCallback&&r.options.onCompleteCallback()},this.formatNumber=function(n){var o,a,c,h,l=n<0?"-":"";o=Math.abs(n).toFixed(r.options.decimalPlaces);var u=(o+="").split(".");if(a=u[0],c=u.length>1?r.options.decimal+u[1]:"",r.options.useGrouping){h="";for(var d=3,f=0,p=0,y=a.length;p<y;++p)r.options.useIndianSeparators&&p===4&&(d=2,f=1),p!==0&&f%d==0&&(h=r.options.separator+h),f++,h=a[y-p-1]+h;a=h}return r.options.numerals&&r.options.numerals.length&&(a=a.replace(/[0-9]/g,function(m){return r.options.numerals[+m]}),c=c.replace(/[0-9]/g,function(m){return r.options.numerals[+m]})),l+r.options.prefix+a+c+r.options.suffix},this.easeOutExpo=function(n,o,a,c){return a*(1-Math.pow(2,-10*n/c))*1024/1023+o},this.options=pt(pt({},this.defaults),s),this.formattingFn=this.options.formattingFn?this.options.formattingFn:this.formatNumber,this.easingFn=this.options.easingFn?this.options.easingFn:this.easeOutExpo,this.el=typeof e=="string"?document.getElementById(e):e,t=t??this.parse(this.el.innerHTML),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.endVal=this.validateValue(t),this.options.decimalPlaces=Math.max(this.options.decimalPlaces),this.resetDuration(),this.options.separator=String(this.options.separator),this.useEasing=this.options.useEasing,this.options.separator===""&&(this.options.useGrouping=!1),this.el?this.printValue(this.startVal):this.error="[CountUp] target is null or undefined",typeof window<"u"&&this.options.enableScrollSpy&&(this.error?console.error(this.error,e):(window.onScrollFns=window.onScrollFns||[],window.onScrollFns.push(function(){return r.handleScroll(r)}),window.onscroll=function(){window.onScrollFns.forEach(function(n){return n()})},this.handleScroll(this)))}return i.prototype.handleScroll=function(e){if(e&&window&&!e.once){var t=window.innerHeight+window.scrollY,s=e.el.getBoundingClientRect(),r=s.top+window.pageYOffset,n=s.top+s.height+window.pageYOffset;n<t&&n>window.scrollY&&e.paused?(e.paused=!1,setTimeout(function(){return e.start()},e.options.scrollSpyDelay),e.options.scrollSpyOnce&&(e.once=!0)):(window.scrollY>n||r>t)&&!e.paused&&e.reset()}},i.prototype.determineDirectionAndSmartEasing=function(){var e=this.finalEndVal?this.finalEndVal:this.endVal;this.countDown=this.startVal>e;var t=e-this.startVal;if(Math.abs(t)>this.options.smartEasingThreshold&&this.options.useEasing){this.finalEndVal=e;var s=this.countDown?1:-1;this.endVal=e+s*this.options.smartEasingAmount,this.duration=this.duration/2}else this.endVal=e,this.finalEndVal=null;this.finalEndVal!==null?this.useEasing=!1:this.useEasing=this.options.useEasing},i.prototype.start=function(e){this.error||(this.options.onStartCallback&&this.options.onStartCallback(),e&&(this.options.onCompleteCallback=e),this.duration>0?(this.determineDirectionAndSmartEasing(),this.paused=!1,this.rAF=requestAnimationFrame(this.count)):this.printValue(this.endVal))},i.prototype.pauseResume=function(){this.paused?(this.startTime=null,this.duration=this.remaining,this.startVal=this.frameVal,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count)):cancelAnimationFrame(this.rAF),this.paused=!this.paused},i.prototype.reset=function(){cancelAnimationFrame(this.rAF),this.paused=!0,this.resetDuration(),this.startVal=this.validateValue(this.options.startVal),this.frameVal=this.startVal,this.printValue(this.startVal)},i.prototype.update=function(e){cancelAnimationFrame(this.rAF),this.startTime=null,this.endVal=this.validateValue(e),this.endVal!==this.frameVal&&(this.startVal=this.frameVal,this.finalEndVal==null&&this.resetDuration(),this.finalEndVal=null,this.determineDirectionAndSmartEasing(),this.rAF=requestAnimationFrame(this.count))},i.prototype.printValue=function(e){var t;if(this.el){var s=this.formattingFn(e);!((t=this.options.plugin)===null||t===void 0)&&t.render?this.options.plugin.render(this.el,s):this.el.tagName==="INPUT"?this.el.value=s:this.el.tagName==="text"||this.el.tagName==="tspan"?this.el.textContent=s:this.el.innerHTML=s}},i.prototype.ensureNumber=function(e){return typeof e=="number"&&!isNaN(e)},i.prototype.validateValue=function(e){var t=Number(e);return this.ensureNumber(t)?t:(this.error="[CountUp] invalid start or end value: ".concat(e),null)},i.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},i.prototype.parse=function(e){var t=function(o){return o.replace(/([.,'  ])/g,"\\$1")},s=t(this.options.separator),r=t(this.options.decimal),n=e.replace(new RegExp(s,"g"),"").replace(new RegExp(r,"g"),".");return parseFloat(n)},i}();var lr=!1;function hr(){if(lr)return;lr=!0;let i=document.querySelectorAll("[number-count]"),e=new IntersectionObserver(t=>{t.forEach(s=>{if(s.isIntersecting){let r=s.target;e.unobserve(r);let n=r.dataset.countDirection||"up",o=parseFloat(r.dataset.countOffset||"10")/100,a=parseFloat(r.dataset.countDuration||"2"),c=r.dataset.countTarget||r.textContent?.trim()||"0",h=parseFloat(c.replace(/,/g,""));if(isNaN(h))return;let l=n==="down"?h*(1+o):h*(1-o);new cr(r,h,{startVal:Math.round(l),duration:a,useGrouping:!0}).start()}})},{threshold:0});i.forEach(t=>{t.dataset.countTarget=t.textContent?.trim()||"0",e.observe(t)})}var ur=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,s]=e.split("=");return i[t]=s,i},{});var dr=(i,e)=>{window.posthog.capture(i,e)},fr=(i,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(i,e),console.log("ph user identified"))};async function ki(i){let t=new TextEncoder().encode(i.toLowerCase().trim()),s=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(n=>n.toString(16).padStart(2,"0")).join("")}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let i=setTimeout(()=>{document.body.style.visibility="visible"},4e3),e=new ft,{accessToken:t,refreshToken:s}=as(),r=document.querySelector("[stats-skeleton]"),n=document.querySelector("[stats-wrap]"),o=document.querySelector("[error-div]"),a=document.querySelector("[error-text]"),c=document.querySelector("[waitlist-rank]"),h=document.querySelector("[spots]"),l=document.querySelectorAll("[referral-code]"),u=document.querySelector("[referral-count]"),d=document.querySelector("[desktop-bonus-remaining]"),f=document.querySelector("[desktop-bonus-complete]"),p=document.querySelector("[climbed-dropped]"),y=document.querySelector("[keep-moving]"),m=document.querySelector("[rank-arrow-wrap]"),b=document.querySelector("[cohort-text]"),P=document.querySelector("[top-100]"),O=document.querySelector("[top-1000]"),x=document.querySelector("[top-100k]"),S=document.querySelector("[sms-bonus-remaining]"),Me=document.querySelector("[sms-bonus-complete]"),gt=document.querySelector("[social-media]"),Kt=document.querySelector("[social-media-details]");if(Kt&&gt&&Kt.addEventListener("click",()=>{gt.style.display="block",gt.scrollIntoView({behavior:"smooth"})}),localStorage.getItem("sms_submitted")==="true"?(S&&(S.style.display="none"),Me&&(Me.style.display="block")):(S&&(S.style.display="block"),Me&&(Me.style.display="none")),!t||!s){clearTimeout(i),window.location.href="/get-started?redirect=android-waitlist";return}try{e.setCookies(t,s);let mt=e.checkAndSetSession(),pr=new Promise((v,pe)=>setTimeout(()=>pe(new Error("Session timeout")),3e3));await Promise.race([mt,pr]),clearTimeout(i),document.body.style.visibility="visible";let _t=e.sessionData?.access_token,Ve=e.sessionData?.user.email,gr=e.sessionData?.user.user_metadata.full_name||" ",[Yt,Qt]=is(gr),Be=e.sessionData?.user.id;localStorage.setItem("email",Ve),Be&&localStorage.setItem("user_id",Be),Be&&fr(Be,{email:Ve,firstName:Yt,lastName:Qt});let mr=ur(),{dub_id:Xt,referral:Zt,promo_code:es}=mr;if(!localStorage.getItem("conversion_sent")){let v={access_token:_t,first_name:Yt,last_name:Qt,dub_click_id:Xt||void 0,referral:Zt||void 0,promo_code:es||void 0};await ge.signupUser(v),await ge.ensureReferralCode(_t),localStorage.setItem("conversion_sent","true")}let yt=!localStorage.getItem("android_waitlist_joined");if(yt){let v={email:Ve,device_type:"android"};await ge.addToWaitlist(v),localStorage.setItem("android_waitlist_joined","true"),dr("app_waitlist",{device_type:"android",source:"android-waitlist-page"})}let z=await ge.getAndroidWaitlistStats(_t),_r=()=>{r&&(r.style.display="none"),n&&(n.style.display="block")};if(z.status===401||z.status===429||!z.ok){try{let v=await z.json();a&&(a.textContent=`Status: ${z.status} | ${JSON.stringify(v)}`)}catch{a&&(a.textContent=`Status: ${z.status} | Could not parse response`)}r&&(r.style.display="none"),o&&(o.style.display="block");return}let E=await z.json();if(yt){let v=await ki(Ve);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:E.current_rank,user_email_hash:v})}let ts=localStorage.getItem("android_waitlist_last_rank");if(ts&&!yt){let v=parseInt(ts,10);E.current_rank<v&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:E.current_rank,positions_gained:v-E.current_rank,referral_count:E.referrals_count}))}if(localStorage.setItem("android_waitlist_last_rank",E.current_rank.toString()),c&&(c.textContent=E.current_rank.toLocaleString()),E.starting_rank!==null){let v=E.starting_rank-E.current_rank;h&&(h.textContent=Math.abs(v).toLocaleString()),v<0&&(p&&(p.textContent="fell"),y&&(y.style.display="none"),m&&m.classList.add("invert"))}let N=E.current_rank;if(N<=100?P&&P.classList.add("active"):N<=1e3?O&&O.classList.add("active"):N<=1e5&&x&&x.classList.add("active"),b)if(N<=100)b.innerHTML="You're in the <strong>top 100!</strong>";else if(N<=1e3){let v=N-100;b.innerHTML=`<strong>Only ${v.toLocaleString()} spots</strong> to top 100`}else if(N<=1e5){let v=N-1e3;b.innerHTML=`<strong>Only ${v.toLocaleString()} spots</strong> to top 1,000`}else{let v=N-1e5;b.innerHTML=`<strong>Only ${v.toLocaleString()} spots</strong> to top 100,000`}l.forEach(v=>{v.textContent=E.referral_code}),u&&(u.textContent=E.referrals_count.toString()),E.desktop_dictation_bonus_earned?(d&&(d.style.display="none"),f&&(f.style.display="block")):(d&&(d.style.display="block"),f&&(f.style.display="none"));let yr=`https://wisprflow.ai/r?${E.referral_code}`;document.querySelectorAll("[share]").forEach(v=>{let pe=v.getAttribute("share");if(!pe)return;let wt=document.querySelector(`[share-content="${pe}"]`)?.textContent||"";v.addEventListener("click",async()=>{switch(pe){case"x":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(wt)}`,"_blank");break;case"linkedin":window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(yr)}`,"_blank");break;case"whatsapp":window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(wt)}`,"_blank");break;case"slack":await navigator.clipboard.writeText(wt),window.open("slack://open","_self");break}})}),_r(),hr()}catch(mt){console.error("Error on android-waitlist page:",mt),clearTimeout(i),window.location.href="/get-started?redirect=android-waitlist"}});})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanay-wispr/webflow-package",
3
- "version": "6.4.2",
3
+ "version": "6.4.3",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },