@tanay-wispr/webflow-package 6.7.7 → 6.7.8
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.
- package/dist/androidWaitlist.js +1 -1
- package/dist/downloads.js +2 -2
- package/dist/login.js +1 -1
- package/dist/signup.js +1 -1
- package/package.json +1 -1
package/dist/androidWaitlist.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var Wi=Object.create;var Wt=Object.defineProperty;var Vi=Object.getOwnPropertyDescriptor;var Bi=Object.getOwnPropertyNames;var zi=Object.getPrototypeOf,Ji=Object.prototype.hasOwnProperty;var Gi=(s,e)=>()=>(s&&(e=s(s=0)),e);var ne=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ki=(s,e)=>{for(var t in e)Wt(s,t,{get:e[t],enumerable:!0})},is=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bi(e))!Ji.call(s,i)&&i!==t&&Wt(s,i,{get:()=>e[i],enumerable:!(r=Vi(e,i))||r.enumerable});return s};var ns=(s,e,t)=>(t=s!=null?Wi(zi(s)):{},is(e||!s||!s.__esModule?Wt(t,"default",{value:s,enumerable:!0}):t,s)),Yi=s=>is(Wt({},"__esModule",{value:!0}),s);var Ee={};Ki(Ee,{Headers:()=>Er,Request:()=>tn,Response:()=>rn,default:()=>Sr,fetch:()=>en});var Zi,Ve,en,Sr,Er,tn,rn,ye=Gi(()=>{"use strict";Zi=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")},Ve=Zi(),en=Ve.fetch,Sr=Ve.fetch.bind(Ve),Er=Ve.Headers,tn=Ve.Request,rn=Ve.Response});var fs=ne(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});var Tr=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};xr.default=Tr});var Lr=ne(pt=>{"use strict";var ps=pt&&pt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(pt,"__esModule",{value:!0});var nn=ps((ye(),Yi(Ee))),on=ps(fs()),Ar=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=nn.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 r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let c=null,d=null,u=null,p=n.status,m=n.statusText;if(n.ok){if(this.method!=="HEAD"){let R=await n.text();R===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?d=R:d=JSON.parse(R))}let S=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),b=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");S&&b&&b.length>1&&(u=parseInt(b[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(d)&&(d.length>1?(c={code:"PGRST116",details:`Results contain ${d.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},d=null,u=null,p=406,m="Not Acceptable"):d.length===1?d=d[0]:d=null)}else{let S=await n.text();try{c=JSON.parse(S),Array.isArray(c)&&n.status===404&&(d=[],c=null,p=200,m="OK")}catch{n.status===404&&S===""?(p=204,m="No Content"):c={message:S}}if(c&&this.isMaybeSingle&&(!((l=c?.details)===null||l===void 0)&&l.includes("0 rows"))&&(c=null,p=200,m="OK"),c&&this.shouldThrowOnError)throw new on.default(c)}return{error:c,data:d,count:u,status:p,statusText:m}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,l;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:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};pt.default=Ar});var Cr=ne(mt=>{"use strict";var an=mt&&mt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(mt,"__esModule",{value:!0});var ln=an(Lr()),Rr=class extends ln.default{select(e){let t=!1,r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:i=r}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.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:r=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let l=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${c}"; options=${l};`,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}};mt.default=Rr});var Kt=ne(gt=>{"use strict";var cn=gt&>.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(gt,"__esModule",{value:!0});var dn=cn(Cr()),Pr=class extends dn.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 r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),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:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};gt.default=Pr});var Ir=ne(yt=>{"use strict";var un=yt&&yt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(yt,"__esModule",{value:!0});var _t=un(Kt()),Or=class{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){let i=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),r&&(this.headers.Prefer=`count=${r}`),new _t.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new _t.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let l=e.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(l.length>0){let c=[...new Set(l)].map(d=>`"${d}"`);this.url.searchParams.set("columns",c.join(","))}}return new _t.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new _t.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new _t.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};yt.default=Or});var ms=ne(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.version=void 0;Yt.version="0.0.0-automated"});var gs=ne(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.DEFAULT_HEADERS=void 0;var hn=ms();Xt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${hn.version}`}});var ys=ne(wt=>{"use strict";var _s=wt&&wt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(wt,"__esModule",{value:!0});var fn=_s(Ir()),pn=_s(Kt()),mn=gs(),jr=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},mn.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new fn.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new s(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),l;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([d,u])=>u!==void 0).map(([d,u])=>[d,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([d,u])=>{a.searchParams.append(d,u)})):(o="POST",l=t);let c=Object.assign({},this.headers);return n&&(c.Prefer=`count=${n}`),new pn.default({method:o,url:a,headers:c,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};wt.default=jr});var Es=ne(V=>{"use strict";var vt=V&&V.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(V,"__esModule",{value:!0});V.PostgrestBuilder=V.PostgrestTransformBuilder=V.PostgrestFilterBuilder=V.PostgrestQueryBuilder=V.PostgrestClient=void 0;var ws=vt(ys());V.PostgrestClient=ws.default;var vs=vt(Ir());V.PostgrestQueryBuilder=vs.default;var bs=vt(Kt());V.PostgrestFilterBuilder=bs.default;var ks=vt(Cr());V.PostgrestTransformBuilder=ks.default;var Ss=vt(Lr());V.PostgrestBuilder=Ss.default;V.default={PostgrestClient:ws.default,PostgrestQueryBuilder:vs.default,PostgrestFilterBuilder:bs.default,PostgrestTransformBuilder:ks.default,PostgrestBuilder:Ss.default}});var Is=ne((zo,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 Vt=s=>s.verification_method==="email_otp"&&typeof s.pending_authentication_token=="string"&&s.pending_authentication_token.length>0,U="https://api.wisprflow.ai",se=class extends Error{constructor(t,r,i,n=null){super(i);this.status=t;this.code=r;this.passwordRejectionMessage=n;this.name="AriaAuthError"}},Q=s=>s.trim().toLowerCase(),os=(s,e)=>{let t=new Set(["verification_failed","invalid_credentials","sso_required","scim_managed_domain","sign_in_to_continue","identity_conflict","rate_limited","provider_unavailable","validation_error"]);return typeof s.code=="string"?s.code:s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"&&typeof s.detail.code=="string"?s.detail.code:typeof s.detail=="string"&&t.has(s.detail)?s.detail:{401:"invalid_credentials",409:"identity_conflict",422:"validation_error",429:"rate_limited",503:"provider_unavailable"}[e]??"authentication_failed"},ut=(s,e)=>({verification_failed:"Incorrect or expired code. Try again.",invalid_credentials:"Incorrect email or password.",sso_required:"Sign in with SSO to continue.",scim_managed_domain:"This account is managed by your organization.",sign_in_to_continue:"This account already exists. Sign in to continue.",identity_conflict:"We couldn't continue with this account. Try again or contact support.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again.",invalid_code:"Enter the six-digit code."})[s]??(e===403?"This sign-in method is not available for this account.":"Unable to complete authentication. Please try again."),Xi=(s,e,t)=>[s.message,s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"?s.detail.message:null,typeof s.detail=="string"?s.detail:null].find(n=>typeof n=="string"&&n.length>0&&n!==e)??ut(e,t),We=(s,e)=>{let t=os(s,e);return new se(e,t,Xi(s,t,e),e===400&&typeof s.detail=="string"&&s.detail.length>0?s.detail:null)},Qi=(s,e)=>{let t=os(s,e);return new se(e,t,ut(t,e))},kr=class{static async signupUser(e){try{let t=`${U}/signup`,i=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=i&&i.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(`${U}/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(`${U}/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(`${U}/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(`${U}/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){let t=Q(e),r=await fetch(`${U}/user_status?email=${encodeURIComponent(t)}`),i=await r.json().catch(()=>({}));if(!r.ok)throw We(i,r.status);return i}static async requestPasswordReset(e,t){let r=await fetch(`${U}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:Q(e),captcha_token:t})});if(!r.ok){let i=await r.json().catch(()=>({}));throw We(i,r.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${U}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:Q(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw We(r,t.status);return r}static async signInWithCaptcha(e){let t=await fetch(`${U}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:Q(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw We(r,t.status);return r}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${U}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:Q(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw We(r,t.status);return r}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new se(422,"invalid_code",ut("invalid_code",422));let t=await fetch(`${U}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json().catch(()=>({}));if(!t.ok){let i=Qi(r,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new se(t.status,"verification_failed",ut("verification_failed",t.status))}if(r.provider!=="workos"||!r.access_token||!r.refresh_token||!r.user_id||!r.email)throw new se(t.status,"authentication_failed",ut("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${U}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:Q(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw We(r,t.status);return r}static async getSubscriptionStatus(e){return await fetch(`${U}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${U}/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,r){let i=`${U}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return r&&(i+=`¤cy=${r}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${U}/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(`${U}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${U}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${U}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,r){let i=new FormData;return i.append("screenshot",e),await fetch(`${U}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:r})}};function as(s){let[e,...t]=s.split(" "),r=t.join(" ");return[e,r]}function ls(s){return s==="azure"?"Microsoft":s==="workos"?"SSO":s.charAt(0).toUpperCase()+s.slice(1)}var j=kr;var cs=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var ds=()=>{let s=window.location.hash.substring(1),e=new URLSearchParams(s);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var us=()=>{let{access_token:s,refresh_token:e}=ds(),t=s,r=e;if(!t||!r){let i=cs();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var hs=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ye(),Ee)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var ht=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Bt=class extends ht{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},zt=class extends ht{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Jt=class extends ht{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Gt;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(Gt||(Gt={}));var sn=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},ft=class{constructor(e,{headers:t={},customFetch:r,region:i=Gt.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=hs(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return sn(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let c;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",c=o):typeof o=="string"?(a["Content-Type"]="text/plain",c=o):typeof FormData<"u"&&o instanceof FormData?c=o:(a["Content-Type"]="application/json",c=JSON.stringify(o)));let d=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:c}).catch(y=>{throw new Bt(y)}),u=d.headers.get("x-relay-error");if(u&&u==="true")throw new zt(d);if(!d.ok)throw new Jt(d);let p=((r=d.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),m;return p==="application/json"?m=yield d.json():p==="application/octet-stream"?m=yield d.blob():p==="text/event-stream"?m=d:p==="multipart/form-data"?m=yield d.formData():m=yield d.text(),{data:m,error:null}}catch(i){return{data:null,error:i}}})}};var Ts=ns(Es(),1),{PostgrestClient:xs,PostgrestQueryBuilder:Ao,PostgrestFilterBuilder:Lo,PostgrestTransformBuilder:Ro,PostgrestBuilder:Co}=Ts.default;var As="2.10.2";var Ls={"X-Client-Info":`realtime-js/${As}`},Rs="1.0.0",Zt=1e4,Cs=1e3,Te;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(Te||(Te={}));var z;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(z||(z={}));var Y;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(Y||(Y={}));var Qt;(function(s){s.websocket="websocket"})(Qt||(Qt={}));var we;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(we||(we={}));var bt=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),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+i));o=o+i;let l=r.decode(e.slice(o,o+n));o=o+n;let c=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:c}}};var xe=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 C;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(C||(C={}));var Ur=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=gn(o,s,e,i),n),{})},gn=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?Ps(n,o):$r(o)},Ps=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return vn(e,t)}switch(s){case C.bool:return _n(e);case C.float4:case C.float8:case C.int2:case C.int4:case C.int8:case C.numeric:case C.oid:return yn(e);case C.json:case C.jsonb:return wn(e);case C.timestamp:return bn(e);case C.abstime:case C.date:case C.daterange:case C.int4range:case C.int8range:case C.money:case C.reltime:case C.text:case C.time:case C.timestamptz:case C.timetz:case C.tsrange:case C.tstzrange:return $r(e);default:return $r(e)}},$r=s=>s,_n=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},yn=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},wn=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},vn=(s,e)=>{if(typeof s!="string")return s;let t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n,o=s.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Ps(e,a))}return s},bn=s=>typeof s=="string"?s.replace(" ","T"):s,er=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var Ae=class{constructor(e,t,r={},i=Zt){this.channel=e,this.event=t,this.payload=r,this.timeout=i,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 r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.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(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Mr;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Mr||(Mr={}));var Be=class s{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=s.syncState(this.state,i,n,o),this.pendingDiffs.forEach(l=>{this.state=s.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=s.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(c,d)=>{o[c]||(l[c]=d)}),this.map(o,(c,d)=>{let u=n[c];if(u){let p=d.map(b=>b.presence_ref),m=u.map(b=>b.presence_ref),y=d.filter(b=>m.indexOf(b.presence_ref)<0),S=u.filter(b=>p.indexOf(b.presence_ref)<0);y.length>0&&(a[c]=y),S.length>0&&(l[c]=S)}else a[c]=d}),this.syncDiff(n,{joins:a,leaves:l},r,i)}static syncDiff(e,t,r,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(a,l)=>{var c;let d=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),d.length>0){let u=e[a].map(m=>m.presence_ref),p=d.filter(m=>u.indexOf(m.presence_ref)<0);e[a].unshift(...p)}r(a,d,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let d=l.map(u=>u.presence_ref);c=c.filter(u=>d.indexOf(u.presence_ref)<0),e[a]=c,i(a,c,l),c.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return"metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=i,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 Nr;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Nr||(Nr={}));var qr;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(qr||(qr={}));var Dr;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Dr||(Dr={}));var ze=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=z.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 Ae(this,Y.join,this.params,this.timeout),this.rejoinTimer=new xe(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=z.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=z.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=z.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=z.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Y.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new Be(this),this.broadcastEndpointURL=er(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,i;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(d=>e&&e("CHANNEL_ERROR",d)),this._onClose(()=>e&&e("CLOSED"));let l={},c={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(d=>d.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:c},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:d})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),d===void 0){e&&e("SUBSCRIBED");return}else{let p=this.bindings.postgres_changes,m=(u=p?.length)!==null&&u!==void 0?u:0,y=[];for(let S=0;S<m;S++){let b=p[S],{filter:{event:R,schema:h,table:g,filter:L}}=b,P=d&&d[S];if(P&&P.event===R&&P.schema===h&&P.table===g&&P.filter===L)y.push(Object.assign(Object.assign({},b),{id:P.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,e&&e("SUBSCRIBED");return}}).receive("error",d=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(d).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,r){return this._on(e,t,r)}async send(e,t={}){var r,i;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 l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),c.receive("ok",()=>n("ok")),c.receive("error",()=>n("error")),c.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=z.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Y.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new Ae(this,Y.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new Ae(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:d}=Y;if(r&&[a,l,c,d].indexOf(o)>=0&&r!==this._joinRef())return;let p=this._onMessage(o,t,r);if(t&&!p)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(m=>{var y,S,b;return((y=m.filter)===null||y===void 0?void 0:y.event)==="*"||((b=(S=m.filter)===null||S===void 0?void 0:S.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===o}).map(m=>m.callback(p,r)):(n=this.bindings[o])===null||n===void 0||n.filter(m=>{var y,S,b,R,h,g;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){let L=m.id,P=(y=m.filter)===null||y===void 0?void 0:y.event;return L&&((S=t.ids)===null||S===void 0?void 0:S.includes(L))&&(P==="*"||P?.toLocaleLowerCase()===((b=t.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))}else{let L=(h=(R=m?.filter)===null||R===void 0?void 0:R.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return L==="*"||L===((g=t?.event)===null||g===void 0?void 0:g.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof p=="object"&&"ids"in p){let y=p.data,{schema:S,table:b,commit_timestamp:R,type:h,errors:g}=y;p=Object.assign(Object.assign({},{schema:S,table:b,commit_timestamp:R,eventType:h,new:{},old:{},errors:g}),this._getPayloadRecords(y))}m.callback(p,r)})}_isClosed(){return this.state===z.closed}_isJoined(){return this.state===z.joined}_isJoining(){return this.state===z.joining}_isLeaving(){return this.state===z.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&s.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Y.close,{},e)}_onError(e){this._on(Y.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=z.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Ur(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Ur(e.columns,e.old_record)),t}};var Sn=()=>{},En=typeof WebSocket<"u",Je=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Ls,this.params={},this.timeout=Zt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Sn,this.conn=null,this.sendBuffer=[],this.serializer=new bt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(ye(),Ee)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Qt.websocket}`,this.httpEndpoint=er(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 i=(r=t?.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),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 xe(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(En){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Fr(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>ns(Is())).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,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case Te.connecting:return we.Connecting;case Te.open:return we.Open;case Te.closing:return we.Closing;default:return we.Closed}}isConnected(){return this.connectionState()===we.Open}channel(e,t={config:{}}){let r=new ze(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${r} (${n})`,i),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(Y.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(r=>r.topic===e&&(r._isJoined()||r._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:Rs}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,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(Y.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_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(Cs,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Fr=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Te.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var Ge=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function q(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var tr=class extends Ge{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},kt=class extends Ge{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Tn=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},rr=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ye(),Ee)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},js=()=>Tn(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(ye(),Ee))).Response:Response});var Ke=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Hr=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),xn=(s,e)=>Ke(void 0,void 0,void 0,function*(){let t=yield js();s instanceof t?s.json().then(r=>{e(new tr(Hr(r),s.status||500))}).catch(r=>{e(new kt(Hr(r),r))}):e(new kt(Hr(s),s))}),An=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function sr(s,e,t,r,i,n){return Ke(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,An(e,r,i,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>xn(l,a))})})}function St(s,e,t,r){return Ke(this,void 0,void 0,function*(){return sr(s,"GET",e,t,r)})}function oe(s,e,t,r,i){return Ke(this,void 0,void 0,function*(){return sr(s,"POST",e,r,i,t)})}function $s(s,e,t,r,i){return Ke(this,void 0,void 0,function*(){return sr(s,"PUT",e,r,i,t)})}function ir(s,e,t,r,i){return Ke(this,void 0,void 0,function*(){return sr(s,"DELETE",e,r,i,t)})}var Z=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Ln={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Us={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Et=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=rr(i)}uploadOrUpdate(e,t,r,i){return Z(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Us),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl)):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let l=this._removeEmptyFolders(t),c=this._getFinalPath(l),d=yield this.fetch(`${this.url}/object/${c}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield d.json();return d.ok?{data:{path:l,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(q(n))return{data:null,error:n};throw n}})}upload(e,t,r){return Z(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return Z(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 l,c=Object.assign({upsert:Us.upsert},i),d=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,d["cache-control"]=`max-age=${c.cacheControl}`,d["content-type"]=c.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:d}),p=yield u.json();return u.ok?{data:{path:n,fullPath:p.Key},error:null}:{data:null,error:p}}catch(l){if(q(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return Z(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield oe(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new Ge("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(q(r))return{data:null,error:r};throw r}})}update(e,t,r){return Z(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return Z(this,void 0,void 0,function*(){try{return{data:yield oe(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(q(i))return{data:null,error:i};throw i}})}copy(e,t,r){return Z(this,void 0,void 0,function*(){try{return{data:{path:(yield oe(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(q(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return Z(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield oe(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(q(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return Z(this,void 0,void 0,function*(){try{let i=yield oe(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(q(i))return{data:null,error:i};throw i}})}download(e,t){return Z(this,void 0,void 0,function*(){let i=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 St(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(q(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&i.push(l);let c=i.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${c}`)}}}remove(e){return Z(this,void 0,void 0,function*(){try{return{data:yield ir(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(q(t))return{data:null,error:t};throw t}})}list(e,t,r){return Z(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Ln),t),{prefix:e||""});return{data:yield oe(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(q(i))return{data:null,error:i};throw i}})}_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 Ms="2.6.0";var Ns={"X-Client-Info":`storage-js/${Ms}`};var Ye=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Tt=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Ns),t),this.fetch=rr(r)}listBuckets(){return Ye(this,void 0,void 0,function*(){try{return{data:yield St(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(q(e))return{data:null,error:e};throw e}})}getBucket(e){return Ye(this,void 0,void 0,function*(){try{return{data:yield St(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(q(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Ye(this,void 0,void 0,function*(){try{return{data:yield oe(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(r){if(q(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Ye(this,void 0,void 0,function*(){try{return{data:yield $s(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(r){if(q(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Ye(this,void 0,void 0,function*(){try{return{data:yield oe(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(q(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Ye(this,void 0,void 0,function*(){try{return{data:yield ir(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(q(t))return{data:null,error:t};throw t}})}};var xt=class extends Tt{constructor(e,t={},r){super(e,t,r)}from(e){return new Et(this.url,this.headers,e,this.fetch)}};var qs="2.44.4";var At="";typeof Deno<"u"?At="deno":typeof document<"u"?At="web":typeof navigator<"u"&&navigator.product==="ReactNative"?At="react-native":At="node";var Rn={"X-Client-Info":`supabase-js-${At}/${qs}`},Ds={headers:Rn},Fs={schema:"public"},Hs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ws={};ye();var Cn=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Pn=s=>{let e;return s?e=s:typeof fetch>"u"?e=Sr:e=fetch,(...t)=>e(...t)},On=()=>typeof Headers>"u"?Er:Headers,Vs=(s,e,t)=>{let r=Pn(t),i=On();return(n,o)=>Cn(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:s,c=new i(o?.headers);return c.has("apikey")||c.set("apikey",s),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),r(n,Object.assign(Object.assign({},o),{headers:c}))})};function Bs(s){return s.replace(/\/$/,"")}function zs(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:l,global:c}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},l),i),global:Object.assign(Object.assign({},c),n)}}var nr="2.64.4";var Js="http://localhost:9999",Gs="supabase.auth.token";var Ks={"X-Client-Info":`gotrue-js/${nr}`},Wr=10;var Lt="X-Supabase-Api-Version",Vr={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Ys(s){return Math.round(Date.now()/1e3)+s}function Xs(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}var ee=()=>typeof document<"u",Le={tested:!1,writable:!1},ve=()=>{if(!ee())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Le.tested)return Le.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),Le.tested=!0,Le.writable=!0}catch{Le.tested=!0,Le.writable=!1}return Le.writable};function or(s){let e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}var ar=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ye(),Ee)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Qs=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",Br=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Ct=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},lr=async(s,e)=>{await s.removeItem(e)};function In(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,l,c,d=0;for(s=s.replace("-","+").replace("_","/");d<s.length;)o=e.indexOf(s.charAt(d++)),a=e.indexOf(s.charAt(d++)),l=e.indexOf(s.charAt(d++)),c=e.indexOf(s.charAt(d++)),r=o<<2|a>>4,i=(a&15)<<4|l>>2,n=(l&3)<<6|c,t=t+String.fromCharCode(r),l!=64&&i!=0&&(t=t+String.fromCharCode(i)),c!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Rt=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Rt.promiseConstructor=Promise;function zr(s){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=s.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 r=t[1];return JSON.parse(In(r))}async function Zs(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function ei(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await s(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function jn(s){return("0"+s.toString(16)).substr(-2)}function $n(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,jn).join("")}async function Un(s){let t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function Mn(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Nn(s){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."),s;let t=await Un(s);return Mn(t)}async function Re(s,e,t=!1){let r=$n(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await Br(s,`${e}-code-verifier`,i);let n=await Nn(r);return[n,r===n?"plain":"s256"]}var qn=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function ti(s){let e=s.headers.get(Lt);if(!e||!e.match(qn))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Pt=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function E(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var cr=class extends Pt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function ri(s){return E(s)&&s.name==="AuthApiError"}var Xe=class extends Pt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},pe=class extends Pt{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},ae=class extends pe{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Qe=class extends pe{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Ce=class extends pe{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Pe=class extends pe{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}}},Ot=class extends pe{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}}},Ze=class extends pe{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function dr(s){return E(s)&&s.name==="AuthRetryableFetchError"}var It=class extends pe{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Dn=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},Oe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Fn=[502,503,504];async function si(s){var e;if(!Qs(s))throw new Ze(Oe(s),0);if(Fn.includes(s.status))throw new Ze(Oe(s),s.status);let t;try{t=await s.json()}catch(n){throw new Xe(Oe(n),n)}let r,i=ti(s);if(i&&i.getTime()>=Vr["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new It(Oe(t),s.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 It(Oe(t),s.status,t.weak_password.reasons);throw new cr(Oe(t),s.status||500,r)}var Hn=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function T(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Lt]||(n[Lt]=Vr["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(i=r?.query)!==null&&i!==void 0?i:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Wn(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(l):{data:Object.assign({},l),error:null}}async function Wn(s,e,t,r,i,n){let o=Hn(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(l){throw console.error(l),new Ze(Oe(l),0)}if(a.ok||await si(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await si(l)}}function me(s){var e;let t=null;Vn(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Ys(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function Jr(s){let e=me(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function le(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function ii(s){return{data:s,error:null}}function ni(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Dn(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function oi(s){return s}function Vn(s){return s.access_token&&s.refresh_token&&s.expires_in}var Bn=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},Ie=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=ar(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await T(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(E(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await T(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:le})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Bn(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await T(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:ni,redirectTo:t?.redirectTo})}catch(t){if(E(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await T(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:le})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},d=await T(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:oi});if(d.error)throw d.error;let u=await d.json(),p=(o=d.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=d.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(y=>{let S=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(y.split(";")[1].split("=")[1]);c[`${b}Page`]=S}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},u),c),error:null}}catch(c){if(E(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){try{return await T(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:le})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await T(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:le})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await T(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:le})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await T(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(E(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await T(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}};var ai={getItem:s=>ve()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{ve()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{ve()&&globalThis.localStorage.removeItem(s)}};function Gr(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function li(){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 je={debug:!!(globalThis&&ve()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},jt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},ur=class extends jt{};async function Kr(s,e,t){je.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),je.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){je.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{je.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw je.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new ur(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(je.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()}})}li();var zn={url:Js,storageKey:Gs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ks,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},$t=30*1e3,ci=3;async function di(s,e,t){return await t()}var $e=class s{constructor(e){var t,r;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=s.nextInstanceID,s.nextInstanceID+=1,this.instanceID>0&&ee()&&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 i=Object.assign(Object.assign({},zn),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Ie({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=ar(i.fetch),this.lock=i.lock||di,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:ee()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Kr:this.lock=di,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?i.storage?this.storage=i.storage:ve()?this.storage=ai:(this.memoryStorage={},this.storage=Gr(this.memoryStorage)):(this.memoryStorage={},this.storage=Gr(this.memoryStorage)),ee()&&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)}(r=this.broadcastChannel)===null||r===void 0||r.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} (${nr}) ${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=ee()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),r?.message==="Identity is already linked"||r?.message==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return E(e)?{error:e}:{error:new Xe("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:me}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(E(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:d,password:u,options:p}=e,m=null,y=null;this.flowType==="pkce"&&([m,y]=await Re(this.storage,this.storageKey)),n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p?.emailRedirectTo,body:{email:d,password:u,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:m,code_challenge_method:y},xform:me})}else if("phone"in e){let{phone:d,password:u,options:p}=e;n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:u,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(i=p?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:me})}else throw new Ce("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 l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(E(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 T(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:Jr})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await T(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:Jr})}else throw new Ce("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Qe}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.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 Ct(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await T(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:me});return await lr(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 Qe}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:r,token:i,access_token:n,nonce:o}=e,a=await T(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:me}),{data:l,error:c}=a;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Qe}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:l}=e,c=null,d=null;this.flowType==="pkce"&&([c,d]=await Re(this.storage,this.storageKey));let{error:u}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(r=l?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:d},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:d}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l?.data)!==null&&i!==void 0?i:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c?.message_id},error:d}}throw new Ce("You must provide either an email or phone number.")}catch(a){if(E(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await T(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:me});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(E(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Re(this.storage,this.storageKey)),await T(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:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e?.options)===null||i===void 0)&&i.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:ii})}catch(n){if(E(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:r}=e;if(r)throw r;if(!t)throw new ae;let{error:i}=await T(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(E(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:r,type:i,options:n}=e,{error:o}=await T(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,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:r,type:i,options:n}=e,{data:o,error:a}=await T(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new Ce("You must provide either an email or phone number and a type")}catch(t){if(E(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 r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}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 Ct(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 r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,c,d)=>(!o&&c==="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(l,c,d))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},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 T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:le}):await this._useSession(async t=>{var r,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ae}:await T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:le})})}catch(t){if(E(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 r=>{let{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new ae;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Re(this.storage,this.storageKey));let{data:c,error:d}=await T(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:le});if(d)throw d;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return zr(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 ae;let t=Date.now()/1e3,r=t,i=!0,n=null,o=zr(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(E(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 r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new ae;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!ee())throw new Pe("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Pe("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Ot("Not a valid PKCE flow url.");let t=or(window.location.href);if(e){if(!t.code)throw new Ot("No code detected.");let{data:h,error:g}=await this._exchangeCodeForSession(t.code);if(g)throw g;let L=new URL(window.location.href);return L.searchParams.delete("code"),window.history.replaceState(window.history.state,"",L.toString()),{data:{session:h.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Pe(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=t;if(!n||!a||!o||!c)throw new Pe("No session defined in URL");let d=Math.round(Date.now()/1e3),u=parseInt(a),p=d+u;l&&(p=parseInt(l));let m=p-d;m*1e3<=$t&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${u}s`);let y=p-u;d-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,p,d):d-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",y,p,d);let{data:S,error:b}=await this._getUser(n);if(b)throw b;let R={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:p,refresh_token:o,token_type:c,user:S.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:R,redirectType:t.type},error:null}}catch(t){if(E(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=or(window.location.href);return!!(ee()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=or(window.location.href),t=await Ct(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 r;let{data:i,error:n}=t;if(n)return{error:n};let o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(ri(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await lr(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Xs(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await Re(this.storage,this.storageKey,!0));try{return await T(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(E(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,l,c,d;let{data:u,error:p}=n;if(p)throw p;let m=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:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await T(this.fetch,"GET",m,{headers:this.headers,jwt:(d=(c=u.session)===null||c===void 0?void 0:c.access_token)!==null&&d!==void 0?d:void 0})});if(i)throw i;return ee()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(E(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await T(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await ei(async i=>(i>0&&await Zs(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await T(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:me})),(i,n)=>{let o=200*Math.pow(2,i);return n&&dr(n)&&Date.now()+o-r<$t})}catch(r){if(this._debug(t,"error",r),E(r))return{data:{session:null,user:null},error:r};throw r}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 r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),ee()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await Ct(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<i+Wr;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Wr}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),dr(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new ae;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Rt;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new ae;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(i,"error",n),E(n)){let o={session:null,error:n};return dr(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&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(l){n.push(l)}});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(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Br(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await lr(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&ee()&&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(),$t);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:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((r.expires_at*1e3-e)/$t);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${$t}ms, refresh threshold is ${ci} ticks`),i<=ci&&await this._callRefreshToken(r.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 jt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!ee()||!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,r){let i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await Re(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await T(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:l}=await T(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return l?{data:null,error:l}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.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(E(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}: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 r=e?.factors||[],i=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let l=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(l="aal2");let d=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:d},error:null}}))}};$e.nextInstanceID=0;var Jn=$e,Yr=Jn;var hr=class extends Yr{constructor(e){super(e)}};var Gn=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Ut=class{constructor(e,t,r){var i,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=Bs(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 l=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,c={db:Fs,realtime:Ws,auth:Object.assign(Object.assign({},Hs),{storageKey:l}),global:Ds},d=zs(r??{},c);this.storageKey=(i=d.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=d.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=d.auth)!==null&&o!==void 0?o:{},this.headers,d.global.fetch),this.fetch=Vs(t,this._getAccessToken.bind(this),d.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},d.realtime)),this.rest=new xs(`${a}/rest/v1`,{headers:this.headers,schema:d.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new ft(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new xt(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Gn(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:n,flowType:o,debug:a},l,c){var d;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new hr({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:c,hasCustomAuthorizationHeader:(d="Authorization"in this.headers)!==null&&d!==void 0?d:!1})}_initRealtimeClient(e){return new Je(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var ui=(s,e,t)=>new Ut(s,e,t);var ge={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Kn=s=>{try{let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},fr=s=>{let[e,t]=s.split(".");return!e||!t?null:Kn(t)},hi=s=>{let e=fr(s);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return typeof e.client_id=="string"||t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var Yn="https://api.workos.com",Xn=60,et=(s,e)=>typeof s[e]=="string"?s[e]:void 0,fi=(s,e,t)=>{let r=fr(s);if(!r)return null;let i=et(r,"urn:wispr:user_external_id")??et(r,"sub"),n=t?.email??et(r,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof r.exp=="number"?r.exp:void 0,l={id:i??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:s,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:l}},Qn=async(s,e,t,r)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):Yn,n=await fetch(`${i}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:s,organization_id:r})});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${n.status}`)}return await n.json()},pi=async(s,e)=>{let t=fr(s);if(!t)throw new Error("Invalid WorkOS access token");let r=Math.floor(Date.now()/1e3),i=typeof t.exp=="number"?t.exp:0,n=et(t,"client_id");if(i-r<Xn&&n){let l=await Qn(e,n,et(t,"iss"),et(t,"org_id")),c=fi(l.access_token,l.refresh_token,l.user);if(!c)throw new Error("WorkOS refresh returned an invalid access token");return c}if(i<=r)throw new Error("WorkOS session expired");let a=fi(s,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var tt=class{constructor(){this.sessionData=null;this.supabase=ui(ge.supaBaseUrl,ge.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ge.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||ge.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||ge.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:r,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw console.error("Error setting session:",r),r}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,r){let i=new Date;i.setTime(i.getTime()+r*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{if(hi(t)==="workos"){this.sessionData=await pi(t,r),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,r)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,i]=t.split("=");return e[r]=i,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:r}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||ge.redirectUri}});if(r)throw r}catch(r){throw console.error("Error sending magic link:",r),r}}async signUpWithPassword(e,t,r,i,n,o){try{if(!n)throw new Error("Please complete the verification");let a=await j.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,redirect_url:i||ge.redirectUri,workos_capable:o?.workosCapable||void 0});return console.log("Signup request completed"),a}catch(a){throw console.error("Error signing up:",a),a}}async signInWithPassword(e,t,r,i){try{if(!r)throw new Error("Please complete the verification");let n=await j.signInWithCaptcha({email:e,password:t,captcha_token:r,provision:i?.provision??!1,workos_capable:i?.workosCapable||void 0});if(Vt(n))return{kind:"otp",challenge:n};if(!n.access_token||!n.refresh_token)throw new Error(n.error||"Invalid login credentials");return console.log("Sign in request completed"),{kind:"authenticated",accessToken:n.access_token,refreshToken:n.refresh_token,fullName:[n.first_name,n.last_name].filter(Boolean).join(" ")||void 0,provider:n.provider||void 0}}catch(n){throw console.error("Error signing in with password:",n),n}}async resendVerificationEmail(e,t,r,i){try{if(!r)throw new Error("Please complete the verification");let n=await j.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||ge.redirectUri,workos_capable:i?.workosCapable||void 0});return console.log("Verification request completed"),n}catch(n){throw console.error("Error resending verification email:",n),n}}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 pr=null,mi=(s,e)=>{if(!(s instanceof Error)||s.name!=="AriaAuthError")return e;let t={verification_failed:"Incorrect or expired code. Try again.",invalid_code:"Enter the six-digit code.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again."},{code:r}=s;return r&&t[r]||e},mr=()=>{pr!==null&&(window.clearInterval(pr),pr=null)};function rt(){let s=document.querySelector("[otp-verification]");s&&(s.style.display="none"),mr()}function gi(s){let e=document.querySelector("[otp-verification]");if(!e){console.warn("[otpUi] [otp-verification] block not found in DOM");return}let t=Array.from(document.querySelectorAll("[otp-box]")),r=document.querySelector("[otp-email]"),i=document.querySelector("[otp-verify]"),n=document.querySelector("[otp-error]"),o=document.querySelector("[otp-error-message]"),a=document.querySelector("[otp-resend]"),l=document.querySelector("[otp-resend-countdown]"),c=document.querySelector("[otp-resend-seconds]"),d=document.querySelector("[otp-reset]");t.forEach(h=>{h.value="",h.removeAttribute("disabled"),h.setAttribute("inputmode","numeric"),h.setAttribute("autocomplete","one-time-code"),h.setAttribute("data-ph-no-capture",""),h.setAttribute("data-1p-ignore",""),h.setAttribute("data-private",""),h.classList.add("ph-no-capture")}),n&&(n.style.display="none"),l&&(l.style.display="none"),a&&(a.style.display=""),i&&(i.textContent="Verify",i.style.pointerEvents="",i.removeAttribute("aria-disabled")),mr(),r&&(r.textContent=s.email),e.style.display="block",t[0]?.focus();let u=h=>{n&&(n.style.display="block"),o&&(o.textContent=h)},p=()=>{n&&(n.style.display="none")},m=!1,y=!1,S=h=>{i&&(i.style.pointerEvents=h?"none":"",h?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled"),i instanceof HTMLButtonElement&&(i.disabled=h),a&&a.style.display!=="none"&&(a.style.pointerEvents=h?"none":"",h?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},b=async()=>{if(m)return;let h=t.map(g=>g.value).join("");if(h.length!==6){u("Please enter all 6 digits.");return}m=!0,S(!0),t.forEach(g=>g.setAttribute("disabled","true")),p();try{await s.onVerify(h),p(),i&&(i.textContent="Verified \u2705")}catch(g){m=!1,S(!1),t.forEach(L=>{L.value="",L.removeAttribute("disabled")}),u(mi(g,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((h,g)=>{h.oninput=()=>{h.value=h.value.replace(/\D/g,"").slice(0,1),h.value&&g<t.length-1&&t[g+1].focus(),p()},h.onkeydown=L=>{L.key==="Backspace"&&!h.value&&g>0?t[g-1].focus():L.key==="Enter"&&(L.preventDefault(),b())},h.onpaste=L=>{L.preventDefault();let P=(L.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);P.split("").forEach((J,ie)=>{t[ie]&&(t[ie].value=J)});let de=Math.min(P.length,t.length-1);t[de]?.focus(),p()}}),i&&(i.onclick=h=>{h.preventDefault(),b()});let R=()=>{let h=30;a&&(a.style.display="none"),l&&(l.style.display="block"),c&&(c.textContent=String(h)),mr(),pr=window.setInterval(()=>{h-=1,c&&(c.textContent=String(h)),h<=0&&(mr(),a&&(a.style.display=""),l&&(l.style.display="none"))},1e3)};a&&(a.onclick=async h=>{if(h.preventDefault(),!(y||a.style.display==="none")){y=!0,t.forEach(g=>{g.value="",g.removeAttribute("disabled")}),t[0]?.focus(),p(),R();try{await s.onResend?.()}catch(g){u(mi(g,"We couldn't send a new code. Please try again when the timer ends."))}finally{y=!1}}}),d&&(d.onclick=h=>{h.preventDefault(),rt(),s.onReset?.()})}var Ue=()=>window.hcaptcha,gr=async()=>{let s=Ue();if(!s)throw new Error("Verification system not loaded");let e=await s.execute({async:!0}),t=typeof e=="string"?e:e.response;if(!t)throw new Error("Verification cancelled");return t},Mt=(s,e)=>s instanceof Error?s.message:e,_i=(s,e)=>s instanceof se?s.code==="sso_required"?(e.showSso(),!0):s.code==="scim_managed_domain"?(e.showScim(),!0):(s.code==="sign_in_to_continue"&&e.showLogin(),e.showError(s.message),!0):!1,yi=s=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(r){e={pendingAuthenticationToken:r.pendingAuthenticationToken,email:Q(r.email)},s.beforeShow(),gi({email:e.email,onVerify:async i=>{if(!e)throw rt(),s.onMissingChallenge(),new Error("Missing OTP challenge");let n=await j.verifyEmailOtp({code:i,pending_authentication_token:e.pendingAuthenticationToken});t(),await s.onAuthenticated(n)},onResend:async()=>{if(!e)throw rt(),s.onMissingChallenge(),new Error("Missing OTP challenge");let i=await gr();try{await s.client.resendVerificationEmail(e.email,s.redirectUrl,i,{workosCapable:s.isWorkosCapable(e.email)})}finally{Ue()?.reset()}},onReset:()=>{t(),s.onReset()}})}}};var ce=null;function Xr(s,e=30,t){ce&&(clearInterval(ce),ce=null);let r=e;s.style.pointerEvents="none",s.textContent=`Resend (${r}s)`,ce=setInterval(()=>{r=r-1,s.textContent=r>0?`Resend (${r}s)`:"Resend email",r===0&&(s.style.pointerEvents="auto",ce&&(clearInterval(ce),ce=null),t&&t())},1e3)}function wi(){ce&&(clearInterval(ce),ce=null)}var vi=/^[\p{L}\p{M}\s\-'.]+$/u;function Zn(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":vi.test(t)?t.length>30?"Your name must be 30 characters or fewer":e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Your name can't include symbols":null}function Qr(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":vi.test(t)?t.length>30?"Your name must be 30 characters or fewer":t.includes(" ")?e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Please include your last name":"Your name can't include symbols":null}function bi(s,e,t){let r="full-name-match-error",i=l=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let c=document.getElementById(r);c||(c=document.createElement("div"),c.id=r,c.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",c)),c.textContent=l},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(r)?.remove()},o=()=>{let l=Zn(e.value,s.value);l?i(l):n()},a=()=>{let l=Qr(e.value,s.value);l?i(l):n()};s.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var ki="password-rejection-error",Si=s=>s instanceof se?s.passwordRejectionMessage:null,Nt=s=>{s.classList.remove("error"),document.getElementById(ki)?.remove()},Zr=(s,e)=>{if(Nt(s),e.length===0)return;s.classList.add("error");let t=document.createElement("div");t.id=ki,t.style.fontSize="0.875rem",t.textContent=e,s.insertAdjacentElement("afterend",t)};var O=(s,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:s,retry_attempt:10-t}),window.posthog.capture(s,e)):t>0&&setTimeout(()=>O(s,e,t-1),200)},Ei=(s,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(s,e),console.log("ph user identified"))};var eo="wispr_workos_capable";var Ti=()=>{try{return window.sessionStorage.getItem(eo)==="true"}catch{return!1}};function xi(s,e){let t=new tt,r="email_input",i=null,n=()=>{i?.clear()},o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),l=document.querySelector("#password-input"),c=document.querySelector("#full-name"),d=document.querySelector("#google-login"),u=document.querySelector("#apple-login"),p=document.querySelector("#microsoft-login"),m=document.querySelector("[email-element]"),y=document.querySelector("[different-provider]"),S=document.querySelector("[different-provider-name]"),b=document.querySelector("[different-provider-reset]"),R=document.querySelector("[email-signup-success]"),h=document.querySelector("[email-signup-error]"),g=document.querySelector("[error-message]"),L=document.querySelector("[verification-email]"),P=document.querySelector("[email-signup-retry]"),de=document.querySelector("[email-signup-reset]"),J=document.querySelector("[scim-div]"),ie=document.querySelector("[scim-reset]"),D=document.querySelector("[forgot-password]"),be=document.querySelector("[forgot-password-success]"),st=document.querySelector("[forgot-password-email]"),te=document.querySelector("[unverified-email]"),it=document.querySelector("[unverified-email-address]"),ue=document.querySelector("[resend-verification-email]"),ke=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(d&&d.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(s)}catch(_){console.error("Error during Google sign-in:",_)}}),u&&u.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","apple"),await t.signInWithApple(s)}catch(_){console.error("Error during Apple sign-in:",_)}}),p&&p.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(s)}catch(_){console.error("Error during Microsoft sign-in:",_)}}));let X=()=>{n(),y&&(y.style.display="none"),R&&(R.style.display="none"),h&&(h.style.display="none"),te&&(te.style.display="none"),J&&(J.style.display="none"),D&&(D.style.display="none"),be&&(be.style.display="none"),rt();let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="block"),m&&(m.style.display="flex"),a&&(a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled")),l&&(l.value="",l.style.display="none",l.removeAttribute("required"),Nt(l)),c&&(c.value="",c.style.display="none",c.removeAttribute("required"));let v=document.querySelector("[captcha-embed]"),A=document.querySelector("#h-captcha-container");v&&(v.style.display="none"),A&&(A.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),r="email_input",a&&a.focus()},Se=()=>{m&&(m.style.display="flex"),a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),l&&(l.style.display="block",l.setAttribute("required","true"),l.focus()),c&&(c.style.display="none",c.removeAttribute("required"));let _=document.querySelector("[captcha-embed]"),v=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),v&&(v.style.display="block"),D&&(D.style.display="block",D.onclick=async()=>{let A=a?.value||"",x=D.textContent||"";try{let{hcaptcha:F}=window;if(!F)throw new Error("Verification system not loaded. Please refresh the page.");D.style.pointerEvents="none",D.textContent="Sending...";let{response:I}=await F.execute({async:!0});if(!I)throw new Error("Verification cancelled");await j.requestPasswordReset(A,I),F.reset(),m&&(m.style.display="none"),D&&(D.style.display="none"),be&&(be.style.display="block"),st&&(st.textContent=A)}catch(F){console.error("Error sending password reset email:",F),D.textContent=x,D.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",g&&(g.textContent=F instanceof Error?F.message:"Failed to send reset email"))}}),r="login"},nt=()=>{a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),l&&(l.style.display="block",l.setAttribute("required","true"),l.focus()),c&&(c.style.display="block",c.setAttribute("required","true"));let _=document.querySelector("[captcha-embed]"),v=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),v&&(v.style.display="block"),r="signup"},ot=()=>{let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="none"),J&&(J.style.display="block"),ie&&(ie.onclick=()=>{J&&(J.style.display="none"),_&&(_.style.display="block"),X()})},Me=_=>{n();let v=ls(_);m&&(m.style.display="none"),y&&(y.style.display="block"),S&&(S.textContent=v),b&&(b.onclick=()=>{y&&(y.style.display="none"),X()}),r="oauth_user"};i=yi({client:t,redirectUrl:s,isWorkosCapable:()=>!0,beforeShow:()=>{m&&(m.style.display="none"),te&&(te.style.display="none")},onAuthenticated:async _=>{n(),t.setCookies(_.access_token,_.refresh_token),localStorage.setItem("email",_.email),localStorage.setItem("user_id",_.user_id),localStorage.setItem("signin_provider","email");let v=[_.first_name,_.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(_.access_token,_.refresh_token,v):window.location.href=s},onMissingChallenge:Se,onReset:X});let Ne=_=>{m&&(m.style.display="none"),te&&(te.style.display="block"),it&&(it.textContent=_),ue&&(ue.onclick=async()=>{let v=ue.textContent||"";try{let A=await gr();await t.resendVerificationEmail(_,s,A),ue.textContent="Verification email resent! \u2705",ue.style.textDecoration="none"}catch(A){ue.textContent=v,h&&(h.style.display="block"),g&&(g.textContent=Mt(A,"Unable to resend verification."))}finally{Ue()?.reset()}}),ke&&(ke.onclick=()=>{te&&(te.style.display="none"),X()}),r="unverified_email"},qe=_=>_i(_,{showSso:()=>Me("workos"),showScim:ot,showLogin:Se,showError:v=>{h&&(h.style.display="block"),g&&(g.textContent=v)}}),De=async(_,v)=>{let A=v.value;v.classList.add("loading"),v.value="";try{let x=await j.checkUserStatus(_);v.classList.remove("loading"),v.value=A,!x.exists&&x.scim_managed?ot():x.enforce_sso?Me("workos"):x.exists&&x.provider&&x.provider!=="email"&&x.provider!=="workos"?Me(x.provider):x.exists&&x.provider==="workos"?Se():x.exists&&x.provider==="email"&&!x.verified?Ne(_):x.exists&&x.provider==="email"?Se():nt()}catch(x){console.error("Error checking user status:",x),v.classList.remove("loading"),v.value=A,qe(x)||nt()}},qt=async(_,v,A,x)=>{if(!v||v.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}let F=window.hcaptcha?.getResponse()||"";if(!F){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}A.classList.add("loading"),A.value="";try{if(e?.mcpLoginState){let N=await j.signInWithEmail({email:_,password:v,mcp_login_state:e.mcpLoginState,workos_capable:Ti()});if(!N.redirect_url)throw new Error(N.error||"Unable to continue connector login. Please try again.");O("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=N.redirect_url;return}let I=Ti(),M=await t.signInWithPassword(_,v,F,{workosCapable:I,provision:!1});if(M.kind==="otp"){if(!I)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let N={pendingAuthenticationToken:M.challenge.pending_authentication_token,email:Q(M.challenge.email||_)};Ue()?.reset(),A.classList.remove("loading"),A.value=x,i?.show(N);return}t.setCookies(M.accessToken,M.refreshToken),localStorage.setItem("email",_),e?.onLoginSuccess?await e.onLoginSuccess(M.accessToken,M.refreshToken,M.fullName):window.location.href=s}catch(I){window.hcaptcha&&window.hcaptcha.reset(),A.classList.remove("loading"),A.value=x,!qe(I)&&h&&(h.style.display="block",g&&(g.textContent=Mt(I,"Unable to sign in. Please try again.")))}},at=async(_,v,A,x,F)=>{if(!v||v.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}if(v.trim().toLowerCase()===_.trim().toLowerCase()){Zr(l,"Password can't be the same as your email address.");return}if(!A||A.trim().length<2){h&&(h.style.display="block",g&&(g.textContent="Please enter your full name"));return}let I=Qr(A,v);if(I){h&&(h.style.display="block",g&&(g.textContent=I));return}let M=window.hcaptcha?.getResponse()||"";if(!M){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}x.classList.add("loading"),x.value="";try{let N=await t.signUpWithPassword(_,v,A,s,M,{workosCapable:!0});if(window.hcaptcha&&window.hcaptcha.reset(),x.classList.remove("loading"),x.value=F,m&&(m.style.display="none"),h&&(h.style.display="none"),Vt(N)){let W={pendingAuthenticationToken:N.pending_authentication_token,email:Q(N.email||_)};i?.show(W);return}R&&(R.style.display="block"),L&&(L.textContent=_),P&&(Xr(P,30),P.onclick=async()=>{if(P.style.pointerEvents!=="none")try{let W=await gr();await t.resendVerificationEmail(_,s,W,{workosCapable:!0}),Xr(P,30)}catch(W){h&&(h.style.display="block"),g&&(g.textContent=Mt(W,"Unable to resend verification. Please try again."))}finally{Ue()?.reset()}}),de&&(de.onclick=()=>{R&&(R.style.display="none"),wi(),X()})}catch(N){x.classList.remove("loading"),x.value=F,Ue()?.reset();let W=Si(N);W&&l?Zr(l,W):!qe(N)&&h&&(h.style.display="block",g&&(g.textContent=Mt(N,"Unable to create the account. Please try again.")))}};return o&&l&&c&&(bi(l,c,o.querySelector('[type="submit"]')),l.addEventListener("input",()=>Nt(l))),o&&o.addEventListener("submit",async _=>{_.stopPropagation(),_.preventDefault();let v=Q(a?.value||"");a&&(a.value=v);let A=l?.value||"",x=c?.value||"";if(!v||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)){h&&(h.style.display="block",g&&(g.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),g&&(g.textContent=""),l&&Nt(l);let I=o.querySelector('[type="submit"]'),M=I?.value||"";localStorage.setItem("signin_provider","email");try{r==="email_input"?await De(v,I):r==="login"?await qt(v,A,I,M):r==="signup"&&await at(v,A,x,I,M)}catch(N){console.error("Auth flow error:",N),I&&(I.classList.remove("loading"),I.value=M),h&&(h.style.display="block")}}),{reset:X}}var _r=function(){return _r=Object.assign||function(s){for(var e,t=1,r=arguments.length;t<r;t++)for(var i in e=arguments[t])Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=e[i]);return s},_r.apply(this,arguments)},Ai=function(){function s(e,t,r){var i=this;this.endVal=t,this.options=r,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){i.startTime||(i.startTime=n);var o=n-i.startTime;i.remaining=i.duration-o,i.useEasing?i.countDown?i.frameVal=i.startVal-i.easingFn(o,0,i.startVal-i.endVal,i.duration):i.frameVal=i.easingFn(o,i.startVal,i.endVal-i.startVal,i.duration):i.frameVal=i.startVal+(i.endVal-i.startVal)*(o/i.duration);var a=i.countDown?i.frameVal<i.endVal:i.frameVal>i.endVal;i.frameVal=a?i.endVal:i.frameVal,i.frameVal=Number(i.frameVal.toFixed(i.options.decimalPlaces)),i.printValue(i.frameVal),o<i.duration?i.rAF=requestAnimationFrame(i.count):i.finalEndVal!==null?i.update(i.finalEndVal):i.options.onCompleteCallback&&i.options.onCompleteCallback()},this.formatNumber=function(n){var o,a,l,c,d=n<0?"-":"";o=Math.abs(n).toFixed(i.options.decimalPlaces);var u=(o+="").split(".");if(a=u[0],l=u.length>1?i.options.decimal+u[1]:"",i.options.useGrouping){c="";for(var p=3,m=0,y=0,S=a.length;y<S;++y)i.options.useIndianSeparators&&y===4&&(p=2,m=1),y!==0&&m%p==0&&(c=i.options.separator+c),m++,c=a[S-y-1]+c;a=c}return i.options.numerals&&i.options.numerals.length&&(a=a.replace(/[0-9]/g,function(b){return i.options.numerals[+b]}),l=l.replace(/[0-9]/g,function(b){return i.options.numerals[+b]})),d+i.options.prefix+a+l+i.options.suffix},this.easeOutExpo=function(n,o,a,l){return a*(1-Math.pow(2,-10*n/l))*1024/1023+o},this.options=_r(_r({},this.defaults),r),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 i.handleScroll(i)}),window.onscroll=function(){window.onScrollFns.forEach(function(n){return n()})},this.handleScroll(this)))}return s.prototype.handleScroll=function(e){if(e&&window&&!e.once){var t=window.innerHeight+window.scrollY,r=e.el.getBoundingClientRect(),i=r.top+window.pageYOffset,n=r.top+r.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||i>t)&&!e.paused&&e.reset()}},s.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 r=this.countDown?1:-1;this.endVal=e+r*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},s.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))},s.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},s.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)},s.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))},s.prototype.printValue=function(e){var t;if(this.el){var r=this.formattingFn(e);!((t=this.options.plugin)===null||t===void 0)&&t.render?this.options.plugin.render(this.el,r):this.el.tagName==="INPUT"?this.el.value=r:this.el.tagName==="text"||this.el.tagName==="tspan"?this.el.textContent=r:this.el.innerHTML=r}},s.prototype.ensureNumber=function(e){return typeof e=="number"&&!isNaN(e)},s.prototype.validateValue=function(e){var t=Number(e);return this.ensureNumber(t)?t:(this.error="[CountUp] invalid start or end value: ".concat(e),null)},s.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},s.prototype.parse=function(e){var t=function(o){return o.replace(/([.,' ])/g,"\\$1")},r=t(this.options.separator),i=t(this.options.decimal),n=e.replace(new RegExp(r,"g"),"").replace(new RegExp(i,"g"),".");return parseFloat(n)},s}();var Li=!1;function Ri(){if(Li)return;Li=!0;let s=document.querySelectorAll("[number-count]"),e=new IntersectionObserver(t=>{t.forEach(r=>{if(r.isIntersecting){let i=r.target;e.unobserve(i);let n=i.dataset.countDirection||"up",o=parseFloat(i.dataset.countOffset||"10")/100,a=parseFloat(i.dataset.countDuration||"2"),l=5,c=i.dataset.countTarget||i.textContent?.trim()||"0",d=parseFloat(c.replace(/,/g,""));if(isNaN(d))return;let u=d*o,p=Math.max(u,l),m=n==="down"?d+p:Math.max(0,d-p);new Ai(i,d,{startVal:Math.round(m),duration:a,useGrouping:!0}).start()}})},{threshold:0});s.forEach(t=>{t.dataset.countTarget=t.textContent?.trim()||"0",e.observe(t)})}var Ci=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});async function to(s){let t=new TextEncoder().encode(s.toLowerCase().trim()),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=setTimeout(()=>{document.body.style.visibility="visible"},4e3),e=new tt,{accessToken:t,refreshToken:r}=us(),i=document.querySelector("[auth-section]"),n=document.querySelector("[waitlist-content]"),o=document.querySelectorAll("[logout-button]"),a=document.querySelector("[stats-skeleton]"),l=document.querySelector("[stats-wrap]"),c=document.querySelector("[error-div]"),d=document.querySelector("[error-text]"),u=document.querySelector("[waitlist-rank]"),p=document.querySelector("[spots]"),m=document.querySelectorAll("[referral-code]"),y=document.querySelector("[referral-count]"),S=document.querySelector("[desktop-bonus-remaining]"),b=document.querySelector("[desktop-bonus-complete]"),R=document.querySelector("[climbed-dropped]"),h=document.querySelector("[keep-moving]"),g=document.querySelector("[rank-arrow-wrap]"),L=document.querySelector("[cohort-text]"),P=document.querySelector("[top-100]"),de=document.querySelector("[top-1000]"),J=document.querySelector("[top-100k]"),ie=document.querySelector("[sms-bonus-remaining]"),D=document.querySelector("[sms-bonus-complete]"),be=document.querySelector("[total-boost]"),st=document.querySelector("[social-media-details]"),te=document.querySelector("[sms-popup-button]"),it=document.querySelector("[app-download]"),ue=document.querySelector("[file-upload]"),ke=document.querySelector("[file-input]"),X=document.querySelector("[file-validation-error]"),Se=document.querySelector("[file-upload-loading]"),nt=document.querySelector("[cancel-upload-button]"),ot=document.querySelector("[file-upload-verified]"),Me=document.querySelector("[boost-earned]"),yr=document.querySelector("[boost-earned-location]"),Ne=document.querySelector("[woohoo-button]"),qe=document.querySelector("[file-upload-failed]"),De=document.querySelector("[upload-failed-text]"),qt=document.querySelector("[close-button]"),at=document.querySelector("[share-on-x]"),_=document.querySelector("[share-on-linkedin]"),v=document.querySelector("[share-on-whatsapp]"),A=document.querySelector("[share-on-slack]"),x=document.querySelector("[share-on-discord]"),F=document.querySelector("[social-media-bonus-remaining]"),I=document.querySelector("[social-media-bonus-complete]"),M=document.querySelector("[share-on-other-channel]");st&&st.addEventListener("click",()=>{O("android_waitlist_social_details_opened"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_details_opened"})}),te&&te.addEventListener("click",()=>{O("android_waitlist_sms_button_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_button_clicked"})}),it&&it.addEventListener("click",()=>{window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_app_download",source:"android-waitlist-page"}),O("android_waitlist_download_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_download_clicked"})});let N=async()=>{clearTimeout(s),document.body.style.visibility="visible",o.forEach(Ft=>{Ft.style.display="none"}),n&&(n.style.display="block");let W=window.__abVariantPromise?await window.__abVariantPromise:"control",Fe=document.querySelector("[auth-hero-default]"),G=document.querySelector("[auth-hero-v1]"),re=document.querySelector("[auth-hero-v2]");Fe&&(Fe.style.display="none"),G&&(G.style.display="none"),re&&(re.style.display="none"),W==="dictation-broken"&&G?G.style.display="block":W==="smartest"&&re?re.style.display="block":Fe&&(Fe.style.display="block"),n&&(n.style.display="none"),i&&(i.style.display="block");let Dt=document.querySelector("[reusable-section-wrap]");Dt&&i&&i.appendChild(Dt);let lt=document.querySelector(".wl_cohort-spot-wrap");lt&&(lt.style.display="none"),window.dispatchEvent(new CustomEvent("waitlist:auth-section-ready")),O("android_waitlist_auth_shown"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_auth_shown"}),xi(`${window.location.origin}/android-waitlist`)};if(!t||!r){await N();return}try{e.setCookies(t,r);let W=e.checkAndSetSession(),Fe=new Promise((f,k)=>setTimeout(()=>k(new Error("Session timeout")),3e3));await Promise.race([W,Fe]),e.sessionData&&e.setCookies(e.sessionData.access_token,e.sessionData.refresh_token),clearTimeout(s),document.body.style.visibility="visible",n&&(n.style.display="block"),o.forEach(f=>{f.style.display="flex",f.dataset.bound||(f.dataset.bound="true",f.addEventListener("click",async k=>{k.preventDefault();try{await e.signOut()}finally{localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("android_waitlist_last_rank"),localStorage.removeItem("signin_provider"),sessionStorage.removeItem("referral_status"),window.location.href="/android-waitlist"}}))});let G=e.sessionData?.access_token,re=e.sessionData?.user.email,Dt=e.sessionData?.user.user_metadata.full_name||" ",[lt,Ft]=as(Dt),ct=e.sessionData?.user.id;localStorage.setItem("email",re),ct&&localStorage.setItem("user_id",ct),ct&&Ei(ct,{email:re,firstName:lt,lastName:Ft});let Pi=Ci(),{dub_id:wr,referral:vr,promo_code:es}=Pi,Oi=!!localStorage.getItem("conversion_sent"),He=!localStorage.getItem("android_waitlist_joined"),$={signup:{success:null,error:null},referral:{success:null,error:null},waitlist:{success:null,error:null},stats:{success:null,error:null}},Ii={access_token:G,first_name:lt,last_name:Ft,dub_click_id:wr||void 0,referral:vr||void 0,promo_code:es||void 0};try{await j.signupUser(Ii),$.signup.success=!0}catch(f){$.signup.success=!1,$.signup.error=f instanceof Error?f.message:"Unknown error"}try{let f=await j.ensureReferralCode(G);if($.referral.success=f.ok,!f.ok){let k=await f.json().catch(()=>({}));$.referral.error=k.detail||k.message||`Status ${f.status}`}}catch(f){$.referral.success=!1,$.referral.error=f instanceof Error?f.message:"Network error"}Oi||(O("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:"android",dub_id:wr||void 0,referral:vr||void 0,email:re,user_id:ct||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown"}),localStorage.setItem("conversion_sent","true"));let ji={email:re,device_type:"android"},ts=!1;try{await j.addToWaitlist(ji),$.waitlist.success=!0,ts=!0}catch(f){$.waitlist.success=!1,$.waitlist.error=f instanceof Error?f.message:"Unknown error"}He&&ts&&(localStorage.setItem("android_waitlist_joined","true"),O("app_waitlist",{device_type:"android",source:"android-waitlist-page"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_waitlist",device_type:"android",source:"android-waitlist-page"}));let K=await j.getAndroidWaitlistStats(G);if(K.status===404&&!He){O("android_waitlist_recovery_attempted",{reason:"localStorage flag set but 404 from stats API"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_attempted",reason:"localStorage flag set but 404 from stats API"}),localStorage.removeItem("android_waitlist_joined");try{let f={email:re,device_type:"android"};await j.addToWaitlist(f),localStorage.setItem("android_waitlist_joined","true"),K=await j.getAndroidWaitlistStats(G),K.ok&&(O("android_waitlist_recovery_success"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_success"}))}catch(f){console.error("Recovery addToWaitlist failed:",f)}}let $i=()=>{a&&(a.style.display="none"),l&&(l.style.display="block")};if($.stats.success=K.ok,K.status===401||K.status===429||!K.ok){let f="";try{let k=await K.json();f=JSON.stringify(k),$.stats.error=k.detail||k.message||f,d&&(d.textContent=`Status: ${K.status} | ${f}`)}catch{f="Could not parse response",$.stats.error=f,d&&(d.textContent=`Status: ${K.status} | ${f}`)}O("android_waitlist_api_error",{status:K.status,error:f,signup_success:$.signup.success,signup_error:$.signup.error,referral_success:$.referral.success,referral_error:$.referral.error,waitlist_success:$.waitlist.success,waitlist_error:$.waitlist.error,stats_error:$.stats.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_api_error",status:K.status,error:f}),a&&(a.style.display="none"),c&&(c.style.display="block");return}let H=await K.json();if(He){let f=await to(re);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:H.current_rank,user_email_hash:f})}let rs=localStorage.getItem("android_waitlist_last_rank");if(rs&&!He){let f=parseInt(rs,10);H.current_rank<f&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:H.current_rank,positions_gained:f-H.current_rank,referral_count:H.referrals_count}))}localStorage.setItem("android_waitlist_last_rank",H.current_rank.toString());let br=f=>{let k=f.current_rank;if(u){let w=k.toLocaleString("en-US");u.textContent=w,u instanceof HTMLElement&&(u.dataset.countTarget=w)}if(f.starting_rank!==null){let w=f.starting_rank-k;p&&(p.textContent=Math.abs(w).toLocaleString()),w<0?(R&&(R.textContent="fell"),h&&(h.style.display="none"),g&&g.classList.add("invert")):(R&&(R.textContent="climbed"),h&&(h.style.display="inline-block"),g&&g.classList.remove("invert"))}if(P&&P.classList.remove("active"),de&&de.classList.remove("active"),J&&J.classList.remove("active"),k<=100?P&&P.classList.add("active"):k<=1e3?de&&de.classList.add("active"):k<=1e5&&J&&J.classList.add("active"),document.querySelectorAll("[cohort-wins]").forEach(w=>{w.style.display="none"}),k<=100){let w=document.querySelector('[cohort-wins="top-100"]');w&&(w.style.display="block")}else if(k<=1e3){let w=document.querySelector('[cohort-wins="top-1000"]');w&&(w.style.display="block")}else if(k<=1e5){let w=document.querySelector('[cohort-wins="top-100k"]');w&&(w.style.display="block")}if(L)if(k<=100)L.innerHTML="You're in the <strong>top 100!</strong>";else if(k<=1e3){let w=k-100;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 100`}else if(k<=1e5){let w=k-1e3;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 1,000`}else{let w=k-1e5;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 100,000`}m.forEach(w=>{w.textContent=f.referral_code}),y&&(y.textContent=f.referrals_count.toString()),f.desktop_dictation_bonus_earned?(S&&(S.style.display="none"),b&&(b.style.display="block")):(S&&(S.style.display="block"),b&&(b.style.display="none")),f.phone_number_bonus_earned?(ie&&(ie.style.display="none"),D&&(D.style.display="block")):(ie&&(ie.style.display="block"),D&&(D.style.display="none")),f.verified_share_twitter&&at&&at.classList.add("verified"),f.verified_share_linkedin&&_&&_.classList.add("verified"),f.verified_share_whatsapp&&v&&v.classList.add("verified"),f.verified_share_slack&&A&&A.classList.add("verified"),f.verified_share_discord&&x&&x.classList.add("verified");let B=f.verified_share_twitter&&f.verified_share_linkedin&&f.verified_share_whatsapp&&f.verified_share_slack&&f.verified_share_discord;if(B&&(F&&(F.style.display="none"),I&&(I.style.display="block")),be){let w=[f.phone_number_bonus_earned,f.desktop_dictation_bonus_earned,B].filter(Boolean).length;be.textContent=`${w} of 3`}};br(H);let ss=f=>f<=100?"top-100":f<=1e3?"top-1000":f<=1e5?"top-100k":"below-100k";O("android_waitlist_page_view",{rank:H.current_rank,total_boost:H.total_boost,referrals_count:H.referrals_count,cohort:ss(H.current_rank),is_first_visit:He}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_page_view",rank:H.current_rank,total_boost:H.total_boost,referrals_count:H.referrals_count,cohort:ss(H.current_rank),is_first_visit:He});let Ui=`https://wisprflow.ai/waitlist?${H.referral_code}`;document.querySelectorAll("[share]").forEach(f=>{let k=f.getAttribute("share");if(!k)return;let w=document.querySelector(`[share-content="${k}"]`)?.textContent||"";f.addEventListener("click",async()=>{switch(O("android_waitlist_share_clicked",{platform:k}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_share_clicked",platform:k}),k){case"x":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(w)}`,"_blank");break;case"linkedin":await navigator.clipboard.writeText(w),window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(Ui)}`,"_blank");break;case"whatsapp":window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(w)}`,"_blank");break;case"slack":await navigator.clipboard.writeText(w),window.open("slack://open","_self");break;case"discord":await navigator.clipboard.writeText(w),window.open("https://discord.com/app","_blank");break}})}),window.addEventListener("sms:submit",async f=>{let k=f,{phoneNumber:B}=k.detail;try{let w=await j.submitPhoneNumber(B,G),he=await w.json();if(!w.ok||!he.success){let Ht=he.error||"Something went wrong";window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:Ht}})),O("android_waitlist_sms_error",{error:Ht}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:Ht});return}window.dispatchEvent(new CustomEvent("sms:success"));let fe=await j.getAndroidWaitlistStats(G);fe.ok&&br(await fe.json()),O("android_waitlist_sms_submitted",{boost_earned:he.boost_earned,new_rank:he.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_submitted",boost_earned:he.boost_earned,new_rank:he.current_rank})}catch(w){console.error("SMS submission error:",w),window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:"Network error. Please try again."}})),O("android_waitlist_sms_error",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:"network_error"})}});let _e=f=>{ue&&(ue.style.display=f==="idle"?"block":"none"),Se&&(Se.style.display=f==="loading"?"block":"none"),ot&&(ot.style.display=f==="verified"?"block":"none"),qe&&(qe.style.display=f==="failed"?"block":"none"),X&&(X.style.display="none")},Mi=f=>{let B=["image/png","image/jpeg","image/jpg"];return f.size>20971520?"File too large. Maximum size is 20MB.":B.includes(f.type)?null:"Please upload a PNG or JPEG image."},Ni={social_share_x:"X",social_share_linkedin:"LinkedIn",social_share_whatsapp:"WhatsApp",social_share_slack:"Slack",social_share_discord:"Discord"},qi=f=>Ni[f]||"Social Media",Di={social_share_x:at,social_share_linkedin:_,social_share_whatsapp:v,social_share_slack:A,social_share_discord:x},Fi=f=>{let k=Di[f];k&&k.classList.add("verified")},Hi=f=>({file_too_large:"File exceeds 20MB limit. (file_too_large)",invalid_file_type:"Please upload a PNG or JPEG. (invalid_file_type)","User not on Android waitlist":"Please join the waitlist first. (User not on Android waitlist)",all_platforms_already_claimed:"You've claimed all social share bonuses! (all_platforms_already_claimed)",x_already_claimed:"You've already received the X bonus. (x_already_claimed)",linkedin_already_claimed:"You've already received the LinkedIn bonus. (linkedin_already_claimed)",whatsapp_already_claimed:"You've already received the WhatsApp bonus. (whatsapp_already_claimed)",slack_already_claimed:"You've already received the Slack bonus. (slack_already_claimed)",discord_already_claimed:"You've already received the Discord bonus. (discord_already_claimed)",not_posted:"This looks like a draft, not a published post. (not_posted)",no_wispr_mention:"Post must mention Wispr Flow or wisprflow.ai. (no_wispr_mention)",invalid:"We couldn't verify this screenshot. Try a clearer image. (invalid)","An error occurred":"Something went wrong. Please try again. (An error occurred)"})[f??""]??`Verification failed. (${f})`,dt=null;ke&&ke.addEventListener("change",async()=>{let f=ke.files?.[0];if(!f)return;ke.value="";let k=Mi(f);if(k){X&&(X.textContent=k,X.style.display="block"),O("android_waitlist_social_validation_error",{error:k}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_validation_error",error:k});return}O("android_waitlist_social_upload_started"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_started"}),_e("loading"),dt=new AbortController;try{let B=await j.submitSocialShare(f,G,dt.signal),w=await B.json();if(!B.ok||!w.success){_e("failed"),De&&(De.textContent=Hi(w.error)),O("android_waitlist_social_upload_failed",{error:w.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:w.error});return}_e("verified"),Me&&(Me.textContent=w.boost_earned.toLocaleString()),yr&&(yr.textContent=qi(w.action)),Fi(w.action);let he=await j.getAndroidWaitlistStats(G);if(he.ok){let fe=await he.json();br(fe),fe.verified_share_twitter&&fe.verified_share_linkedin&&fe.verified_share_whatsapp&&fe.verified_share_slack&&fe.verified_share_discord&&(Ne&&(Ne.style.display="none"),M&&(M.style.display="none"),O("android_waitlist_social_all_claimed"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_all_claimed"}))}O("android_waitlist_social_share_verified",{platform:w.action,boost_earned:w.boost_earned,new_rank:w.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_share_verified",platform:w.action,boost_earned:w.boost_earned,new_rank:w.current_rank})}catch(B){if(B instanceof Error&&B.name==="AbortError"){_e("idle");return}console.error("Social share upload error:",B),_e("failed"),De&&(De.textContent="Network error. Please try again."),O("android_waitlist_social_upload_failed",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:"network_error"})}finally{dt=null}}),nt&&nt.addEventListener("click",()=>{dt&&dt.abort(),_e("idle"),O("android_waitlist_social_upload_cancelled"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_cancelled"})}),Ne&&Ne.addEventListener("click",()=>{_e("idle")}),qt&&qt.addEventListener("click",()=>{_e("idle")}),$i(),window.dispatchEvent(new CustomEvent("waitlist:stats-ready")),Ri()}catch(W){console.error("Error on android-waitlist page:",W),e.setCookie("access_token","",-1),e.setCookie("refresh_token","",-1),await N()}});})();
|
|
1
|
+
"use strict";(()=>{var Fi=Object.create;var Ft=Object.defineProperty;var Hi=Object.getOwnPropertyDescriptor;var Wi=Object.getOwnPropertyNames;var Vi=Object.getPrototypeOf,Bi=Object.prototype.hasOwnProperty;var zi=(s,e)=>()=>(s&&(e=s(s=0)),e);var ie=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ji=(s,e)=>{for(var t in e)Ft(s,t,{get:e[t],enumerable:!0})},ss=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Wi(e))!Bi.call(s,i)&&i!==t&&Ft(s,i,{get:()=>e[i],enumerable:!(r=Hi(e,i))||r.enumerable});return s};var is=(s,e,t)=>(t=s!=null?Fi(Vi(s)):{},ss(e||!s||!s.__esModule?Ft(t,"default",{value:s,enumerable:!0}):t,s)),Gi=s=>ss(Ft({},"__esModule",{value:!0}),s);var Te={};Ji(Te,{Headers:()=>Sr,Request:()=>Zi,Response:()=>en,default:()=>kr,fetch:()=>Qi});var Xi,Be,Qi,kr,Sr,Zi,en,ye=zi(()=>{"use strict";Xi=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")},Be=Xi(),Qi=Be.fetch,kr=Be.fetch.bind(Be),Sr=Be.Headers,Zi=Be.Request,en=Be.Response});var hs=ie(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});var Er=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Tr.default=Er});var Ar=ie(pt=>{"use strict";var fs=pt&&pt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(pt,"__esModule",{value:!0});var rn=fs((ye(),Gi(Te))),sn=fs(hs()),xr=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=rn.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 r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let c=null,d=null,u=null,p=n.status,m=n.statusText;if(n.ok){if(this.method!=="HEAD"){let R=await n.text();R===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?d=R:d=JSON.parse(R))}let k=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),b=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");k&&b&&b.length>1&&(u=parseInt(b[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(d)&&(d.length>1?(c={code:"PGRST116",details:`Results contain ${d.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},d=null,u=null,p=406,m="Not Acceptable"):d.length===1?d=d[0]:d=null)}else{let k=await n.text();try{c=JSON.parse(k),Array.isArray(c)&&n.status===404&&(d=[],c=null,p=200,m="OK")}catch{n.status===404&&k===""?(p=204,m="No Content"):c={message:k}}if(c&&this.isMaybeSingle&&(!((l=c?.details)===null||l===void 0)&&l.includes("0 rows"))&&(c=null,p=200,m="OK"),c&&this.shouldThrowOnError)throw new sn.default(c)}return{error:c,data:d,count:u,status:p,statusText:m}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,l;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:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};pt.default=xr});var Rr=ie(mt=>{"use strict";var nn=mt&&mt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(mt,"__esModule",{value:!0});var on=nn(Ar()),Lr=class extends on.default{select(e){let t=!1,r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:i=r}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.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:r=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let l=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${c}"; options=${l};`,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}};mt.default=Lr});var Jt=ie(gt=>{"use strict";var an=gt&>.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(gt,"__esModule",{value:!0});var ln=an(Rr()),Cr=class extends ln.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 r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),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:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};gt.default=Cr});var Or=ie(yt=>{"use strict";var cn=yt&&yt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(yt,"__esModule",{value:!0});var _t=cn(Jt()),Pr=class{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){let i=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),r&&(this.headers.Prefer=`count=${r}`),new _t.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new _t.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let l=e.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(l.length>0){let c=[...new Set(l)].map(d=>`"${d}"`);this.url.searchParams.set("columns",c.join(","))}}return new _t.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new _t.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new _t.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};yt.default=Pr});var ps=ie(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.version=void 0;Gt.version="0.0.0-automated"});var ms=ie(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.DEFAULT_HEADERS=void 0;var dn=ps();Kt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${dn.version}`}});var _s=ie(wt=>{"use strict";var gs=wt&&wt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(wt,"__esModule",{value:!0});var un=gs(Or()),hn=gs(Jt()),fn=ms(),Ir=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},fn.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new un.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new s(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),l;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([d,u])=>u!==void 0).map(([d,u])=>[d,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([d,u])=>{a.searchParams.append(d,u)})):(o="POST",l=t);let c=Object.assign({},this.headers);return n&&(c.Prefer=`count=${n}`),new hn.default({method:o,url:a,headers:c,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};wt.default=Ir});var Ss=ie(V=>{"use strict";var vt=V&&V.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(V,"__esModule",{value:!0});V.PostgrestBuilder=V.PostgrestTransformBuilder=V.PostgrestFilterBuilder=V.PostgrestQueryBuilder=V.PostgrestClient=void 0;var ys=vt(_s());V.PostgrestClient=ys.default;var ws=vt(Or());V.PostgrestQueryBuilder=ws.default;var vs=vt(Jt());V.PostgrestFilterBuilder=vs.default;var bs=vt(Rr());V.PostgrestTransformBuilder=bs.default;var ks=vt(Ar());V.PostgrestBuilder=ks.default;V.default={PostgrestClient:ys.default,PostgrestQueryBuilder:ws.default,PostgrestFilterBuilder:vs.default,PostgrestTransformBuilder:bs.default,PostgrestBuilder:ks.default}});var Os=ie((Vo,Ps)=>{"use strict";Ps.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Ht=s=>s.verification_method==="email_otp"&&typeof s.pending_authentication_token=="string"&&s.pending_authentication_token.length>0,M="https://api.wisprflow.ai",re=class extends Error{constructor(t,r,i,n=null){super(i);this.status=t;this.code=r;this.passwordRejectionMessage=n;this.name="AriaAuthError"}},X=s=>s.trim().toLowerCase(),ns=(s,e)=>{let t=new Set(["verification_failed","invalid_credentials","sso_required","scim_managed_domain","sign_in_to_continue","identity_conflict","rate_limited","provider_unavailable","validation_error"]);return typeof s.code=="string"?s.code:s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"&&typeof s.detail.code=="string"?s.detail.code:typeof s.detail=="string"&&t.has(s.detail)?s.detail:{401:"invalid_credentials",409:"identity_conflict",422:"validation_error",429:"rate_limited",503:"provider_unavailable"}[e]??"authentication_failed"},ut=(s,e)=>({verification_failed:"Incorrect or expired code. Try again.",invalid_credentials:"Incorrect email or password.",sso_required:"Sign in with SSO to continue.",scim_managed_domain:"This account is managed by your organization.",sign_in_to_continue:"This account already exists. Sign in to continue.",identity_conflict:"We couldn't continue with this account. Try again or contact support.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again.",invalid_code:"Enter the six-digit code."})[s]??(e===403?"This sign-in method is not available for this account.":"Unable to complete authentication. Please try again."),Ki=(s,e,t)=>[s.message,s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"?s.detail.message:null,typeof s.detail=="string"?s.detail:null].find(n=>typeof n=="string"&&n.length>0&&n!==e)??ut(e,t),Ve=(s,e)=>{let t=ns(s,e);return new re(e,t,Ki(s,t,e),e===400&&typeof s.detail=="string"&&s.detail.length>0?s.detail:null)},Yi=(s,e)=>{let t=ns(s,e);return new re(e,t,ut(t,e))},br=class{static async signupUser(e){try{let t=`${M}/signup`,i=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=i&&i.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(`${M}/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(`${M}/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(`${M}/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(`${M}/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){let t=X(e),r=await fetch(`${M}/user_status?email=${encodeURIComponent(t)}`),i=await r.json().catch(()=>({}));if(!r.ok)throw Ve(i,r.status);return i}static async requestPasswordReset(e,t){let r=await fetch(`${M}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:X(e),captcha_token:t})});if(!r.ok){let i=await r.json().catch(()=>({}));throw Ve(i,r.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${M}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:X(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ve(r,t.status);return r}static async signInWithCaptcha(e){let t=await fetch(`${M}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:X(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ve(r,t.status);return r}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${M}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:X(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ve(r,t.status);return r}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new re(422,"invalid_code",ut("invalid_code",422));let t=await fetch(`${M}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json().catch(()=>({}));if(!t.ok){let i=Yi(r,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new re(t.status,"verification_failed",ut("verification_failed",t.status))}if(r.provider!=="workos"||!r.access_token||!r.refresh_token||!r.user_id||!r.email)throw new re(t.status,"authentication_failed",ut("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${M}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:X(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Ve(r,t.status);return r}static async getSubscriptionStatus(e){return await fetch(`${M}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${M}/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,r){let i=`${M}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return r&&(i+=`¤cy=${r}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${M}/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(`${M}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${M}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${M}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,r){let i=new FormData;return i.append("screenshot",e),await fetch(`${M}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:r})}};function os(s){let[e,...t]=s.split(" "),r=t.join(" ");return[e,r]}function as(s){return s==="azure"?"Microsoft":s==="workos"?"SSO":s.charAt(0).toUpperCase()+s.slice(1)}var $=br;var ls=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var cs=()=>{let s=window.location.hash.substring(1),e=new URLSearchParams(s);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var ds=()=>{let{access_token:s,refresh_token:e}=cs(),t=s,r=e;if(!t||!r){let i=ls();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var us=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ye(),Te)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var ht=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Wt=class extends ht{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Vt=class extends ht{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Bt=class extends ht{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},zt;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(zt||(zt={}));var tn=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},ft=class{constructor(e,{headers:t={},customFetch:r,region:i=zt.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=us(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return tn(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let c;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",c=o):typeof o=="string"?(a["Content-Type"]="text/plain",c=o):typeof FormData<"u"&&o instanceof FormData?c=o:(a["Content-Type"]="application/json",c=JSON.stringify(o)));let d=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:c}).catch(y=>{throw new Wt(y)}),u=d.headers.get("x-relay-error");if(u&&u==="true")throw new Vt(d);if(!d.ok)throw new Bt(d);let p=((r=d.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),m;return p==="application/json"?m=yield d.json():p==="application/octet-stream"?m=yield d.blob():p==="text/event-stream"?m=d:p==="multipart/form-data"?m=yield d.formData():m=yield d.text(),{data:m,error:null}}catch(i){return{data:null,error:i}}})}};var Es=is(Ss(),1),{PostgrestClient:Ts,PostgrestQueryBuilder:To,PostgrestFilterBuilder:xo,PostgrestTransformBuilder:Ao,PostgrestBuilder:Lo}=Es.default;var xs="2.10.2";var As={"X-Client-Info":`realtime-js/${xs}`},Ls="1.0.0",Xt=1e4,Rs=1e3,xe;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(xe||(xe={}));var z;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(z||(z={}));var K;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(K||(K={}));var Yt;(function(s){s.websocket="websocket"})(Yt||(Yt={}));var we;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(we||(we={}));var bt=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),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+i));o=o+i;let l=r.decode(e.slice(o,o+n));o=o+n;let c=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:c}}};var Ae=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 C;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(C||(C={}));var $r=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=pn(o,s,e,i),n),{})},pn=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?Cs(n,o):jr(o)},Cs=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return yn(e,t)}switch(s){case C.bool:return mn(e);case C.float4:case C.float8:case C.int2:case C.int4:case C.int8:case C.numeric:case C.oid:return gn(e);case C.json:case C.jsonb:return _n(e);case C.timestamp:return wn(e);case C.abstime:case C.date:case C.daterange:case C.int4range:case C.int8range:case C.money:case C.reltime:case C.text:case C.time:case C.timestamptz:case C.timetz:case C.tsrange:case C.tstzrange:return jr(e);default:return jr(e)}},jr=s=>s,mn=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},gn=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},_n=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},yn=(s,e)=>{if(typeof s!="string")return s;let t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n,o=s.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Cs(e,a))}return s},wn=s=>typeof s=="string"?s.replace(" ","T"):s,Qt=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var Le=class{constructor(e,t,r={},i=Xt){this.channel=e,this.event=t,this.payload=r,this.timeout=i,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 r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.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(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Ur;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Ur||(Ur={}));var ze=class s{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=s.syncState(this.state,i,n,o),this.pendingDiffs.forEach(l=>{this.state=s.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=s.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(c,d)=>{o[c]||(l[c]=d)}),this.map(o,(c,d)=>{let u=n[c];if(u){let p=d.map(b=>b.presence_ref),m=u.map(b=>b.presence_ref),y=d.filter(b=>m.indexOf(b.presence_ref)<0),k=u.filter(b=>p.indexOf(b.presence_ref)<0);y.length>0&&(a[c]=y),k.length>0&&(l[c]=k)}else a[c]=d}),this.syncDiff(n,{joins:a,leaves:l},r,i)}static syncDiff(e,t,r,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(a,l)=>{var c;let d=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),d.length>0){let u=e[a].map(m=>m.presence_ref),p=d.filter(m=>u.indexOf(m.presence_ref)<0);e[a].unshift(...p)}r(a,d,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let d=l.map(u=>u.presence_ref);c=c.filter(u=>d.indexOf(u.presence_ref)<0),e[a]=c,i(a,c,l),c.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return"metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=i,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 Mr;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Mr||(Mr={}));var Nr;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(Nr||(Nr={}));var qr;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(qr||(qr={}));var Je=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=z.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 Le(this,K.join,this.params,this.timeout),this.rejoinTimer=new Ae(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=z.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=z.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=z.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=z.errored,this.rejoinTimer.scheduleTimeout())}),this._on(K.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new ze(this),this.broadcastEndpointURL=Qt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,i;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(d=>e&&e("CHANNEL_ERROR",d)),this._onClose(()=>e&&e("CLOSED"));let l={},c={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(d=>d.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:c},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:d})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),d===void 0){e&&e("SUBSCRIBED");return}else{let p=this.bindings.postgres_changes,m=(u=p?.length)!==null&&u!==void 0?u:0,y=[];for(let k=0;k<m;k++){let b=p[k],{filter:{event:R,schema:h,table:g,filter:L}}=b,P=d&&d[k];if(P&&P.event===R&&P.schema===h&&P.table===g&&P.filter===L)y.push(Object.assign(Object.assign({},b),{id:P.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,e&&e("SUBSCRIBED");return}}).receive("error",d=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(d).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,r){return this._on(e,t,r)}async send(e,t={}){var r,i;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 l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),c.receive("ok",()=>n("ok")),c.receive("error",()=>n("error")),c.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=z.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(K.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new Le(this,K.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new Le(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:d}=K;if(r&&[a,l,c,d].indexOf(o)>=0&&r!==this._joinRef())return;let p=this._onMessage(o,t,r);if(t&&!p)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(m=>{var y,k,b;return((y=m.filter)===null||y===void 0?void 0:y.event)==="*"||((b=(k=m.filter)===null||k===void 0?void 0:k.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===o}).map(m=>m.callback(p,r)):(n=this.bindings[o])===null||n===void 0||n.filter(m=>{var y,k,b,R,h,g;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){let L=m.id,P=(y=m.filter)===null||y===void 0?void 0:y.event;return L&&((k=t.ids)===null||k===void 0?void 0:k.includes(L))&&(P==="*"||P?.toLocaleLowerCase()===((b=t.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))}else{let L=(h=(R=m?.filter)===null||R===void 0?void 0:R.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return L==="*"||L===((g=t?.event)===null||g===void 0?void 0:g.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof p=="object"&&"ids"in p){let y=p.data,{schema:k,table:b,commit_timestamp:R,type:h,errors:g}=y;p=Object.assign(Object.assign({},{schema:k,table:b,commit_timestamp:R,eventType:h,new:{},old:{},errors:g}),this._getPayloadRecords(y))}m.callback(p,r)})}_isClosed(){return this.state===z.closed}_isJoined(){return this.state===z.joined}_isJoining(){return this.state===z.joining}_isLeaving(){return this.state===z.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&s.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(K.close,{},e)}_onError(e){this._on(K.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=z.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=$r(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=$r(e.columns,e.old_record)),t}};var bn=()=>{},kn=typeof WebSocket<"u",Ge=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=As,this.params={},this.timeout=Xt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=bn,this.conn=null,this.sendBuffer=[],this.serializer=new bt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(ye(),Te)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Yt.websocket}`,this.httpEndpoint=Qt(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 i=(r=t?.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),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 Ae(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(kn){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Dr(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>is(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,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case xe.connecting:return we.Connecting;case xe.open:return we.Open;case xe.closing:return we.Closing;default:return we.Closed}}isConnected(){return this.connectionState()===we.Open}channel(e,t={config:{}}){let r=new Je(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${r} (${n})`,i),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(K.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(r=>r.topic===e&&(r._isJoined()||r._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:Ls}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,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(K.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_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(Rs,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Dr=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=xe.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var Ke=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function D(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var Zt=class extends Ke{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},kt=class extends Ke{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Sn=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},er=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ye(),Te)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Is=()=>Sn(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(ye(),Te))).Response:Response});var Ye=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Fr=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),En=(s,e)=>Ye(void 0,void 0,void 0,function*(){let t=yield Is();s instanceof t?s.json().then(r=>{e(new Zt(Fr(r),s.status||500))}).catch(r=>{e(new kt(Fr(r),r))}):e(new kt(Fr(s),s))}),Tn=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function tr(s,e,t,r,i,n){return Ye(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,Tn(e,r,i,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>En(l,a))})})}function St(s,e,t,r){return Ye(this,void 0,void 0,function*(){return tr(s,"GET",e,t,r)})}function ne(s,e,t,r,i){return Ye(this,void 0,void 0,function*(){return tr(s,"POST",e,r,i,t)})}function js(s,e,t,r,i){return Ye(this,void 0,void 0,function*(){return tr(s,"PUT",e,r,i,t)})}function rr(s,e,t,r,i){return Ye(this,void 0,void 0,function*(){return tr(s,"DELETE",e,r,i,t)})}var Q=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},xn={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},$s={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Et=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=er(i)}uploadOrUpdate(e,t,r,i){return Q(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},$s),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl)):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let l=this._removeEmptyFolders(t),c=this._getFinalPath(l),d=yield this.fetch(`${this.url}/object/${c}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield d.json();return d.ok?{data:{path:l,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(D(n))return{data:null,error:n};throw n}})}upload(e,t,r){return Q(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return Q(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 l,c=Object.assign({upsert:$s.upsert},i),d=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,d["cache-control"]=`max-age=${c.cacheControl}`,d["content-type"]=c.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:d}),p=yield u.json();return u.ok?{data:{path:n,fullPath:p.Key},error:null}:{data:null,error:p}}catch(l){if(D(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return Q(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield ne(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new Ke("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(D(r))return{data:null,error:r};throw r}})}update(e,t,r){return Q(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return Q(this,void 0,void 0,function*(){try{return{data:yield ne(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(D(i))return{data:null,error:i};throw i}})}copy(e,t,r){return Q(this,void 0,void 0,function*(){try{return{data:{path:(yield ne(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(D(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return Q(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield ne(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(D(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return Q(this,void 0,void 0,function*(){try{let i=yield ne(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(D(i))return{data:null,error:i};throw i}})}download(e,t){return Q(this,void 0,void 0,function*(){let i=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 St(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(D(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&i.push(l);let c=i.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${c}`)}}}remove(e){return Q(this,void 0,void 0,function*(){try{return{data:yield rr(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(D(t))return{data:null,error:t};throw t}})}list(e,t,r){return Q(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},xn),t),{prefix:e||""});return{data:yield ne(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(D(i))return{data:null,error:i};throw i}})}_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 Us="2.6.0";var Ms={"X-Client-Info":`storage-js/${Us}`};var Xe=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Tt=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Ms),t),this.fetch=er(r)}listBuckets(){return Xe(this,void 0,void 0,function*(){try{return{data:yield St(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(D(e))return{data:null,error:e};throw e}})}getBucket(e){return Xe(this,void 0,void 0,function*(){try{return{data:yield St(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(D(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Xe(this,void 0,void 0,function*(){try{return{data:yield ne(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(r){if(D(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Xe(this,void 0,void 0,function*(){try{return{data:yield js(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(r){if(D(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Xe(this,void 0,void 0,function*(){try{return{data:yield ne(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(D(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Xe(this,void 0,void 0,function*(){try{return{data:yield rr(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(D(t))return{data:null,error:t};throw t}})}};var xt=class extends Tt{constructor(e,t={},r){super(e,t,r)}from(e){return new Et(this.url,this.headers,e,this.fetch)}};var Ns="2.44.4";var At="";typeof Deno<"u"?At="deno":typeof document<"u"?At="web":typeof navigator<"u"&&navigator.product==="ReactNative"?At="react-native":At="node";var An={"X-Client-Info":`supabase-js-${At}/${Ns}`},qs={headers:An},Ds={schema:"public"},Fs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Hs={};ye();var Ln=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Rn=s=>{let e;return s?e=s:typeof fetch>"u"?e=kr:e=fetch,(...t)=>e(...t)},Cn=()=>typeof Headers>"u"?Sr:Headers,Ws=(s,e,t)=>{let r=Rn(t),i=Cn();return(n,o)=>Ln(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:s,c=new i(o?.headers);return c.has("apikey")||c.set("apikey",s),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),r(n,Object.assign(Object.assign({},o),{headers:c}))})};function Vs(s){return s.replace(/\/$/,"")}function Bs(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:l,global:c}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},l),i),global:Object.assign(Object.assign({},c),n)}}var sr="2.64.4";var zs="http://localhost:9999",Js="supabase.auth.token";var Gs={"X-Client-Info":`gotrue-js/${sr}`},Hr=10;var Lt="X-Supabase-Api-Version",Wr={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Ks(s){return Math.round(Date.now()/1e3)+s}function Ys(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}var Z=()=>typeof document<"u",Re={tested:!1,writable:!1},ve=()=>{if(!Z())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Re.tested)return Re.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),Re.tested=!0,Re.writable=!0}catch{Re.tested=!0,Re.writable=!1}return Re.writable};function ir(s){let e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}var nr=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(ye(),Te)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Xs=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",Vr=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Ct=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},or=async(s,e)=>{await s.removeItem(e)};function Pn(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,l,c,d=0;for(s=s.replace("-","+").replace("_","/");d<s.length;)o=e.indexOf(s.charAt(d++)),a=e.indexOf(s.charAt(d++)),l=e.indexOf(s.charAt(d++)),c=e.indexOf(s.charAt(d++)),r=o<<2|a>>4,i=(a&15)<<4|l>>2,n=(l&3)<<6|c,t=t+String.fromCharCode(r),l!=64&&i!=0&&(t=t+String.fromCharCode(i)),c!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Rt=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Rt.promiseConstructor=Promise;function Br(s){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=s.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 r=t[1];return JSON.parse(Pn(r))}async function Qs(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Zs(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await s(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function On(s){return("0"+s.toString(16)).substr(-2)}function In(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,On).join("")}async function jn(s){let t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function $n(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Un(s){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."),s;let t=await jn(s);return $n(t)}async function Ce(s,e,t=!1){let r=In(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await Vr(s,`${e}-code-verifier`,i);let n=await Un(r);return[n,r===n?"plain":"s256"]}var Mn=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function ei(s){let e=s.headers.get(Lt);if(!e||!e.match(Mn))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Pt=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function E(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var ar=class extends Pt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function ti(s){return E(s)&&s.name==="AuthApiError"}var Qe=class extends Pt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},fe=class extends Pt{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},oe=class extends fe{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Ze=class extends fe{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Pe=class extends fe{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Oe=class extends fe{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}}},Ot=class extends fe{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}}},et=class extends fe{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function lr(s){return E(s)&&s.name==="AuthRetryableFetchError"}var It=class extends fe{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Nn=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},Ie=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),qn=[502,503,504];async function ri(s){var e;if(!Xs(s))throw new et(Ie(s),0);if(qn.includes(s.status))throw new et(Ie(s),s.status);let t;try{t=await s.json()}catch(n){throw new Qe(Ie(n),n)}let r,i=ei(s);if(i&&i.getTime()>=Wr["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new It(Ie(t),s.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 It(Ie(t),s.status,t.weak_password.reasons);throw new ar(Ie(t),s.status||500,r)}var Dn=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function T(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Lt]||(n[Lt]=Wr["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(i=r?.query)!==null&&i!==void 0?i:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Fn(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(l):{data:Object.assign({},l),error:null}}async function Fn(s,e,t,r,i,n){let o=Dn(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(l){throw console.error(l),new et(Ie(l),0)}if(a.ok||await ri(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await ri(l)}}function pe(s){var e;let t=null;Hn(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Ks(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function zr(s){let e=pe(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function ae(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function si(s){return{data:s,error:null}}function ii(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Nn(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function ni(s){return s}function Hn(s){return s.access_token&&s.refresh_token&&s.expires_in}var Wn=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},je=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=nr(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await T(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(E(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await T(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ae})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Wn(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await T(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:ii,redirectTo:t?.redirectTo})}catch(t){if(E(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await T(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ae})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},d=await T(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:ni});if(d.error)throw d.error;let u=await d.json(),p=(o=d.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=d.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(y=>{let k=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(y.split(";")[1].split("=")[1]);c[`${b}Page`]=k}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},u),c),error:null}}catch(c){if(E(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){try{return await T(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ae})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await T(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ae})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await T(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ae})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await T(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(E(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await T(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}};var oi={getItem:s=>ve()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{ve()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{ve()&&globalThis.localStorage.removeItem(s)}};function Jr(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function ai(){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 $e={debug:!!(globalThis&&ve()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},jt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},cr=class extends jt{};async function Gr(s,e,t){$e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),$e.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){$e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{$e.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw $e.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new cr(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if($e.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()}})}ai();var Vn={url:zs,storageKey:Js,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Gs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},$t=30*1e3,li=3;async function ci(s,e,t){return await t()}var Ue=class s{constructor(e){var t,r;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=s.nextInstanceID,s.nextInstanceID+=1,this.instanceID>0&&Z()&&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 i=Object.assign(Object.assign({},Vn),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new je({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=nr(i.fetch),this.lock=i.lock||ci,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:Z()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Gr:this.lock=ci,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?i.storage?this.storage=i.storage:ve()?this.storage=oi:(this.memoryStorage={},this.storage=Jr(this.memoryStorage)):(this.memoryStorage={},this.storage=Jr(this.memoryStorage)),Z()&&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)}(r=this.broadcastChannel)===null||r===void 0||r.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} (${sr}) ${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=Z()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),r?.message==="Identity is already linked"||r?.message==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return E(e)?{error:e}:{error:new Qe("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:pe}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(E(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:d,password:u,options:p}=e,m=null,y=null;this.flowType==="pkce"&&([m,y]=await Ce(this.storage,this.storageKey)),n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p?.emailRedirectTo,body:{email:d,password:u,data:(t=p?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:m,code_challenge_method:y},xform:pe})}else if("phone"in e){let{phone:d,password:u,options:p}=e;n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:u,data:(r=p?.data)!==null&&r!==void 0?r:{},channel:(i=p?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:pe})}else throw new Pe("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 l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(n){if(E(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 T(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:zr})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await T(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:zr})}else throw new Pe("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Ze}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.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 Ct(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await T(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:pe});return await or(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 Ze}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:r,token:i,access_token:n,nonce:o}=e,a=await T(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:pe}),{data:l,error:c}=a;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Ze}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:l}=e,c=null,d=null;this.flowType==="pkce"&&([c,d]=await Ce(this.storage,this.storageKey));let{error:u}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(r=l?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:d},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:d}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l?.data)!==null&&i!==void 0?i:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c?.message_id},error:d}}throw new Pe("You must provide either an email or phone number.")}catch(a){if(E(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await T(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:pe});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(E(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Ce(this.storage,this.storageKey)),await T(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:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e?.options)===null||i===void 0)&&i.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:si})}catch(n){if(E(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:r}=e;if(r)throw r;if(!t)throw new oe;let{error:i}=await T(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(E(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:r,type:i,options:n}=e,{error:o}=await T(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,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:r,type:i,options:n}=e,{data:o,error:a}=await T(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new Pe("You must provide either an email or phone number and a type")}catch(t){if(E(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 r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}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 Ct(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 r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,c,d)=>(!o&&c==="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(l,c,d))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},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 T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ae}):await this._useSession(async t=>{var r,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new oe}:await T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:ae})})}catch(t){if(E(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 r=>{let{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new oe;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Ce(this.storage,this.storageKey));let{data:c,error:d}=await T(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:ae});if(d)throw d;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(E(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return Br(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 oe;let t=Date.now()/1e3,r=t,i=!0,n=null,o=Br(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(E(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 r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new oe;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!Z())throw new Oe("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Oe("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Ot("Not a valid PKCE flow url.");let t=ir(window.location.href);if(e){if(!t.code)throw new Ot("No code detected.");let{data:h,error:g}=await this._exchangeCodeForSession(t.code);if(g)throw g;let L=new URL(window.location.href);return L.searchParams.delete("code"),window.history.replaceState(window.history.state,"",L.toString()),{data:{session:h.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Oe(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=t;if(!n||!a||!o||!c)throw new Oe("No session defined in URL");let d=Math.round(Date.now()/1e3),u=parseInt(a),p=d+u;l&&(p=parseInt(l));let m=p-d;m*1e3<=$t&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${u}s`);let y=p-u;d-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,p,d):d-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",y,p,d);let{data:k,error:b}=await this._getUser(n);if(b)throw b;let R={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:p,refresh_token:o,token_type:c,user:k.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:R,redirectType:t.type},error:null}}catch(t){if(E(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=ir(window.location.href);return!!(Z()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=ir(window.location.href),t=await Ct(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 r;let{data:i,error:n}=t;if(n)return{error:n};let o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(ti(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await or(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Ys(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await Ce(this.storage,this.storageKey,!0));try{return await T(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(E(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,l,c,d;let{data:u,error:p}=n;if(p)throw p;let m=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:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await T(this.fetch,"GET",m,{headers:this.headers,jwt:(d=(c=u.session)===null||c===void 0?void 0:c.access_token)!==null&&d!==void 0?d:void 0})});if(i)throw i;return Z()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(E(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await T(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await Zs(async i=>(i>0&&await Qs(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await T(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:pe})),(i,n)=>{let o=200*Math.pow(2,i);return n&&lr(n)&&Date.now()+o-r<$t})}catch(r){if(this._debug(t,"error",r),E(r))return{data:{session:null,user:null},error:r};throw r}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 r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),Z()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await Ct(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<i+Hr;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Hr}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),lr(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new oe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Rt;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new oe;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(i,"error",n),E(n)){let o={session:null,error:n};return lr(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&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(l){n.push(l)}});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(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Vr(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await or(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Z()&&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(),$t);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:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((r.expires_at*1e3-e)/$t);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${$t}ms, refresh threshold is ${li} ticks`),i<=li&&await this._callRefreshToken(r.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 jt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Z()||!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,r){let i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await Ce(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await T(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:l}=await T(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return l?{data:null,error:l}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(E(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.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(E(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}: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 r=e?.factors||[],i=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let l=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(l="aal2");let d=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:d},error:null}}))}};Ue.nextInstanceID=0;var Bn=Ue,Kr=Bn;var dr=class extends Kr{constructor(e){super(e)}};var zn=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(d){try{c(r.next(d))}catch(u){o(u)}}function l(d){try{c(r.throw(d))}catch(u){o(u)}}function c(d){d.done?n(d.value):i(d.value).then(a,l)}c((r=r.apply(s,e||[])).next())})},Ut=class{constructor(e,t,r){var i,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=Vs(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 l=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,c={db:Ds,realtime:Hs,auth:Object.assign(Object.assign({},Fs),{storageKey:l}),global:qs},d=Bs(r??{},c);this.storageKey=(i=d.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=d.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=d.auth)!==null&&o!==void 0?o:{},this.headers,d.global.fetch),this.fetch=Ws(t,this._getAccessToken.bind(this),d.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},d.realtime)),this.rest=new Ts(`${a}/rest/v1`,{headers:this.headers,schema:d.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new ft(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new xt(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return zn(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:n,flowType:o,debug:a},l,c){var d;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new dr({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:c,hasCustomAuthorizationHeader:(d="Authorization"in this.headers)!==null&&d!==void 0?d:!1})}_initRealtimeClient(e){return new Ge(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var di=(s,e,t)=>new Ut(s,e,t);var me={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Jn=s=>{try{let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},ur=s=>{let[e,t]=s.split(".");return!e||!t?null:Jn(t)},ui=s=>{let e=ur(s);if(!e)return"unknown";let t=typeof e.iss=="string"?e.iss:"";return typeof e.client_id=="string"||t.includes("workos.com")||t.includes("authkit.app")?"workos":"supabase"};var Gn="https://api.workos.com",Kn=60,tt=(s,e)=>typeof s[e]=="string"?s[e]:void 0,hi=(s,e,t)=>{let r=ur(s);if(!r)return null;let i=tt(r,"urn:wispr:user_external_id")??tt(r,"sub"),n=t?.email??tt(r,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof r.exp=="number"?r.exp:void 0,l={id:i??"",aud:"authenticated",email:n,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:s,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:l}},Yn=async(s,e,t,r)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):Gn,n=await fetch(`${i}/user_management/authenticate`,{method:"POST",headers:{Accept:"application/json, text/plain, */*","Content-Type":"application/json"},body:JSON.stringify({client_id:e,grant_type:"refresh_token",refresh_token:s,organization_id:r})});if(!n.ok){let o=await n.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${n.status}`)}return await n.json()},fi=async(s,e)=>{let t=ur(s);if(!t)throw new Error("Invalid WorkOS access token");let r=Math.floor(Date.now()/1e3),i=typeof t.exp=="number"?t.exp:0,n=tt(t,"client_id");if(i-r<Kn&&n){let l=await Yn(e,n,tt(t,"iss"),tt(t,"org_id")),c=hi(l.access_token,l.refresh_token,l.user);if(!c)throw new Error("WorkOS refresh returned an invalid access token");return c}if(i<=r)throw new Error("WorkOS session expired");let a=hi(s,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var rt=class{constructor(){this.sessionData=null;this.supabase=di(me.supaBaseUrl,me.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||me.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||me.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||me.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:r,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw console.error("Error setting session:",r),r}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,r){let i=new Date;i.setTime(i.getTime()+r*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{if(ui(t)==="workos"){this.sessionData=await fi(t,r),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,r)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,i]=t.split("=");return e[r]=i,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:r}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||me.redirectUri}});if(r)throw r}catch(r){throw console.error("Error sending magic link:",r),r}}async signUpWithPassword(e,t,r,i,n,o){try{if(!n)throw new Error("Please complete the verification");let a=await $.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,redirect_url:i||me.redirectUri,workos_capable:o?.workosCapable||void 0});return console.log("Signup request completed"),a}catch(a){throw console.error("Error signing up:",a),a}}async signInWithPassword(e,t,r,i){try{if(!r)throw new Error("Please complete the verification");let n=await $.signInWithCaptcha({email:e,password:t,captcha_token:r,provision:i?.provision??!1,workos_capable:i?.workosCapable||void 0});if(Ht(n))return{kind:"otp",challenge:n};if(!n.access_token||!n.refresh_token)throw new Error(n.error||"Invalid login credentials");return console.log("Sign in request completed"),{kind:"authenticated",accessToken:n.access_token,refreshToken:n.refresh_token,fullName:[n.first_name,n.last_name].filter(Boolean).join(" ")||void 0,provider:n.provider||void 0}}catch(n){throw console.error("Error signing in with password:",n),n}}async resendVerificationEmail(e,t,r,i){try{if(!r)throw new Error("Please complete the verification");let n=await $.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||me.redirectUri,workos_capable:i?.workosCapable||void 0});return console.log("Verification request completed"),n}catch(n){throw console.error("Error resending verification email:",n),n}}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 hr=null,pi=(s,e)=>{if(!(s instanceof Error)||s.name!=="AriaAuthError")return e;let t={verification_failed:"Incorrect or expired code. Try again.",invalid_code:"Enter the six-digit code.",rate_limited:"Too many attempts. Please wait before trying again.",provider_unavailable:"Verification is temporarily unavailable. Please try again later.",validation_error:"Check your information and try again."},{code:r}=s;return r&&t[r]||e},fr=()=>{hr!==null&&(window.clearInterval(hr),hr=null)};function st(){let s=document.querySelector("[otp-verification]");s&&(s.style.display="none"),fr()}function mi(s){let e=document.querySelector("[otp-verification]");if(!e){console.warn("[otpUi] [otp-verification] block not found in DOM");return}let t=Array.from(document.querySelectorAll("[otp-box]")),r=document.querySelector("[otp-email]"),i=document.querySelector("[otp-verify]"),n=document.querySelector("[otp-error]"),o=document.querySelector("[otp-error-message]"),a=document.querySelector("[otp-resend]"),l=document.querySelector("[otp-resend-countdown]"),c=document.querySelector("[otp-resend-seconds]"),d=document.querySelector("[otp-reset]");t.forEach(h=>{h.value="",h.removeAttribute("disabled"),h.setAttribute("inputmode","numeric"),h.setAttribute("autocomplete","one-time-code"),h.setAttribute("data-ph-no-capture",""),h.setAttribute("data-1p-ignore",""),h.setAttribute("data-private",""),h.classList.add("ph-no-capture")}),n&&(n.style.display="none"),l&&(l.style.display="none"),a&&(a.style.display=""),i&&(i.textContent="Verify",i.style.pointerEvents="",i.removeAttribute("aria-disabled")),fr(),r&&(r.textContent=s.email),e.style.display="block",t[0]?.focus();let u=h=>{n&&(n.style.display="block"),o&&(o.textContent=h)},p=()=>{n&&(n.style.display="none")},m=!1,y=!1,k=h=>{i&&(i.style.pointerEvents=h?"none":"",h?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled"),i instanceof HTMLButtonElement&&(i.disabled=h),a&&a.style.display!=="none"&&(a.style.pointerEvents=h?"none":"",h?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},b=async()=>{if(m)return;let h=t.map(g=>g.value).join("");if(h.length!==6){u("Please enter all 6 digits.");return}m=!0,k(!0),t.forEach(g=>g.setAttribute("disabled","true")),p();try{await s.onVerify(h),p(),i&&(i.textContent="Verified \u2705")}catch(g){m=!1,k(!1),t.forEach(L=>{L.value="",L.removeAttribute("disabled")}),u(pi(g,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((h,g)=>{h.oninput=()=>{h.value=h.value.replace(/\D/g,"").slice(0,1),h.value&&g<t.length-1&&t[g+1].focus(),p()},h.onkeydown=L=>{L.key==="Backspace"&&!h.value&&g>0?t[g-1].focus():L.key==="Enter"&&(L.preventDefault(),b())},h.onpaste=L=>{L.preventDefault();let P=(L.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);P.split("").forEach((J,se)=>{t[se]&&(t[se].value=J)});let ce=Math.min(P.length,t.length-1);t[ce]?.focus(),p()}}),i&&(i.onclick=h=>{h.preventDefault(),b()});let R=()=>{let h=30;a&&(a.style.display="none"),l&&(l.style.display="block"),c&&(c.textContent=String(h)),fr(),hr=window.setInterval(()=>{h-=1,c&&(c.textContent=String(h)),h<=0&&(fr(),a&&(a.style.display=""),l&&(l.style.display="none"))},1e3)};a&&(a.onclick=async h=>{if(h.preventDefault(),!(y||a.style.display==="none")){y=!0,t.forEach(g=>{g.value="",g.removeAttribute("disabled")}),t[0]?.focus(),p(),R();try{await s.onResend?.()}catch(g){u(pi(g,"We couldn't send a new code. Please try again when the timer ends."))}finally{y=!1}}}),d&&(d.onclick=h=>{h.preventDefault(),st(),s.onReset?.()})}var Me=()=>window.hcaptcha,pr=async()=>{let s=Me();if(!s)throw new Error("Verification system not loaded");let e=await s.execute({async:!0}),t=typeof e=="string"?e:e.response;if(!t)throw new Error("Verification cancelled");return t},Mt=(s,e)=>s instanceof Error?s.message:e,gi=(s,e)=>s instanceof re?s.code==="sso_required"?(e.showSso(),!0):s.code==="scim_managed_domain"?(e.showScim(),!0):(s.code==="sign_in_to_continue"&&e.showLogin(),e.showError(s.message),!0):!1,_i=s=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(r){e={pendingAuthenticationToken:r.pendingAuthenticationToken,email:X(r.email)},s.beforeShow(),mi({email:e.email,onVerify:async i=>{if(!e)throw st(),s.onMissingChallenge(),new Error("Missing OTP challenge");let n=await $.verifyEmailOtp({code:i,pending_authentication_token:e.pendingAuthenticationToken});t(),await s.onAuthenticated(n)},onResend:async()=>{if(!e)throw st(),s.onMissingChallenge(),new Error("Missing OTP challenge");let i=await pr();try{await s.client.resendVerificationEmail(e.email,s.redirectUrl,i,{workosCapable:s.isWorkosCapable(e.email)})}finally{Me()?.reset()}},onReset:()=>{t(),s.onReset()}})}}};var le=null;function Yr(s,e=30,t){le&&(clearInterval(le),le=null);let r=e;s.style.pointerEvents="none",s.textContent=`Resend (${r}s)`,le=setInterval(()=>{r=r-1,s.textContent=r>0?`Resend (${r}s)`:"Resend email",r===0&&(s.style.pointerEvents="auto",le&&(clearInterval(le),le=null),t&&t())},1e3)}function yi(){le&&(clearInterval(le),le=null)}var wi=/^[\p{L}\p{M}\s\-'.]+$/u;function Xn(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":wi.test(t)?t.length>30?"Your name must be 30 characters or fewer":e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Your name can't include symbols":null}function Xr(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":wi.test(t)?t.length>30?"Your name must be 30 characters or fewer":t.includes(" ")?e&&e.toLowerCase()===t.toLowerCase()?"Your full name can't be the same as your password":null:"Please include your last name":"Your name can't include symbols":null}function vi(s,e,t){let r="full-name-match-error",i=l=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let c=document.getElementById(r);c||(c=document.createElement("div"),c.id=r,c.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",c)),c.textContent=l},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(r)?.remove()},o=()=>{let l=Xn(e.value,s.value);l?i(l):n()},a=()=>{let l=Xr(e.value,s.value);l?i(l):n()};s.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var bi="password-rejection-error",ki=s=>s instanceof re?s.passwordRejectionMessage:null,Nt=s=>{s.classList.remove("error"),document.getElementById(bi)?.remove()},Qr=(s,e)=>{if(Nt(s),e.length===0)return;s.classList.add("error");let t=document.createElement("div");t.id=bi,t.style.fontSize="0.875rem",t.textContent=e,s.insertAdjacentElement("afterend",t)};var O=(s,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:s,retry_attempt:10-t}),window.posthog.capture(s,e)):t>0&&setTimeout(()=>O(s,e,t-1),200)},Si=(s,e)=>{window.posthog&&typeof window.posthog.identify=="function"&&(window.posthog.identify(s,e),console.log("ph user identified"))};var Qn="wispr_workos_capable";var Ei=()=>{try{return window.sessionStorage.getItem(Qn)==="true"}catch{return!1}};function Ti(s,e){let t=new rt,r="email_input",i=null,n=()=>{i?.clear()},o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),l=document.querySelector("#password-input"),c=document.querySelector("#full-name"),d=document.querySelector("#google-login"),u=document.querySelector("#apple-login"),p=document.querySelector("#microsoft-login"),m=document.querySelector("[email-element]"),y=document.querySelector("[different-provider]"),k=document.querySelector("[different-provider-name]"),b=document.querySelector("[different-provider-reset]"),R=document.querySelector("[email-signup-success]"),h=document.querySelector("[email-signup-error]"),g=document.querySelector("[error-message]"),L=document.querySelector("[verification-email]"),P=document.querySelector("[email-signup-retry]"),ce=document.querySelector("[email-signup-reset]"),J=document.querySelector("[scim-div]"),se=document.querySelector("[scim-reset]"),F=document.querySelector("[forgot-password]"),be=document.querySelector("[forgot-password-success]"),it=document.querySelector("[forgot-password-email]"),ee=document.querySelector("[unverified-email]"),nt=document.querySelector("[unverified-email-address]"),de=document.querySelector("[resend-verification-email]"),ke=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(d&&d.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(s)}catch(_){console.error("Error during Google sign-in:",_)}}),u&&u.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","apple"),await t.signInWithApple(s)}catch(_){console.error("Error during Apple sign-in:",_)}}),p&&p.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(s)}catch(_){console.error("Error during Microsoft sign-in:",_)}}));let Y=()=>{n(),y&&(y.style.display="none"),R&&(R.style.display="none"),h&&(h.style.display="none"),ee&&(ee.style.display="none"),J&&(J.style.display="none"),F&&(F.style.display="none"),be&&(be.style.display="none"),st();let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="block"),m&&(m.style.display="flex"),a&&(a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled")),l&&(l.value="",l.style.display="none",l.removeAttribute("required"),Nt(l)),c&&(c.value="",c.style.display="none",c.removeAttribute("required"));let v=document.querySelector("[captcha-embed]"),A=document.querySelector("#h-captcha-container");v&&(v.style.display="none"),A&&(A.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),r="email_input",a&&a.focus()},Se=()=>{m&&(m.style.display="flex"),a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),l&&(l.style.display="block",l.setAttribute("required","true"),l.focus()),c&&(c.style.display="none",c.removeAttribute("required"));let _=document.querySelector("[captcha-embed]"),v=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),v&&(v.style.display="block"),F&&(F.style.display="block",F.onclick=async()=>{let A=a?.value||"",x=F.textContent||"";try{let{hcaptcha:H}=window;if(!H)throw new Error("Verification system not loaded. Please refresh the page.");F.style.pointerEvents="none",F.textContent="Sending...";let{response:I}=await H.execute({async:!0});if(!I)throw new Error("Verification cancelled");await $.requestPasswordReset(A,I),H.reset(),m&&(m.style.display="none"),F&&(F.style.display="none"),be&&(be.style.display="block"),it&&(it.textContent=A)}catch(H){console.error("Error sending password reset email:",H),F.textContent=x,F.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",g&&(g.textContent=H instanceof Error?H.message:"Failed to send reset email"))}}),r="login"},ot=()=>{a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),l&&(l.style.display="block",l.setAttribute("required","true"),l.focus()),c&&(c.style.display="block",c.setAttribute("required","true"));let _=document.querySelector("[captcha-embed]"),v=document.querySelector("#h-captcha-container");_&&(_.style.display="block"),v&&(v.style.display="block"),r="signup"},at=()=>{let _=document.querySelector(".gs-hero_form-block");_&&(_.style.display="none"),J&&(J.style.display="block"),se&&(se.onclick=()=>{J&&(J.style.display="none"),_&&(_.style.display="block"),Y()})},Ne=_=>{n();let v=as(_);m&&(m.style.display="none"),y&&(y.style.display="block"),k&&(k.textContent=v),b&&(b.onclick=()=>{y&&(y.style.display="none"),Y()}),r="oauth_user"};i=_i({client:t,redirectUrl:s,isWorkosCapable:()=>!0,beforeShow:()=>{m&&(m.style.display="none"),ee&&(ee.style.display="none")},onAuthenticated:async _=>{n(),t.setCookies(_.access_token,_.refresh_token),localStorage.setItem("email",_.email),localStorage.setItem("user_id",_.user_id),localStorage.setItem("signin_provider","email");let v=[_.first_name,_.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(_.access_token,_.refresh_token,v):window.location.href=s},onMissingChallenge:Se,onReset:Y});let qe=_=>{m&&(m.style.display="none"),ee&&(ee.style.display="block"),nt&&(nt.textContent=_),de&&(de.onclick=async()=>{let v=de.textContent||"";try{let A=await pr();await t.resendVerificationEmail(_,s,A),de.textContent="Verification email resent! \u2705",de.style.textDecoration="none"}catch(A){de.textContent=v,h&&(h.style.display="block"),g&&(g.textContent=Mt(A,"Unable to resend verification."))}finally{Me()?.reset()}}),ke&&(ke.onclick=()=>{ee&&(ee.style.display="none"),Y()}),r="unverified_email"},De=_=>gi(_,{showSso:()=>Ne("workos"),showScim:at,showLogin:Se,showError:v=>{h&&(h.style.display="block"),g&&(g.textContent=v)}}),Fe=async(_,v)=>{let A=v.value;v.classList.add("loading"),v.value="";try{let x=await $.checkUserStatus(_);v.classList.remove("loading"),v.value=A,!x.exists&&x.scim_managed?at():x.enforce_sso?Ne("workos"):x.exists&&x.provider&&x.provider!=="email"&&x.provider!=="workos"?Ne(x.provider):x.exists&&x.provider==="workos"?Se():x.exists&&x.provider==="email"&&!x.verified?qe(_):x.exists&&x.provider==="email"?Se():ot()}catch(x){console.error("Error checking user status:",x),v.classList.remove("loading"),v.value=A,De(x)||ot()}},qt=async(_,v,A,x)=>{if(!v||v.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}let H=window.hcaptcha?.getResponse()||"";if(!H){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}A.classList.add("loading"),A.value="";try{if(e?.mcpLoginState){let q=await $.signInWithEmail({email:_,password:v,mcp_login_state:e.mcpLoginState,workos_capable:Ei()});if(!q.redirect_url)throw new Error(q.error||"Unable to continue connector login. Please try again.");O("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=q.redirect_url;return}let I=Ei(),N=await t.signInWithPassword(_,v,H,{workosCapable:I,provision:!1});if(N.kind==="otp"){if(!I)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let q={pendingAuthenticationToken:N.challenge.pending_authentication_token,email:X(N.challenge.email||_)};Me()?.reset(),A.classList.remove("loading"),A.value=x,i?.show(q);return}t.setCookies(N.accessToken,N.refreshToken),localStorage.setItem("email",_),e?.onLoginSuccess?await e.onLoginSuccess(N.accessToken,N.refreshToken,N.fullName):window.location.href=s}catch(I){window.hcaptcha&&window.hcaptcha.reset(),A.classList.remove("loading"),A.value=x,!De(I)&&h&&(h.style.display="block",g&&(g.textContent=Mt(I,"Unable to sign in. Please try again.")))}},lt=async(_,v,A,x,H)=>{if(!v||v.length<8){h&&(h.style.display="block",g&&(g.textContent="Password must be at least 8 characters"));return}if(v.trim().toLowerCase()===_.trim().toLowerCase()){Qr(l,"Password can't be the same as your email address.");return}if(!A||A.trim().length<2){h&&(h.style.display="block",g&&(g.textContent="Please enter your full name"));return}let I=Xr(A,v);if(I){h&&(h.style.display="block",g&&(g.textContent=I));return}let N=window.hcaptcha?.getResponse()||"";if(!N){h&&(h.style.display="block",g&&(g.textContent="Please complete the verification"));return}x.classList.add("loading"),x.value="";try{let q=await t.signUpWithPassword(_,v,A,s,N,{workosCapable:!0});if(window.hcaptcha&&window.hcaptcha.reset(),x.classList.remove("loading"),x.value=H,m&&(m.style.display="none"),h&&(h.style.display="none"),Ht(q)){let j={pendingAuthenticationToken:q.pending_authentication_token,email:X(q.email||_)};i?.show(j);return}R&&(R.style.display="block"),L&&(L.textContent=_),P&&(Yr(P,30),P.onclick=async()=>{if(P.style.pointerEvents!=="none")try{let j=await pr();await t.resendVerificationEmail(_,s,j,{workosCapable:!0}),Yr(P,30)}catch(j){h&&(h.style.display="block"),g&&(g.textContent=Mt(j,"Unable to resend verification. Please try again."))}finally{Me()?.reset()}}),ce&&(ce.onclick=()=>{R&&(R.style.display="none"),yi(),Y()})}catch(q){x.classList.remove("loading"),x.value=H,Me()?.reset();let j=ki(q);j&&l?Qr(l,j):!De(q)&&h&&(h.style.display="block",g&&(g.textContent=Mt(q,"Unable to create the account. Please try again.")))}};return o&&l&&c&&(vi(l,c,o.querySelector('[type="submit"]')),l.addEventListener("input",()=>Nt(l))),o&&o.addEventListener("submit",async _=>{_.stopPropagation(),_.preventDefault();let v=X(a?.value||"");a&&(a.value=v);let A=l?.value||"",x=c?.value||"";if(!v||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)){h&&(h.style.display="block",g&&(g.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),g&&(g.textContent=""),l&&Nt(l);let I=o.querySelector('[type="submit"]'),N=I?.value||"";localStorage.setItem("signin_provider","email");try{r==="email_input"?await Fe(v,I):r==="login"?await qt(v,A,I,N):r==="signup"&&await lt(v,A,x,I,N)}catch(q){console.error("Auth flow error:",q),I&&(I.classList.remove("loading"),I.value=N),h&&(h.style.display="block")}}),{reset:Y}}var mr=function(){return mr=Object.assign||function(s){for(var e,t=1,r=arguments.length;t<r;t++)for(var i in e=arguments[t])Object.prototype.hasOwnProperty.call(e,i)&&(s[i]=e[i]);return s},mr.apply(this,arguments)},xi=function(){function s(e,t,r){var i=this;this.endVal=t,this.options=r,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){i.startTime||(i.startTime=n);var o=n-i.startTime;i.remaining=i.duration-o,i.useEasing?i.countDown?i.frameVal=i.startVal-i.easingFn(o,0,i.startVal-i.endVal,i.duration):i.frameVal=i.easingFn(o,i.startVal,i.endVal-i.startVal,i.duration):i.frameVal=i.startVal+(i.endVal-i.startVal)*(o/i.duration);var a=i.countDown?i.frameVal<i.endVal:i.frameVal>i.endVal;i.frameVal=a?i.endVal:i.frameVal,i.frameVal=Number(i.frameVal.toFixed(i.options.decimalPlaces)),i.printValue(i.frameVal),o<i.duration?i.rAF=requestAnimationFrame(i.count):i.finalEndVal!==null?i.update(i.finalEndVal):i.options.onCompleteCallback&&i.options.onCompleteCallback()},this.formatNumber=function(n){var o,a,l,c,d=n<0?"-":"";o=Math.abs(n).toFixed(i.options.decimalPlaces);var u=(o+="").split(".");if(a=u[0],l=u.length>1?i.options.decimal+u[1]:"",i.options.useGrouping){c="";for(var p=3,m=0,y=0,k=a.length;y<k;++y)i.options.useIndianSeparators&&y===4&&(p=2,m=1),y!==0&&m%p==0&&(c=i.options.separator+c),m++,c=a[k-y-1]+c;a=c}return i.options.numerals&&i.options.numerals.length&&(a=a.replace(/[0-9]/g,function(b){return i.options.numerals[+b]}),l=l.replace(/[0-9]/g,function(b){return i.options.numerals[+b]})),d+i.options.prefix+a+l+i.options.suffix},this.easeOutExpo=function(n,o,a,l){return a*(1-Math.pow(2,-10*n/l))*1024/1023+o},this.options=mr(mr({},this.defaults),r),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 i.handleScroll(i)}),window.onscroll=function(){window.onScrollFns.forEach(function(n){return n()})},this.handleScroll(this)))}return s.prototype.handleScroll=function(e){if(e&&window&&!e.once){var t=window.innerHeight+window.scrollY,r=e.el.getBoundingClientRect(),i=r.top+window.pageYOffset,n=r.top+r.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||i>t)&&!e.paused&&e.reset()}},s.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 r=this.countDown?1:-1;this.endVal=e+r*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},s.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))},s.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},s.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)},s.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))},s.prototype.printValue=function(e){var t;if(this.el){var r=this.formattingFn(e);!((t=this.options.plugin)===null||t===void 0)&&t.render?this.options.plugin.render(this.el,r):this.el.tagName==="INPUT"?this.el.value=r:this.el.tagName==="text"||this.el.tagName==="tspan"?this.el.textContent=r:this.el.innerHTML=r}},s.prototype.ensureNumber=function(e){return typeof e=="number"&&!isNaN(e)},s.prototype.validateValue=function(e){var t=Number(e);return this.ensureNumber(t)?t:(this.error="[CountUp] invalid start or end value: ".concat(e),null)},s.prototype.resetDuration=function(){this.startTime=null,this.duration=1e3*Number(this.options.duration),this.remaining=this.duration},s.prototype.parse=function(e){var t=function(o){return o.replace(/([.,' ])/g,"\\$1")},r=t(this.options.separator),i=t(this.options.decimal),n=e.replace(new RegExp(r,"g"),"").replace(new RegExp(i,"g"),".");return parseFloat(n)},s}();var Ai=!1;function Li(){if(Ai)return;Ai=!0;let s=document.querySelectorAll("[number-count]"),e=new IntersectionObserver(t=>{t.forEach(r=>{if(r.isIntersecting){let i=r.target;e.unobserve(i);let n=i.dataset.countDirection||"up",o=parseFloat(i.dataset.countOffset||"10")/100,a=parseFloat(i.dataset.countDuration||"2"),l=5,c=i.dataset.countTarget||i.textContent?.trim()||"0",d=parseFloat(c.replace(/,/g,""));if(isNaN(d))return;let u=d*o,p=Math.max(u,l),m=n==="down"?d+p:Math.max(0,d-p);new xi(i,d,{startVal:Math.round(m),duration:a,useGrouping:!0}).start()}})},{threshold:0});s.forEach(t=>{t.dataset.countTarget=t.textContent?.trim()||"0",e.observe(t)})}var Ri=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});async function Zn(s){let t=new TextEncoder().encode(s.toLowerCase().trim()),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=setTimeout(()=>{document.body.style.visibility="visible"},4e3),e=new rt,{accessToken:t,refreshToken:r}=ds(),i=document.querySelector("[auth-section]"),n=document.querySelector("[waitlist-content]"),o=document.querySelectorAll("[logout-button]"),a=document.querySelector("[stats-skeleton]"),l=document.querySelector("[stats-wrap]"),c=document.querySelector("[error-div]"),d=document.querySelector("[error-text]"),u=document.querySelector("[waitlist-rank]"),p=document.querySelector("[spots]"),m=document.querySelectorAll("[referral-code]"),y=document.querySelector("[referral-count]"),k=document.querySelector("[desktop-bonus-remaining]"),b=document.querySelector("[desktop-bonus-complete]"),R=document.querySelector("[climbed-dropped]"),h=document.querySelector("[keep-moving]"),g=document.querySelector("[rank-arrow-wrap]"),L=document.querySelector("[cohort-text]"),P=document.querySelector("[top-100]"),ce=document.querySelector("[top-1000]"),J=document.querySelector("[top-100k]"),se=document.querySelector("[sms-bonus-remaining]"),F=document.querySelector("[sms-bonus-complete]"),be=document.querySelector("[total-boost]"),it=document.querySelector("[social-media-details]"),ee=document.querySelector("[sms-popup-button]"),nt=document.querySelector("[app-download]"),de=document.querySelector("[file-upload]"),ke=document.querySelector("[file-input]"),Y=document.querySelector("[file-validation-error]"),Se=document.querySelector("[file-upload-loading]"),ot=document.querySelector("[cancel-upload-button]"),at=document.querySelector("[file-upload-verified]"),Ne=document.querySelector("[boost-earned]"),gr=document.querySelector("[boost-earned-location]"),qe=document.querySelector("[woohoo-button]"),De=document.querySelector("[file-upload-failed]"),Fe=document.querySelector("[upload-failed-text]"),qt=document.querySelector("[close-button]"),lt=document.querySelector("[share-on-x]"),_=document.querySelector("[share-on-linkedin]"),v=document.querySelector("[share-on-whatsapp]"),A=document.querySelector("[share-on-slack]"),x=document.querySelector("[share-on-discord]"),H=document.querySelector("[social-media-bonus-remaining]"),I=document.querySelector("[social-media-bonus-complete]"),N=document.querySelector("[share-on-other-channel]");it&&it.addEventListener("click",()=>{O("android_waitlist_social_details_opened"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_details_opened"})}),ee&&ee.addEventListener("click",()=>{O("android_waitlist_sms_button_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_button_clicked"})}),nt&&nt.addEventListener("click",()=>{window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_app_download",source:"android-waitlist-page"}),O("android_waitlist_download_clicked"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_download_clicked"})});let q=async()=>{clearTimeout(s),document.body.style.visibility="visible",o.forEach(_r=>{_r.style.display="none"}),n&&(n.style.display="block");let j=window.__abVariantPromise?await window.__abVariantPromise:"control",te=document.querySelector("[auth-hero-default]"),He=document.querySelector("[auth-hero-v1]"),Ee=document.querySelector("[auth-hero-v2]");te&&(te.style.display="none"),He&&(He.style.display="none"),Ee&&(Ee.style.display="none"),j==="dictation-broken"&&He?He.style.display="block":j==="smartest"&&Ee?Ee.style.display="block":te&&(te.style.display="block"),n&&(n.style.display="none"),i&&(i.style.display="block");let ct=document.querySelector("[reusable-section-wrap]");ct&&i&&i.appendChild(ct);let ge=document.querySelector(".wl_cohort-spot-wrap");ge&&(ge.style.display="none"),window.dispatchEvent(new CustomEvent("waitlist:auth-section-ready")),O("android_waitlist_auth_shown"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_auth_shown"}),Ti(`${window.location.origin}/android-waitlist`)};if(!t||!r){await q();return}try{e.setCookies(t,r),await e.checkAndSetSession(),e.sessionData&&e.setCookies(e.sessionData.access_token,e.sessionData.refresh_token),clearTimeout(s),document.body.style.visibility="visible",n&&(n.style.display="block"),o.forEach(f=>{f.style.display="flex",f.dataset.bound||(f.dataset.bound="true",f.addEventListener("click",async S=>{S.preventDefault();try{await e.signOut()}finally{localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("android_waitlist_last_rank"),localStorage.removeItem("signin_provider"),sessionStorage.removeItem("referral_status"),window.location.href="/android-waitlist"}}))});let j=e.sessionData?.access_token,te=e.sessionData?.user.email,He=e.sessionData?.user.user_metadata.full_name||" ",[Ee,ct]=os(He),ge=e.sessionData?.user.id;localStorage.setItem("email",te),ge&&localStorage.setItem("user_id",ge),ge&&Si(ge,{email:te,firstName:Ee,lastName:ct});let _r=Ri(),{dub_id:yr,referral:wr,promo_code:Zr}=_r,Ci=!!localStorage.getItem("conversion_sent"),We=!localStorage.getItem("android_waitlist_joined"),U={signup:{success:null,error:null},referral:{success:null,error:null},waitlist:{success:null,error:null},stats:{success:null,error:null}},Pi={access_token:j,first_name:Ee,last_name:ct,dub_click_id:yr||void 0,referral:wr||void 0,promo_code:Zr||void 0};try{await $.signupUser(Pi),U.signup.success=!0}catch(f){U.signup.success=!1,U.signup.error=f instanceof Error?f.message:"Unknown error"}try{let f=await $.ensureReferralCode(j);if(U.referral.success=f.ok,!f.ok){let S=await f.json().catch(()=>({}));U.referral.error=S.detail||S.message||`Status ${f.status}`}}catch(f){U.referral.success=!1,U.referral.error=f instanceof Error?f.message:"Network error"}Ci||(O("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:"android",dub_id:yr||void 0,referral:wr||void 0,email:te,user_id:ge||void 0}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown"}),localStorage.setItem("conversion_sent","true"));let Oi={email:te,device_type:"android"},es=!1;try{await $.addToWaitlist(Oi),U.waitlist.success=!0,es=!0}catch(f){U.waitlist.success=!1,U.waitlist.error=f instanceof Error?f.message:"Unknown error"}We&&es&&(localStorage.setItem("android_waitlist_joined","true"),O("app_waitlist",{device_type:"android",source:"android-waitlist-page"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"app_waitlist",device_type:"android",source:"android-waitlist-page"}));let G=await $.getAndroidWaitlistStats(j);if(G.status===404&&!We){O("android_waitlist_recovery_attempted",{reason:"localStorage flag set but 404 from stats API"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_attempted",reason:"localStorage flag set but 404 from stats API"}),localStorage.removeItem("android_waitlist_joined");try{let f={email:te,device_type:"android"};await $.addToWaitlist(f),localStorage.setItem("android_waitlist_joined","true"),G=await $.getAndroidWaitlistStats(j),G.ok&&(O("android_waitlist_recovery_success"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_recovery_success"}))}catch(f){console.error("Recovery addToWaitlist failed:",f)}}let Ii=()=>{a&&(a.style.display="none"),l&&(l.style.display="block")};if(U.stats.success=G.ok,G.status===401||G.status===429||!G.ok){let f="";try{let S=await G.json();f=JSON.stringify(S),U.stats.error=S.detail||S.message||f,d&&(d.textContent=`Status: ${G.status} | ${f}`)}catch{f="Could not parse response",U.stats.error=f,d&&(d.textContent=`Status: ${G.status} | ${f}`)}O("android_waitlist_api_error",{status:G.status,error:f,signup_success:U.signup.success,signup_error:U.signup.error,referral_success:U.referral.success,referral_error:U.referral.error,waitlist_success:U.waitlist.success,waitlist_error:U.waitlist.error,stats_error:U.stats.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_api_error",status:G.status,error:f}),a&&(a.style.display="none"),c&&(c.style.display="block");return}let W=await G.json();if(We){let f=await Zn(te);window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_signup",waitlist_position:W.current_rank,user_email_hash:f})}let ts=localStorage.getItem("android_waitlist_last_rank");if(ts&&!We){let f=parseInt(ts,10);W.current_rank<f&&(window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_position_increase",new_position:W.current_rank,positions_gained:f-W.current_rank,referral_count:W.referrals_count}))}localStorage.setItem("android_waitlist_last_rank",W.current_rank.toString());let vr=f=>{let S=f.current_rank;if(u){let w=S.toLocaleString("en-US");u.textContent=w,u instanceof HTMLElement&&(u.dataset.countTarget=w)}if(f.starting_rank!==null){let w=f.starting_rank-S;p&&(p.textContent=Math.abs(w).toLocaleString()),w<0?(R&&(R.textContent="fell"),h&&(h.style.display="none"),g&&g.classList.add("invert")):(R&&(R.textContent="climbed"),h&&(h.style.display="inline-block"),g&&g.classList.remove("invert"))}if(P&&P.classList.remove("active"),ce&&ce.classList.remove("active"),J&&J.classList.remove("active"),S<=100?P&&P.classList.add("active"):S<=1e3?ce&&ce.classList.add("active"):S<=1e5&&J&&J.classList.add("active"),document.querySelectorAll("[cohort-wins]").forEach(w=>{w.style.display="none"}),S<=100){let w=document.querySelector('[cohort-wins="top-100"]');w&&(w.style.display="block")}else if(S<=1e3){let w=document.querySelector('[cohort-wins="top-1000"]');w&&(w.style.display="block")}else if(S<=1e5){let w=document.querySelector('[cohort-wins="top-100k"]');w&&(w.style.display="block")}if(L)if(S<=100)L.innerHTML="You're in the <strong>top 100!</strong>";else if(S<=1e3){let w=S-100;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 100`}else if(S<=1e5){let w=S-1e3;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 1,000`}else{let w=S-1e5;L.innerHTML=`<strong>Only ${w.toLocaleString()} spots</strong> to top 100,000`}m.forEach(w=>{w.textContent=f.referral_code}),y&&(y.textContent=f.referrals_count.toString()),f.desktop_dictation_bonus_earned?(k&&(k.style.display="none"),b&&(b.style.display="block")):(k&&(k.style.display="block"),b&&(b.style.display="none")),f.phone_number_bonus_earned?(se&&(se.style.display="none"),F&&(F.style.display="block")):(se&&(se.style.display="block"),F&&(F.style.display="none")),f.verified_share_twitter&<&<.classList.add("verified"),f.verified_share_linkedin&&_&&_.classList.add("verified"),f.verified_share_whatsapp&&v&&v.classList.add("verified"),f.verified_share_slack&&A&&A.classList.add("verified"),f.verified_share_discord&&x&&x.classList.add("verified");let B=f.verified_share_twitter&&f.verified_share_linkedin&&f.verified_share_whatsapp&&f.verified_share_slack&&f.verified_share_discord;if(B&&(H&&(H.style.display="none"),I&&(I.style.display="block")),be){let w=[f.phone_number_bonus_earned,f.desktop_dictation_bonus_earned,B].filter(Boolean).length;be.textContent=`${w} of 3`}};vr(W);let rs=f=>f<=100?"top-100":f<=1e3?"top-1000":f<=1e5?"top-100k":"below-100k";O("android_waitlist_page_view",{rank:W.current_rank,total_boost:W.total_boost,referrals_count:W.referrals_count,cohort:rs(W.current_rank),is_first_visit:We}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_page_view",rank:W.current_rank,total_boost:W.total_boost,referrals_count:W.referrals_count,cohort:rs(W.current_rank),is_first_visit:We});let ji=`https://wisprflow.ai/waitlist?${W.referral_code}`;document.querySelectorAll("[share]").forEach(f=>{let S=f.getAttribute("share");if(!S)return;let w=document.querySelector(`[share-content="${S}"]`)?.textContent||"";f.addEventListener("click",async()=>{switch(O("android_waitlist_share_clicked",{platform:S}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_share_clicked",platform:S}),S){case"x":window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(w)}`,"_blank");break;case"linkedin":await navigator.clipboard.writeText(w),window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(ji)}`,"_blank");break;case"whatsapp":window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(w)}`,"_blank");break;case"slack":await navigator.clipboard.writeText(w),window.open("slack://open","_self");break;case"discord":await navigator.clipboard.writeText(w),window.open("https://discord.com/app","_blank");break}})}),window.addEventListener("sms:submit",async f=>{let S=f,{phoneNumber:B}=S.detail;try{let w=await $.submitPhoneNumber(B,j),ue=await w.json();if(!w.ok||!ue.success){let Dt=ue.error||"Something went wrong";window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:Dt}})),O("android_waitlist_sms_error",{error:Dt}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:Dt});return}window.dispatchEvent(new CustomEvent("sms:success"));let he=await $.getAndroidWaitlistStats(j);he.ok&&vr(await he.json()),O("android_waitlist_sms_submitted",{boost_earned:ue.boost_earned,new_rank:ue.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_submitted",boost_earned:ue.boost_earned,new_rank:ue.current_rank})}catch(w){console.error("SMS submission error:",w),window.dispatchEvent(new CustomEvent("sms:error",{detail:{message:"Network error. Please try again."}})),O("android_waitlist_sms_error",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_sms_error",error:"network_error"})}});let _e=f=>{de&&(de.style.display=f==="idle"?"block":"none"),Se&&(Se.style.display=f==="loading"?"block":"none"),at&&(at.style.display=f==="verified"?"block":"none"),De&&(De.style.display=f==="failed"?"block":"none"),Y&&(Y.style.display="none")},$i=f=>{let B=["image/png","image/jpeg","image/jpg"];return f.size>20971520?"File too large. Maximum size is 20MB.":B.includes(f.type)?null:"Please upload a PNG or JPEG image."},Ui={social_share_x:"X",social_share_linkedin:"LinkedIn",social_share_whatsapp:"WhatsApp",social_share_slack:"Slack",social_share_discord:"Discord"},Mi=f=>Ui[f]||"Social Media",Ni={social_share_x:lt,social_share_linkedin:_,social_share_whatsapp:v,social_share_slack:A,social_share_discord:x},qi=f=>{let S=Ni[f];S&&S.classList.add("verified")},Di=f=>({file_too_large:"File exceeds 20MB limit. (file_too_large)",invalid_file_type:"Please upload a PNG or JPEG. (invalid_file_type)","User not on Android waitlist":"Please join the waitlist first. (User not on Android waitlist)",all_platforms_already_claimed:"You've claimed all social share bonuses! (all_platforms_already_claimed)",x_already_claimed:"You've already received the X bonus. (x_already_claimed)",linkedin_already_claimed:"You've already received the LinkedIn bonus. (linkedin_already_claimed)",whatsapp_already_claimed:"You've already received the WhatsApp bonus. (whatsapp_already_claimed)",slack_already_claimed:"You've already received the Slack bonus. (slack_already_claimed)",discord_already_claimed:"You've already received the Discord bonus. (discord_already_claimed)",not_posted:"This looks like a draft, not a published post. (not_posted)",no_wispr_mention:"Post must mention Wispr Flow or wisprflow.ai. (no_wispr_mention)",invalid:"We couldn't verify this screenshot. Try a clearer image. (invalid)","An error occurred":"Something went wrong. Please try again. (An error occurred)"})[f??""]??`Verification failed. (${f})`,dt=null;ke&&ke.addEventListener("change",async()=>{let f=ke.files?.[0];if(!f)return;ke.value="";let S=$i(f);if(S){Y&&(Y.textContent=S,Y.style.display="block"),O("android_waitlist_social_validation_error",{error:S}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_validation_error",error:S});return}O("android_waitlist_social_upload_started"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_started"}),_e("loading"),dt=new AbortController;try{let B=await $.submitSocialShare(f,j,dt.signal),w=await B.json();if(!B.ok||!w.success){_e("failed"),Fe&&(Fe.textContent=Di(w.error)),O("android_waitlist_social_upload_failed",{error:w.error}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:w.error});return}_e("verified"),Ne&&(Ne.textContent=w.boost_earned.toLocaleString()),gr&&(gr.textContent=Mi(w.action)),qi(w.action);let ue=await $.getAndroidWaitlistStats(j);if(ue.ok){let he=await ue.json();vr(he),he.verified_share_twitter&&he.verified_share_linkedin&&he.verified_share_whatsapp&&he.verified_share_slack&&he.verified_share_discord&&(qe&&(qe.style.display="none"),N&&(N.style.display="none"),O("android_waitlist_social_all_claimed"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_all_claimed"}))}O("android_waitlist_social_share_verified",{platform:w.action,boost_earned:w.boost_earned,new_rank:w.current_rank}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_share_verified",platform:w.action,boost_earned:w.boost_earned,new_rank:w.current_rank})}catch(B){if(B instanceof Error&&B.name==="AbortError"){_e("idle");return}console.error("Social share upload error:",B),_e("failed"),Fe&&(Fe.textContent="Network error. Please try again."),O("android_waitlist_social_upload_failed",{error:"network_error"}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_failed",error:"network_error"})}finally{dt=null}}),ot&&ot.addEventListener("click",()=>{dt&&dt.abort(),_e("idle"),O("android_waitlist_social_upload_cancelled"),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"android_waitlist_social_upload_cancelled"})}),qe&&qe.addEventListener("click",()=>{_e("idle")}),qt&&qt.addEventListener("click",()=>{_e("idle")}),Ii(),window.dispatchEvent(new CustomEvent("waitlist:stats-ready")),Li()}catch(j){console.error("Error on android-waitlist page:",j),e.setCookie("access_token","",-1),e.setCookie("refresh_token","",-1),await q()}});})();
|