@tanay-wispr/webflow-package 6.8.0 → 6.8.1
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/login.js +1 -1
- package/package.json +1 -1
package/dist/login.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var di=Object.create;var Rt=Object.defineProperty;var hi=Object.getOwnPropertyDescriptor;var fi=Object.getOwnPropertyNames;var pi=Object.getPrototypeOf,gi=Object.prototype.hasOwnProperty;var mi=(s,e)=>()=>(s&&(e=s(s=0)),e);var te=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),_i=(s,e)=>{for(var t in e)Rt(s,t,{get:e[t],enumerable:!0})},Nr=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of fi(e))!gi.call(s,i)&&i!==t&&Rt(s,i,{get:()=>e[i],enumerable:!(r=hi(e,i))||r.enumerable});return s};var qr=(s,e,t)=>(t=s!=null?di(pi(s)):{},Nr(e||!s||!s.__esModule?Rt(t,"default",{value:s,enumerable:!0}):t,s)),yi=s=>Nr(Rt({},"__esModule",{value:!0}),s);var we={};_i(we,{Headers:()=>cr,Request:()=>Pi,Response:()=>Ri,default:()=>ar,fetch:()=>Ci});var xi,Ue,Ci,ar,cr,Pi,Ri,fe=mi(()=>{"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")},Ue=xi(),Ci=Ue.fetch,ar=Ue.fetch.bind(Ue),cr=Ue.Headers,Pi=Ue.Request,Ri=Ue.Response});var Jr=te(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});var lr=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};ur.default=lr});var hr=te(rt=>{"use strict";var Vr=rt&&rt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(rt,"__esModule",{value:!0});var Ii=Vr((fe(),yi(we))),Li=Vr(Jr()),dr=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=Ii.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,c;let l=null,u=null,d=null,f=n.status,p=n.statusText;if(n.ok){if(this.method!=="HEAD"){let O=await n.text();O===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=O:u=JSON.parse(O))}let k=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),S=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");k&&S&&S.length>1&&(d=parseInt(S[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(l={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,d=null,f=406,p="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{let k=await n.text();try{l=JSON.parse(k),Array.isArray(l)&&n.status===404&&(u=[],l=null,f=200,p="OK")}catch{n.status===404&&k===""?(f=204,p="No Content"):l={message:k}}if(l&&this.isMaybeSingle&&(!((c=l?.details)===null||c===void 0)&&c.includes("0 rows"))&&(l=null,f=200,p="OK"),l&&this.shouldThrowOnError)throw new Li.default(l)}return{error:l,data:u,count:d,status:f,statusText:p}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};rt.default=dr});var pr=te(st=>{"use strict";var ji=st&&st.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(st,"__esModule",{value:!0});var $i=ji(hr()),fr=class extends $i.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 c=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${l}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};st.default=fr});var Dt=te(it=>{"use strict";var Ui=it&&it.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(it,"__esModule",{value:!0});var Di=Ui(pr()),gr=class extends Di.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}};it.default=gr});var _r=te(ot=>{"use strict";var Mi=ot&&ot.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ot,"__esModule",{value:!0});var nt=Mi(Dt()),mr=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 nt.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,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new nt.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 c=e.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(c.length>0){let l=[...new Set(c)].map(u=>`"${u}"`);this.url.searchParams.set("columns",l.join(","))}}return new nt.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 nt.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 nt.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ot.default=mr});var Kr=te(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.version=void 0;Mt.version="0.0.0-automated"});var Yr=te(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.DEFAULT_HEADERS=void 0;var Ni=Kr();Nt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Ni.version}`}});var Qr=te(at=>{"use strict";var Xr=at&&at.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(at,"__esModule",{value:!0});var qi=Xr(_r()),Fi=Xr(Dt()),Hi=Yr(),yr=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},Hi.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new qi.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}`),c;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([u,d])=>d!==void 0).map(([u,d])=>[u,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([u,d])=>{a.searchParams.append(u,d)})):(o="POST",c=t);let l=Object.assign({},this.headers);return n&&(l.Prefer=`count=${n}`),new Fi.default({method:o,url:a,headers:l,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};at.default=yr});var is=te(q=>{"use strict";var ct=q&&q.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(q,"__esModule",{value:!0});q.PostgrestBuilder=q.PostgrestTransformBuilder=q.PostgrestFilterBuilder=q.PostgrestQueryBuilder=q.PostgrestClient=void 0;var Zr=ct(Qr());q.PostgrestClient=Zr.default;var es=ct(_r());q.PostgrestQueryBuilder=es.default;var ts=ct(Dt());q.PostgrestFilterBuilder=ts.default;var rs=ct(pr());q.PostgrestTransformBuilder=rs.default;var ss=ct(hr());q.PostgrestBuilder=ss.default;q.default={PostgrestClient:Zr.default,PostgrestQueryBuilder:es.default,PostgrestFilterBuilder:ts.default,PostgrestTransformBuilder:rs.default,PostgrestBuilder:ss.default}});var fs=te((To,hs)=>{"use strict";hs.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Qe=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var C=(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(()=>C(s,e,t-1),200)};var It=s=>s.verification_method==="email_otp"&&typeof s.pending_authentication_token=="string"&&s.pending_authentication_token.length>0,j="https://api.wisprflow.ai",Q=class extends Error{constructor(t,r,i,n=null){super(i);this.status=t;this.code=r;this.passwordRejectionMessage=n;this.name="AriaAuthError"}},F=s=>s.trim().toLowerCase(),Fr=(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"},Ze=(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."),wi=(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)??Ze(e,t),$e=(s,e)=>{let t=Fr(s,e);return new Q(e,t,wi(s,t,e),e===400&&typeof s.detail=="string"&&s.detail.length>0?s.detail:null)},vi=(s,e)=>{let t=Fr(s,e);return new Q(e,t,Ze(t,e))},Ot="promo_code",bi=4e3,ki=new Set([200,400,403,404,409,422]),Hr=s=>{let{hostname:e}=window.location,t=e.includes("wisprflow.ai")?".wisprflow.ai":e;document.cookie=`${s}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${t}`},Wr=s=>{if(!s)return"";try{return decodeURIComponent(s).trim()}catch{return""}},Si=()=>{let s=Qe()[Ot];if(s===void 0)return"";let e=Wr(s);return e||Hr(Ot),e},Ei=s=>{Wr(Qe()[Ot])===s&&Hr(Ot)},Ti=s=>s instanceof DOMException&&(s.name==="TimeoutError"||s.name==="AbortError"),Ai=(s,e)=>e===403?"forbidden":e===404?"not_found":e===409?"already_redeemed":s.detail&&!Array.isArray(s.detail)&&typeof s.detail=="object"&&typeof s.detail.code=="string"?s.detail.code:e===422?"validation_error":"unknown",or=class{static async signupUser(e){try{let t=`${j}/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(`${j}/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(`${j}/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(`${j}/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(`${j}/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=F(e),r=await fetch(`${j}/user_status?email=${encodeURIComponent(t)}`),i=await r.json().catch(()=>({}));if(!r.ok)throw $e(i,r.status);return i}static async requestPasswordReset(e,t){let r=await fetch(`${j}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:F(e),captcha_token:t})});if(!r.ok){let i=await r.json().catch(()=>({}));throw $e(i,r.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${j}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw $e(r,t.status);return r}static async signInWithCaptcha(e){let t=await fetch(`${j}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw $e(r,t.status);return r}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${j}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw $e(r,t.status);return r}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new Q(422,"invalid_code",Ze("invalid_code",422));let t=await fetch(`${j}/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=vi(r,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new Q(t.status,"verification_failed",Ze("verification_failed",t.status))}if(r.provider!=="workos"||!r.access_token||!r.refresh_token||!r.user_id||!r.email)throw new Q(t.status,"authentication_failed",Ze("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${j}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw $e(r,t.status);return r}static async applyPromoCodeFromCookie(e,t=Si()){if(t)try{let r=await fetch(`${j}/api/v1/promos/campaign/apply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e},body:JSON.stringify({code:t,source:"web"}),signal:AbortSignal.timeout(bi)}),{status:i}=r;if(!ki.has(i)){C("promo_cookie_apply",{outcome:"deferred",status:i});return}if(Ei(t),r.ok){C("promo_cookie_apply",{outcome:"attached",status:i});return}let n=await r.json().catch(()=>({}));C("promo_cookie_apply",{outcome:"rejected",status:i,reason:Ai(n,i)})}catch(r){console.error("Promo cookie apply deferred:",r),C("promo_cookie_apply",Ti(r)?{outcome:"deferred",reason:"timeout"}:{outcome:"deferred"})}}static async getSubscriptionStatus(e){return await fetch(`${j}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${j}/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=`${j}/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(`${j}/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(`${j}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${j}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${j}/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(`${j}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:r})}};function Br(s){let[e,...t]=s.split(" "),r=t.join(" ");return[e,r]}function zr(s){return s==="azure"?"Microsoft":s==="workos"?"SSO":s.charAt(0).toUpperCase()+s.slice(1)}var N=or;var Gr=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(fe(),we)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var et=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Lt=class extends et{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},jt=class extends et{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},$t=class extends et{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Ut;(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"})(Ut||(Ut={}));var Oi=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(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((r=r.apply(s,e||[])).next())})},tt=class{constructor(e,{headers:t={},customFetch:r,region:i=Ut.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Gr(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return Oi(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let l;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",l=o):typeof o=="string"?(a["Content-Type"]="text/plain",l=o):typeof FormData<"u"&&o instanceof FormData?l=o:(a["Content-Type"]="application/json",l=JSON.stringify(o)));let u=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:l}).catch(w=>{throw new Lt(w)}),d=u.headers.get("x-relay-error");if(d&&d==="true")throw new jt(u);if(!u.ok)throw new $t(u);let f=((r=u.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),p;return f==="application/json"?p=yield u.json():f==="application/octet-stream"?p=yield u.blob():f==="text/event-stream"?p=u:f==="multipart/form-data"?p=yield u.formData():p=yield u.text(),{data:p,error:null}}catch(i){return{data:null,error:i}}})}};var ns=qr(is(),1),{PostgrestClient:os,PostgrestQueryBuilder:no,PostgrestFilterBuilder:oo,PostgrestTransformBuilder:ao,PostgrestBuilder:co}=ns.default;var as="2.10.2";var cs={"X-Client-Info":`realtime-js/${as}`},ls="1.0.0",Ft=1e4,us=1e3,ve;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(ve||(ve={}));var H;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(H||(H={}));var z;(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"})(z||(z={}));var qt;(function(s){s.websocket="websocket"})(qt||(qt={}));var pe;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(pe||(pe={}));var lt=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 c=r.decode(e.slice(o,o+n));o=o+n;let l=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:l}}};var be=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 I;(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"})(I||(I={}));var vr=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=Wi(o,s,e,i),n),{})},Wi=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?ds(n,o):wr(o)},ds=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return Ji(e,t)}switch(s){case I.bool:return Bi(e);case I.float4:case I.float8:case I.int2:case I.int4:case I.int8:case I.numeric:case I.oid:return zi(e);case I.json:case I.jsonb:return Gi(e);case I.timestamp:return Vi(e);case I.abstime:case I.date:case I.daterange:case I.int4range:case I.int8range:case I.money:case I.reltime:case I.text:case I.time:case I.timestamptz:case I.timetz:case I.tsrange:case I.tstzrange:return wr(e);default:return wr(e)}},wr=s=>s,Bi=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},zi=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},Gi=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},Ji=(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=>ds(e,a))}return s},Vi=s=>typeof s=="string"?s.replace(" ","T"):s,Ht=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var ke=class{constructor(e,t,r={},i=Ft){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 br;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(br||(br={}));var De=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(c=>{this.state=s.syncDiff(this.state,c,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={},c={};return this.map(n,(l,u)=>{o[l]||(c[l]=u)}),this.map(o,(l,u)=>{let d=n[l];if(d){let f=u.map(S=>S.presence_ref),p=d.map(S=>S.presence_ref),w=u.filter(S=>p.indexOf(S.presence_ref)<0),k=d.filter(S=>f.indexOf(S.presence_ref)<0);w.length>0&&(a[l]=w),k.length>0&&(c[l]=k)}else a[l]=u}),this.syncDiff(n,{joins:a,leaves:c},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,c)=>{var l;let u=(l=e[a])!==null&&l!==void 0?l:[];if(e[a]=this.cloneDeep(c),u.length>0){let d=e[a].map(p=>p.presence_ref),f=u.filter(p=>d.indexOf(p.presence_ref)<0);e[a].unshift(...f)}r(a,u,c)}),this.map(o,(a,c)=>{let l=e[a];if(!l)return;let u=c.map(d=>d.presence_ref);l=l.filter(d=>u.indexOf(d.presence_ref)<0),e[a]=l,i(a,l,c),l.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 kr;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(kr||(kr={}));var Sr;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(Sr||(Sr={}));var Er;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Er||(Er={}));var Me=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=H.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 ke(this,z.join,this.params,this.timeout),this.rejoinTimer=new be(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=H.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=H.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=H.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=H.errored,this.rejoinTimer.scheduleTimeout())}),this._on(z.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new De(this),this.broadcastEndpointURL=Ht(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(u=>e&&e("CHANNEL_ERROR",u)),this._onClose(()=>e&&e("CLOSED"));let c={},l={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(u=>u.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:l},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:u})=>{var d;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),u===void 0){e&&e("SUBSCRIBED");return}else{let f=this.bindings.postgres_changes,p=(d=f?.length)!==null&&d!==void 0?d:0,w=[];for(let k=0;k<p;k++){let S=f[k],{filter:{event:O,schema:h,table:m,filter:R}}=S,L=u&&u[k];if(L&&L.event===O&&L.schema===h&&L.table===m&&L.filter===R)w.push(Object.assign(Object.assign({},S),{id:L.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=w,e&&e("SUBSCRIBED");return}}).receive("error",u=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(u).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 c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let l=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),l.receive("ok",()=>n("ok")),l.receive("error",()=>n("error")),l.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=H.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(z.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new ke(this,z.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 ke(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:c,leave:l,join:u}=z;if(r&&[a,c,l,u].indexOf(o)>=0&&r!==this._joinRef())return;let f=this._onMessage(o,t,r);if(t&&!f)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(p=>{var w,k,S;return((w=p.filter)===null||w===void 0?void 0:w.event)==="*"||((S=(k=p.filter)===null||k===void 0?void 0:k.event)===null||S===void 0?void 0:S.toLocaleLowerCase())===o}).map(p=>p.callback(f,r)):(n=this.bindings[o])===null||n===void 0||n.filter(p=>{var w,k,S,O,h,m;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){let R=p.id,L=(w=p.filter)===null||w===void 0?void 0:w.event;return R&&((k=t.ids)===null||k===void 0?void 0:k.includes(R))&&(L==="*"||L?.toLocaleLowerCase()===((S=t.data)===null||S===void 0?void 0:S.type.toLocaleLowerCase()))}else{let R=(h=(O=p?.filter)===null||O===void 0?void 0:O.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return R==="*"||R===((m=t?.event)===null||m===void 0?void 0:m.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof f=="object"&&"ids"in f){let w=f.data,{schema:k,table:S,commit_timestamp:O,type:h,errors:m}=w;f=Object.assign(Object.assign({},{schema:k,table:S,commit_timestamp:O,eventType:h,new:{},old:{},errors:m}),this._getPayloadRecords(w))}p.callback(f,r)})}_isClosed(){return this.state===H.closed}_isJoined(){return this.state===H.joined}_isJoining(){return this.state===H.joining}_isLeaving(){return this.state===H.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(z.close,{},e)}_onError(e){this._on(z.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=H.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=vr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=vr(e.columns,e.old_record)),t}};var Yi=()=>{},Xi=typeof WebSocket<"u",Ne=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=cs,this.params={},this.timeout=Ft,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Yi,this.conn=null,this.sendBuffer=[],this.serializer=new lt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(fe(),we)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${qt.websocket}`,this.httpEndpoint=Ht(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 be(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(Xi){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Tr(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>qr(fs())).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 ve.connecting:return pe.Connecting;case ve.open:return pe.Open;case ve.closing:return pe.Closing;default:return pe.Closed}}isConnected(){return this.connectionState()===pe.Open}channel(e,t={config:{}}){let r=new Me(`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 c;(c=this.conn)===null||c===void 0||c.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(z.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(z.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(us,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Tr=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=ve.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var qe=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function U(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var Wt=class extends qe{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},ut=class extends qe{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Qi=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(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((r=r.apply(s,e||[])).next())})},Bt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(fe(),we)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},ps=()=>Qi(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(fe(),we))).Response:Response});var Fe=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(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((r=r.apply(s,e||[])).next())})},Ar=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Zi=(s,e)=>Fe(void 0,void 0,void 0,function*(){let t=yield ps();s instanceof t?s.json().then(r=>{e(new Wt(Ar(r),s.status||500))}).catch(r=>{e(new ut(Ar(r),r))}):e(new ut(Ar(s),s))}),en=(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 zt(s,e,t,r,i,n){return Fe(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,en(e,r,i,n)).then(c=>{if(!c.ok)throw c;return r?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Zi(c,a))})})}function dt(s,e,t,r){return Fe(this,void 0,void 0,function*(){return zt(s,"GET",e,t,r)})}function re(s,e,t,r,i){return Fe(this,void 0,void 0,function*(){return zt(s,"POST",e,r,i,t)})}function gs(s,e,t,r,i){return Fe(this,void 0,void 0,function*(){return zt(s,"PUT",e,r,i,t)})}function Gt(s,e,t,r,i){return Fe(this,void 0,void 0,function*(){return zt(s,"DELETE",e,r,i,t)})}var J=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(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((r=r.apply(s,e||[])).next())})},tn={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ms={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ht=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=Bt(i)}uploadOrUpdate(e,t,r,i){return J(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},ms),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 c=this._removeEmptyFolders(t),l=this._getFinalPath(c),u=yield this.fetch(`${this.url}/object/${l}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),d=yield u.json();return u.ok?{data:{path:c,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(n){if(U(n))return{data:null,error:n};throw n}})}upload(e,t,r){return J(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return J(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,l=Object.assign({upsert:ms.upsert},i),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(l.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",l.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",l.cacheControl)):(c=r,u["cache-control"]=`max-age=${l.cacheControl}`,u["content-type"]=l.contentType);let d=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:u}),f=yield d.json();return d.ok?{data:{path:n,fullPath:f.Key},error:null}:{data:null,error:f}}catch(c){if(U(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return J(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 re(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 qe("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(U(r))return{data:null,error:r};throw r}})}update(e,t,r){return J(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return J(this,void 0,void 0,function*(){try{return{data:yield re(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(U(i))return{data:null,error:i};throw i}})}copy(e,t,r){return J(this,void 0,void 0,function*(){try{return{data:{path:(yield re(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(U(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return J(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield re(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(U(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return J(this,void 0,void 0,function*(){try{let i=yield re(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(U(i))return{data:null,error:i};throw i}})}download(e,t){return J(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 dt(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(U(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",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let l=i.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${l}`)}}}remove(e){return J(this,void 0,void 0,function*(){try{return{data:yield Gt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}list(e,t,r){return J(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},tn),t),{prefix:e||""});return{data:yield re(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(U(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 _s="2.6.0";var ys={"X-Client-Info":`storage-js/${_s}`};var He=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(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((r=r.apply(s,e||[])).next())})},ft=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},ys),t),this.fetch=Bt(r)}listBuckets(){return He(this,void 0,void 0,function*(){try{return{data:yield dt(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}})}getBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield dt(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return He(this,void 0,void 0,function*(){try{return{data:yield re(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(U(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return He(this,void 0,void 0,function*(){try{return{data:yield gs(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(U(r))return{data:null,error:r};throw r}})}emptyBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield re(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}deleteBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield Gt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}};var pt=class extends ft{constructor(e,t={},r){super(e,t,r)}from(e){return new ht(this.url,this.headers,e,this.fetch)}};var ws="2.44.4";var gt="";typeof Deno<"u"?gt="deno":typeof document<"u"?gt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?gt="react-native":gt="node";var rn={"X-Client-Info":`supabase-js-${gt}/${ws}`},vs={headers:rn},bs={schema:"public"},ks={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ss={};fe();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(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((r=r.apply(s,e||[])).next())})},nn=s=>{let e;return s?e=s:typeof fetch>"u"?e=ar:e=fetch,(...t)=>e(...t)},on=()=>typeof Headers>"u"?cr:Headers,Es=(s,e,t)=>{let r=nn(t),i=on();return(n,o)=>sn(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:s,l=new i(o?.headers);return l.has("apikey")||l.set("apikey",s),l.has("Authorization")||l.set("Authorization",`Bearer ${c}`),r(n,Object.assign(Object.assign({},o),{headers:l}))})};function Ts(s){return s.replace(/\/$/,"")}function As(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:c,global:l}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},l),n)}}var Jt="2.64.4";var xs="http://localhost:9999",Cs="supabase.auth.token";var Ps={"X-Client-Info":`gotrue-js/${Jt}`},xr=10;var mt="X-Supabase-Api-Version",Cr={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Rs(s){return Math.round(Date.now()/1e3)+s}function Os(){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 V=()=>typeof document<"u",Se={tested:!1,writable:!1},ge=()=>{if(!V())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Se.tested)return Se.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),Se.tested=!0,Se.writable=!0}catch{Se.tested=!0,Se.writable=!1}return Se.writable};function Vt(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 Kt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(fe(),we)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Is=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",Pr=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},yt=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Yt=async(s,e)=>{await s.removeItem(e)};function an(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,c,l,u=0;for(s=s.replace("-","+").replace("_","/");u<s.length;)o=e.indexOf(s.charAt(u++)),a=e.indexOf(s.charAt(u++)),c=e.indexOf(s.charAt(u++)),l=e.indexOf(s.charAt(u++)),r=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|l,t=t+String.fromCharCode(r),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),l!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var _t=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};_t.promiseConstructor=Promise;function Rr(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(an(r))}async function Ls(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function js(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 cn(s){return("0"+s.toString(16)).substr(-2)}function ln(){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,cn).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 dn(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function hn(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 dn(t)}async function Ee(s,e,t=!1){let r=ln(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await Pr(s,`${e}-code-verifier`,i);let n=await hn(r);return[n,r===n?"plain":"s256"]}var fn=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function $s(s){let e=s.headers.get(mt);if(!e||!e.match(fn))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var wt=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 Xt=class extends wt{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function Us(s){return E(s)&&s.name==="AuthApiError"}var We=class extends wt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ae=class extends wt{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},se=class extends ae{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Be=class extends ae{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Te=class extends ae{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Ae=class extends ae{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}}},vt=class extends ae{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 ae{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Qt(s){return E(s)&&s.name==="AuthRetryableFetchError"}var bt=class extends ae{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var pn=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},xe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),gn=[502,503,504];async function Ds(s){var e;if(!Is(s))throw new ze(xe(s),0);if(gn.includes(s.status))throw new ze(xe(s),s.status);let t;try{t=await s.json()}catch(n){throw new We(xe(n),n)}let r,i=$s(s);if(i&&i.getTime()>=Cr["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 bt(xe(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 bt(xe(t),s.status,t.weak_password.reasons);throw new Xt(xe(t),s.status||500,r)}var mn=(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[mt]||(n[mt]=Cr["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():"",c=await _n(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function _n(s,e,t,r,i,n){let o=mn(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(c){throw console.error(c),new ze(xe(c),0)}if(a.ok||await Ds(a),r?.noResolveJson)return a;try{return await a.json()}catch(c){await Ds(c)}}function ce(s){var e;let t=null;yn(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Rs(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function Or(s){let e=ce(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 ie(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function Ms(s){return{data:s,error:null}}function Ns(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=pn(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},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function qs(s){return s}function yn(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},Ce=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Kt(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:ie})}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:Ns,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:ie})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,c;try{let l={nextPage:null,lastPage:0,total:0},u=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:qs});if(u.error)throw u.error;let d=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(w=>{let k=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),S=JSON.parse(w.split(";")[1].split("=")[1]);l[`${S}Page`]=k}),l.total=parseInt(f)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(E(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){try{return await T(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ie})}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:ie})}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:ie})}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 Fs={getItem:s=>ge()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{ge()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{ge()&&globalThis.localStorage.removeItem(s)}};function Ir(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function Hs(){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 Pe={debug:!!(globalThis&&ge()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},kt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Zt=class extends kt{};async function Lr(s,e,t){Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),Pe.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){Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new Zt(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(Pe.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()}})}Hs();var vn={url:xs,storageKey:Cs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ps,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},St=30*1e3,Ws=3;async function Bs(s,e,t){return await t()}var Re=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&&V()&&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 Ce({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Kt(i.fetch),this.lock=i.lock||Bs,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:V()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Lr:this.lock=Bs,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:ge()?this.storage=Fs:(this.memoryStorage={},this.storage=Ir(this.memoryStorage)):(this.memoryStorage={},this.storage=Ir(this.memoryStorage)),V()&&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} (${Jt}) ${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=V()?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 We("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:ce}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:l,session:c},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:u,password:d,options:f}=e,p=null,w=null;this.flowType==="pkce"&&([p,w]=await Ee(this.storage,this.storageKey)),n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:u,password:d,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:p,code_challenge_method:w},xform:ce})}else if("phone"in e){let{phone:u,password:d,options:f}=e;n=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(r=f?.data)!==null&&r!==void 0?r:{},channel:(i=f?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:ce})}else throw new Te("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:l,session:c},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:Or})}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:Or})}else throw new Te("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 Be}:(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 yt(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:ce});return await Yt(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 Be}:(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:ce}),{data:c,error:l}=a;return l?{data:{user:null,session:null},error:l}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Be}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:l})}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:c}=e,l=null,u=null;this.flowType==="pkce"&&([l,u]=await Ee(this.storage,this.storageKey));let{error:d}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(r=c?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:l,code_challenge_method:u},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){let{phone:a,options:c}=e,{data:l,error:u}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:l?.message_id},error:u}}throw new Te("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:ce});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:l,session:c},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 Ee(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:Ms})}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 se;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 Te("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 yt(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:(c,l,u)=>(!o&&l==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,l,u))})}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:ie}):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 se}: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:ie})})}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 se;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await Ee(this.storage,this.storageKey));let{data:l,error:u}=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:c}),jwt:o.access_token,xform:ie});if(u)throw u;return o.user=l.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 Rr(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 se;let t=Date.now()/1e3,r=t,i=!0,n=null,o=Rr(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in: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 se;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(!V())throw new Ae("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Ae("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new vt("Not a valid PKCE flow url.");let t=Vt(window.location.href);if(e){if(!t.code)throw new vt("No code detected.");let{data:h,error:m}=await this._exchangeCodeForSession(t.code);if(m)throw m;let R=new URL(window.location.href);return R.searchParams.delete("code"),window.history.replaceState(window.history.state,"",R.toString()),{data:{session:h.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Ae(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:c,token_type:l}=t;if(!n||!a||!o||!l)throw new Ae("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),f=u+d;c&&(f=parseInt(c));let p=f-u;p*1e3<=St&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${d}s`);let w=f-d;u-w>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",w,f,u):u-w<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",w,f,u);let{data:k,error:S}=await this._getUser(n);if(S)throw S;let O={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:d,expires_at:f,refresh_token:o,token_type:l,user:k.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:O,redirectType:t.type},error:null}}catch(t){if(E(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Vt(window.location.href);return!!(V()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Vt(window.location.href),t=await yt(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&&!(Us(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Yt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Os(),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 Ee(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,c,l,u;let{data:d,error:f}=n;if(f)throw f;let p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await T(this.fetch,"GET",p,{headers:this.headers,jwt:(u=(l=d.session)===null||l===void 0?void 0:l.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return V()&&!(!((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 js(async i=>(i>0&&await Ls(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:ce})),(i,n)=>{let o=200*Math.pow(2,i);return n&&Qt(n)&&Date.now()+o-r<St})}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),V()&&!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 yt(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+xr;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${xr}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),Qt(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 se;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new _t;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new se;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 Qt(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(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Pr(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Yt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&V()&&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(),St);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)/St);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${St}ms, refresh threshold is ${Ws} ticks`),i<=Ws&&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 kt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!V()||!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 Ee(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:c}=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 c?{data:null,error:c}:(!((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 c=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");let u=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:u},error:null}}))}};Re.nextInstanceID=0;var bn=Re,jr=bn;var er=class extends jr{constructor(e){super(e)}};var kn=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(u){try{l(r.next(u))}catch(d){o(d)}}function c(u){try{l(r.throw(u))}catch(d){o(d)}}function l(u){u.done?n(u.value):i(u.value).then(a,c)}l((r=r.apply(s,e||[])).next())})},Et=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=Ts(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,l={db:bs,realtime:Ss,auth:Object.assign(Object.assign({},ks),{storageKey:c}),global:vs},u=As(r??{},l);this.storageKey=(i=u.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=u.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=Es(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},u.realtime)),this.rest=new os(`${a}/rest/v1`,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new tt(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new pt(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 kn(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},c,l){var u;let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new er({url:this.authUrl,headers:Object.assign(Object.assign({},d),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:l,hasCustomAuthorizationHeader:(u="Authorization"in this.headers)!==null&&u!==void 0?u:!1})}_initRealtimeClient(e){return new Ne(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 zs=(s,e,t)=>new Et(s,e,t);var le={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Sn=s=>{try{let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},tr=s=>{let[e,t]=s.split(".");return!e||!t?null:Sn(t)},Ge=s=>{let e=tr(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 En="https://api.workos.com",Tn=60,Je=(s,e)=>typeof s[e]=="string"?s[e]:void 0,Gs=(s,e,t)=>{let r=tr(s);if(!r)return null;let i=Je(r,"urn:wispr:user_external_id")??Je(r,"sub"),n=t?.email??Je(r,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof r.exp=="number"?r.exp:void 0,c={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:c}},An=async(s,e,t,r)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):En,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()},Js=async(s,e)=>{let t=tr(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=Je(t,"client_id");if(i-r<Tn&&n){let c=await An(e,n,Je(t,"iss"),Je(t,"org_id")),l=Gs(c.access_token,c.refresh_token,c.user);if(!l)throw new Error("WorkOS refresh returned an invalid access token");return l}if(i<=r)throw new Error("WorkOS session expired");let a=Gs(s,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var Ve=class{constructor(){this.sessionData=null;this.supabase=zs(le.supaBaseUrl,le.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||le.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||le.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||le.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(Ge(t)==="workos"){this.sessionData=await Js(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||le.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 N.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,redirect_url:i||le.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 N.signInWithCaptcha({email:e,password:t,captcha_token:r,provision:i?.provision??!1,workos_capable:i?.workosCapable||void 0});if(It(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 N.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||le.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 rr=null,Vs=(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},sr=()=>{rr!==null&&(window.clearInterval(rr),rr=null)};function Ke(){let s=document.querySelector("[otp-verification]");s&&(s.style.display="none"),sr()}function Ks(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]"),c=document.querySelector("[otp-resend-countdown]"),l=document.querySelector("[otp-resend-seconds]"),u=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"),c&&(c.style.display="none"),a&&(a.style.display=""),i&&(i.textContent="Verify",i.style.pointerEvents="",i.removeAttribute("aria-disabled")),sr(),r&&(r.textContent=s.email),e.style.display="block",t[0]?.focus();let d=h=>{n&&(n.style.display="block"),o&&(o.textContent=h)},f=()=>{n&&(n.style.display="none")},p=!1,w=!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")))},S=async()=>{if(p)return;let h=t.map(m=>m.value).join("");if(h.length!==6){d("Please enter all 6 digits.");return}p=!0,k(!0),t.forEach(m=>m.setAttribute("disabled","true")),f();try{await s.onVerify(h),f(),i&&(i.textContent="Verified \u2705")}catch(m){p=!1,k(!1),t.forEach(R=>{R.value="",R.removeAttribute("disabled")}),d(Vs(m,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((h,m)=>{h.oninput=()=>{h.value=h.value.replace(/\D/g,"").slice(0,1),h.value&&m<t.length-1&&t[m+1].focus(),f()},h.onkeydown=R=>{R.key==="Backspace"&&!h.value&&m>0?t[m-1].focus():R.key==="Enter"&&(R.preventDefault(),S())},h.onpaste=R=>{R.preventDefault();let L=(R.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);L.split("").forEach((W,Z)=>{t[Z]&&(t[Z].value=W)});let oe=Math.min(L.length,t.length-1);t[oe]?.focus(),f()}}),i&&(i.onclick=h=>{h.preventDefault(),S()});let O=()=>{let h=30;a&&(a.style.display="none"),c&&(c.style.display="block"),l&&(l.textContent=String(h)),sr(),rr=window.setInterval(()=>{h-=1,l&&(l.textContent=String(h)),h<=0&&(sr(),a&&(a.style.display=""),c&&(c.style.display="none"))},1e3)};a&&(a.onclick=async h=>{if(h.preventDefault(),!(w||a.style.display==="none")){w=!0,t.forEach(m=>{m.value="",m.removeAttribute("disabled")}),t[0]?.focus(),f(),O();try{await s.onResend?.()}catch(m){d(Vs(m,"We couldn't send a new code. Please try again when the timer ends."))}finally{w=!1}}}),u&&(u.onclick=h=>{h.preventDefault(),Ke(),s.onReset?.()})}var Oe=()=>window.hcaptcha,ir=async()=>{let s=Oe();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},Tt=(s,e)=>s instanceof Error?s.message:e,Ys=(s,e)=>s instanceof Q?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,Xs=s=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(r){e={pendingAuthenticationToken:r.pendingAuthenticationToken,email:F(r.email)},s.beforeShow(),Ks({email:e.email,onVerify:async i=>{if(!e)throw Ke(),s.onMissingChallenge(),new Error("Missing OTP challenge");let n=await N.verifyEmailOtp({code:i,pending_authentication_token:e.pendingAuthenticationToken});t(),await s.onAuthenticated(n)},onResend:async()=>{if(!e)throw Ke(),s.onMissingChallenge(),new Error("Missing OTP challenge");let i=await ir();try{await s.client.resendVerificationEmail(e.email,s.redirectUrl,i,{workosCapable:s.isWorkosCapable(e.email)})}finally{Oe()?.reset()}},onReset:()=>{t(),s.onReset()}})}}};var ne=null;function $r(s,e=30,t){ne&&(clearInterval(ne),ne=null);let r=e;s.style.pointerEvents="none",s.textContent=`Resend (${r}s)`,ne=setInterval(()=>{r=r-1,s.textContent=r>0?`Resend (${r}s)`:"Resend email",r===0&&(s.style.pointerEvents="auto",ne&&(clearInterval(ne),ne=null),t&&t())},1e3)}function Qs(){ne&&(clearInterval(ne),ne=null)}var Zs=/^[\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":Zs.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 Ur(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":Zs.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 ei(s,e,t){let r="full-name-match-error",i=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let l=document.getElementById(r);l||(l=document.createElement("div"),l.id=r,l.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",l)),l.textContent=c},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(r)?.remove()},o=()=>{let c=xn(e.value,s.value);c?i(c):n()},a=()=>{let c=Ur(e.value,s.value);c?i(c):n()};s.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var ti="password-rejection-error",ri=s=>s instanceof Q?s.passwordRejectionMessage:null,At=s=>{s.classList.remove("error"),document.getElementById(ti)?.remove()},Dr=(s,e)=>{if(At(s),e.length===0)return;s.classList.add("error");let t=document.createElement("div");t.id=ti,t.style.fontSize="0.875rem",t.textContent=e,s.insertAdjacentElement("afterend",t)};var Cn="wisprjam.com",Pn="wispr.ai",Rn="wispr_workos_capable",On=s=>s.trim().toLowerCase().split("@")[1]??"",ii=s=>{let e=On(s);return e===Cn||e===Pn},si=()=>{try{return window.sessionStorage.getItem(Rn)==="true"}catch{return!1}};function ni(s,e){let t=new Ve,r="email_input",i=null,n=()=>{i?.clear()},o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),c=document.querySelector("#password-input"),l=document.querySelector("#full-name"),u=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),f=document.querySelector("#microsoft-login"),p=document.querySelector("[email-element]"),w=document.querySelector("[different-provider]"),k=document.querySelector("[different-provider-name]"),S=document.querySelector("[different-provider-reset]"),O=document.querySelector("[email-signup-success]"),h=document.querySelector("[email-signup-error]"),m=document.querySelector("[error-message]"),R=document.querySelector("[verification-email]"),L=document.querySelector("[email-signup-retry]"),oe=document.querySelector("[email-signup-reset]"),W=document.querySelector("[scim-div]"),Z=document.querySelector("[scim-reset]"),D=document.querySelector("[forgot-password]"),me=document.querySelector("[forgot-password-success]"),ue=document.querySelector("[forgot-password-email]"),B=document.querySelector("[unverified-email]"),xt=document.querySelector("[unverified-email-address]"),K=document.querySelector("[resend-verification-email]"),M=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(u&&u.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(s)}catch(y){console.error("Error during Google sign-in:",y)}}),d&&d.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","apple"),await t.signInWithApple(s)}catch(y){console.error("Error during Apple sign-in:",y)}}),f&&f.addEventListener("click",async()=>{try{n(),localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(s)}catch(y){console.error("Error during Microsoft sign-in:",y)}}));let Y=()=>{n(),w&&(w.style.display="none"),O&&(O.style.display="none"),h&&(h.style.display="none"),B&&(B.style.display="none"),W&&(W.style.display="none"),D&&(D.style.display="none"),me&&(me.style.display="none"),Ke();let y=document.querySelector(".gs-hero_form-block");y&&(y.style.display="block"),p&&(p.style.display="flex"),a&&(a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled")),c&&(c.value="",c.style.display="none",c.removeAttribute("required"),At(c)),l&&(l.value="",l.style.display="none",l.removeAttribute("required"));let v=document.querySelector("[captcha-embed]"),P=document.querySelector("#h-captcha-container");v&&(v.style.display="none"),P&&(P.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),r="email_input",a&&a.focus()},de=()=>{p&&(p.style.display="flex"),a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),c&&(c.style.display="block",c.setAttribute("required","true"),c.focus()),l&&(l.style.display="none",l.removeAttribute("required"));let y=document.querySelector("[captcha-embed]"),v=document.querySelector("#h-captcha-container");y&&(y.style.display="block"),v&&(v.style.display="block"),D&&(D.style.display="block",D.onclick=async()=>{let P=a?.value||"",A=D.textContent||"";try{let{hcaptcha:_}=window;if(!_)throw new Error("Verification system not loaded. Please refresh the page.");D.style.pointerEvents="none",D.textContent="Sending...";let{response:g}=await _.execute({async:!0});if(!g)throw new Error("Verification cancelled");await N.requestPasswordReset(P,g),_.reset(),p&&(p.style.display="none"),D&&(D.style.display="none"),me&&(me.style.display="block"),ue&&(ue.textContent=P)}catch(_){console.error("Error sending password reset email:",_),D.textContent=A,D.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",m&&(m.textContent=_ instanceof Error?_.message:"Failed to send reset email"))}}),r="login"},Ye=()=>{a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),c&&(c.style.display="block",c.setAttribute("required","true"),c.focus()),l&&(l.style.display="block",l.setAttribute("required","true"));let y=document.querySelector("[captcha-embed]"),v=document.querySelector("#h-captcha-container");y&&(y.style.display="block"),v&&(v.style.display="block"),r="signup"},_e=()=>{let y=document.querySelector(".gs-hero_form-block");y&&(y.style.display="none"),W&&(W.style.display="block"),Z&&(Z.onclick=()=>{W&&(W.style.display="none"),y&&(y.style.display="block"),Y()})},Ie=y=>{n();let v=zr(y);p&&(p.style.display="none"),w&&(w.style.display="block"),k&&(k.textContent=v),S&&(S.onclick=()=>{w&&(w.style.display="none"),Y()}),r="oauth_user"};i=Xs({client:t,redirectUrl:s,isWorkosCapable:()=>!0,beforeShow:()=>{p&&(p.style.display="none"),B&&(B.style.display="none")},onAuthenticated:async y=>{n(),t.setCookies(y.access_token,y.refresh_token),localStorage.setItem("email",y.email),localStorage.setItem("user_id",y.user_id),localStorage.setItem("signin_provider","email");let v=[y.first_name,y.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(y.access_token,y.refresh_token,v):window.location.href=s},onMissingChallenge:de,onReset:Y});let G=y=>{p&&(p.style.display="none"),B&&(B.style.display="block"),xt&&(xt.textContent=y),K&&(K.onclick=async()=>{let v=K.textContent||"";try{let P=await ir();await t.resendVerificationEmail(y,s,P),K.textContent="Verification email resent! \u2705",K.style.textDecoration="none"}catch(P){K.textContent=v,h&&(h.style.display="block"),m&&(m.textContent=Tt(P,"Unable to resend verification."))}finally{Oe()?.reset()}}),M&&(M.onclick=()=>{B&&(B.style.display="none"),Y()}),r="unverified_email"},X=y=>Ys(y,{showSso:()=>Ie("workos"),showScim:_e,showLogin:de,showError:v=>{h&&(h.style.display="block"),m&&(m.textContent=v)}}),he=async(y,v)=>{let P=v.value;v.classList.add("loading"),v.value="";try{let A=await N.checkUserStatus(y);v.classList.remove("loading"),v.value=P,!A.exists&&A.scim_managed?_e():A.enforce_sso?Ie("workos"):A.exists&&A.provider&&A.provider!=="email"&&A.provider!=="workos"?Ie(A.provider):A.exists&&A.provider==="workos"?de():A.exists&&A.provider==="email"&&!A.verified?G(y):A.exists&&A.provider==="email"?de():Ye()}catch(A){console.error("Error checking user status:",A),v.classList.remove("loading"),v.value=P,X(A)||Ye()}},Xe=async(y,v,P,A)=>{if(!v||v.length<8){h&&(h.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}let _=window.hcaptcha?.getResponse()||"";if(!_){h&&(h.style.display="block",m&&(m.textContent="Please complete the verification"));return}P.classList.add("loading"),P.value="";try{if(e?.mcpLoginState){let x=await N.signInWithEmail({email:y,password:v,mcp_login_state:e.mcpLoginState,workos_capable:si()});if(!x.redirect_url)throw new Error(x.error||"Unable to continue connector login. Please try again.");C("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=x.redirect_url;return}let g=si(),b=await t.signInWithPassword(y,v,_,{workosCapable:g,provision:!1});if(b.kind==="otp"){if(!g)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let x={pendingAuthenticationToken:b.challenge.pending_authentication_token,email:F(b.challenge.email||y)};Oe()?.reset(),P.classList.remove("loading"),P.value=A,i?.show(x);return}t.setCookies(b.accessToken,b.refreshToken),localStorage.setItem("email",y),e?.onLoginSuccess?await e.onLoginSuccess(b.accessToken,b.refreshToken,b.fullName):window.location.href=s}catch(g){window.hcaptcha&&window.hcaptcha.reset(),P.classList.remove("loading"),P.value=A,!X(g)&&h&&(h.style.display="block",m&&(m.textContent=Tt(g,"Unable to sign in. Please try again.")))}},Le=async(y,v,P,A,_)=>{if(!v||v.length<8){h&&(h.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}if(v.trim().toLowerCase()===y.trim().toLowerCase()){Dr(c,"Password can't be the same as your email address.");return}if(!P||P.trim().length<2){h&&(h.style.display="block",m&&(m.textContent="Please enter your full name"));return}let g=Ur(P,v);if(g){h&&(h.style.display="block",m&&(m.textContent=g));return}let b=window.hcaptcha?.getResponse()||"";if(!b){h&&(h.style.display="block",m&&(m.textContent="Please complete the verification"));return}A.classList.add("loading"),A.value="";try{let x=await t.signUpWithPassword(y,v,P,s,b,{workosCapable:!0});if(window.hcaptcha&&window.hcaptcha.reset(),A.classList.remove("loading"),A.value=_,p&&(p.style.display="none"),h&&(h.style.display="none"),It(x)){let $={pendingAuthenticationToken:x.pending_authentication_token,email:F(x.email||y)};i?.show($);return}O&&(O.style.display="block"),R&&(R.textContent=y),L&&($r(L,30),L.onclick=async()=>{if(L.style.pointerEvents!=="none")try{let $=await ir();await t.resendVerificationEmail(y,s,$,{workosCapable:!0}),$r(L,30)}catch($){h&&(h.style.display="block"),m&&(m.textContent=Tt($,"Unable to resend verification. Please try again."))}finally{Oe()?.reset()}}),oe&&(oe.onclick=()=>{O&&(O.style.display="none"),Qs(),Y()})}catch(x){A.classList.remove("loading"),A.value=_,Oe()?.reset();let $=ri(x);$&&c?Dr(c,$):!X(x)&&h&&(h.style.display="block",m&&(m.textContent=Tt(x,"Unable to create the account. Please try again.")))}};return o&&c&&l&&(ei(c,l,o.querySelector('[type="submit"]')),c.addEventListener("input",()=>At(c))),o&&o.addEventListener("submit",async y=>{y.stopPropagation(),y.preventDefault();let v=F(a?.value||"");a&&(a.value=v);let P=c?.value||"",A=l?.value||"";if(!v||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)){h&&(h.style.display="block",m&&(m.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),m&&(m.textContent=""),c&&At(c);let g=o.querySelector('[type="submit"]'),b=g?.value||"";localStorage.setItem("signin_provider","email");try{r==="email_input"?await he(v,g):r==="login"?await Xe(v,P,g,b):r==="signup"&&await Le(v,P,A,g,b)}catch(x){console.error("Auth flow error:",x),g&&(g.classList.remove("loading"),g.value=b),h&&(h.style.display="block")}}),{reset:Y}}var In="wf_first_landing_url";var oi=()=>{try{return localStorage.getItem(In)||void 0}catch{return}};var Ln=/google ads|google adservices|adwords/i,jn=/marketing|advertising/i,ai=s=>{let e=s.filter(r=>Ln.test(r.name??""));if(e.length>0)return e.every(r=>r.decision===!0)?{ad_user_data:!0,ad_personalization:!0}:e.every(r=>r.decision===!1)?{ad_user_data:!1,ad_personalization:!1}:void 0;let t=s.filter(r=>jn.test(r.category??""));if(t.length!==0){if(t.some(r=>r.decision===!0))return{ad_user_data:!0,ad_personalization:!0};if(t.every(r=>r.decision===!1))return{ad_user_data:!1,ad_personalization:!1}}},$n=async()=>{try{let{__ucCmp:s,UC_UI:e}=window;if(s?.getConsentDetails){let t=await s.getConsentDetails();return ai(Object.values(t?.services??{}).map(r=>({name:r?.name,category:r?.category,decision:r?.consent?.type==="EXPLICIT"&&typeof r.consent.given=="boolean"?r.consent.given:void 0})))}if(e?.getServicesBaseInfo)return ai((e.getServicesBaseInfo()??[]).map(t=>({name:t?.name,category:t?.categorySlug,decision:t?.consent?.history?.some(r=>r?.type==="EXPLICIT")&&typeof t.consent.status=="boolean"?t.consent.status:void 0})))}catch{}},ci=()=>{let s=new Promise(e=>{setTimeout(()=>e(void 0),1500)});return Promise.race([$n(),s])};function li(s){try{let e=s._gcl_aw;if(e){let t;try{t=decodeURIComponent(e)}catch{t=e}let r=t.split(".");if(r.length>=3){let i=r.slice(2).join(".");if(i)return i}}return new URLSearchParams(window.location.search).get("gclid")||void 0}catch{return}}var Mr="https://api.wisprflow.ai",ui="https://wisprflow.ai",Un="workos_enabled_webflow";window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=new Ve,e=document.querySelector("[loading-div]"),t=document.querySelector("[success-div]"),r=document.querySelector("[error-div]"),i=document.querySelector("[error-message-api]"),n=document.querySelector("[signup-card]"),o=document.querySelector("[logo-wrap]"),a=document.querySelector("[ip-blocked-div]"),c=document.querySelector('#email-form [type="submit"]'),l=c?.value??"",u=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),f=document.querySelector("#microsoft-login"),p=document.querySelector("#sso-login"),w=document.querySelector("[sso-login-div]"),k=document.querySelector("#sso-email"),S=document.querySelector("#sso-signup-form"),O=document.querySelector('[sso-login="go-back"]'),h=document.querySelector(".gs-hero_form-block"),m=localStorage.getItem("last_authed_provider");m&&{google:u,apple:d,microsoft:f,sso:p,email:document.querySelector("#email-input")}[m]?.classList.add("last-used");let R=()=>{e&&(e.style.display="block"),t&&(t.style.display="none"),r&&(r.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},L=()=>{let g=document.querySelector("[open-button]")?.getAttribute("href")||"wispr-flow://open";C("desktop_login_auto_launch",{deep_link:g}),window.location.href=g},oe=()=>{let _=localStorage.getItem("signin_provider");_&&localStorage.setItem("last_authed_provider",_),e&&(e.style.display="none"),t&&(t.style.display="block"),r&&(r.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible",L()},W=_=>{e&&(e.style.display="none"),t&&(t.style.display="none"),r&&(r.style.display="block"),i&&(i.textContent=_),n&&(n.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},Z=()=>{e&&(e.style.display="none"),t&&(t.style.display="none"),r&&(r.style.display="none"),n&&(n.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="block"),document.body.style.visibility="visible"},D=null,me=document.querySelector("[retry-button]");me&&me.addEventListener("click",()=>ue());let ue=()=>{e&&(e.style.display="none"),r&&(r.style.display="none"),a&&(a.style.display="none"),n&&(n.style.display="block"),o&&(o.style.display="block"),document.body.style.visibility="visible",c&&(c.classList.remove("loading"),c.value=l),D&&D()},B=async(_,g)=>{try{let[b,x]=Br(g||" "),$=N.signupUser({access_token:_,first_name:b,last_name:x}),ee=new Promise((je,ye)=>setTimeout(()=>ye(new Error("signup timeout")),4e3));await Promise.race([$,ee])}catch(b){C("signup_sync_error",{error_message:b instanceof Error?b.message:String(b)})}},xt=()=>{let _=sessionStorage.getItem("wispr_fbclid");return _?`fb.1.${Date.now()}.${_}`:null},K=async(_,g)=>{let b=sessionStorage.getItem("wispr_device_code");if(!b)throw new Error("Device code not found. Please restart authentication from desktop app.");let x=Qe(),$=await ci(),ee=localStorage.getItem("wf_utm_source")||void 0,je=localStorage.getItem("wf_utm_medium")||void 0,ye=localStorage.getItem("wf_utm_campaign")||void 0,Ct=await fetch(`${Mr}/device/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${_}`},body:JSON.stringify({device_code:b,access_token:_,refresh_token:g,fbp:x._fbp||void 0,fbc:x._fbc||xt()||void 0,gclid:li(x),utm:ee||je||ye?{utm_source:ee,utm_medium:je,utm_campaign:ye}:void 0,first_landing_url:oi(),ad_user_data:$?.ad_user_data,ad_personalization:$?.ad_personalization})});if(!Ct.ok){let Pt=await Ct.json().catch(()=>({}));throw Ct.status===403&&Pt?.detail?.code==="enterprise_ip_not_allowed"?new Error("enterprise_ip_not_allowed"):new Error(Pt?.detail?.message||Pt.message||`Server error: ${Ct.status}`)}console.log("Device authentication complete"),sessionStorage.removeItem("wispr_device_code"),Ge(_)==="workos"&&s.setCookie("refresh_token",g,30/86400)},M=new URLSearchParams(window.location.search),Y=M.get("device_code"),de=M.get("error"),Ye=M.get("workos_capable");Ye==="true"?sessionStorage.setItem("wispr_workos_capable","true"):Ye==="false"&&sessionStorage.removeItem("wispr_workos_capable");let _e=sessionStorage.getItem("wispr_workos_capable")==="true",Ie=M.get("auto_signin")==="true",nr=new URLSearchParams(window.location.hash.slice(1)),G=M.get("access_token")||nr.get("access_token"),X=M.get("refresh_token")||nr.get("refresh_token"),he=M.get("mcp_login_state");if(!Y&&!G&&!X&&!he&&!sessionStorage.getItem("wispr_device_code")){console.log("No device_code found - redirecting to /get-started"),C("desktop_login_no_device_code"),window.location.href="/get-started";return}if(C("desktop_login_page_view",{auto_signin:Ie,workos_capable:_e}),Y){sessionStorage.setItem("wispr_device_code",Y);let _=M.get("fbclid");_&&sessionStorage.setItem("wispr_fbclid",_);let g=M.get("skip_default_trial"),b=M.get("grant_weekly_bonus");g&&sessionStorage.setItem("wispr_skip_default_trial",g),b&&sessionStorage.setItem("wispr_grant_weekly_bonus",b)}(Y||G||X||de)&&window.history.replaceState({},"","/login");let Xe="wispr_workos_second_hop_attempted";if(G&&X){console.log("OAuth callback detected - handling tokens");let _=Ge(G);if(C("desktop_login_oauth_callback",{provider:localStorage.getItem("signin_provider")??"unknown",token_provider:_}),R(),_==="workos"){sessionStorage.removeItem(Xe);try{s.setCookies(G,X);let g=M.get("email");g&&localStorage.setItem("email",g);let b=M.get("user_id");b&&localStorage.setItem("user_id",b),await B(G,M.get("name")??void 0),await N.applyPromoCodeFromCookie(G),await K(G,X),C("desktop_login_complete_success",{method:"oauth",provider:"workos"}),oe()}catch(g){if(g instanceof Error&&g.message==="enterprise_ip_not_allowed"){C("desktop_login_complete_error",{method:"oauth",provider:"workos",error:"enterprise_ip_not_allowed"}),Z();return}let b=g instanceof Error?g.message:"Failed to complete authentication. Please try again.";C("desktop_login_complete_error",{method:"oauth",provider:"workos",error:b}),console.error("Error completing WorkOS device authentication:",g),W(b)}return}try{let g=G,b=X;try{s.setCookies(G,X),await s.checkAndSetSession(),s.sessionData&&(g=s.sessionData.access_token,b=s.sessionData.refresh_token,s.setCookies(g,b),localStorage.setItem("email",s.sessionData.user.email),s.sessionData.user.id&&localStorage.setItem("user_id",s.sessionData.user.id))}catch{}let x=s.sessionData?.user.email;if(_e&&x&&ii(x)&&localStorage.getItem("signin_provider")==="google"&&!sessionStorage.getItem(Xe)){sessionStorage.setItem(Xe,"true"),C("desktop_login_workos_second_hop",{email_domain:x.split("@")[1]??"unknown"}),window.location.href=`${Mr}/authkit/google/sign_in?source=${ui}`;return}await B(g,s.sessionData?.user.user_metadata?.full_name),await N.applyPromoCodeFromCookie(g),await K(g,b),C("desktop_login_complete_success",{method:"oauth"}),oe()}catch(g){if(g instanceof Error&&g.message==="enterprise_ip_not_allowed"){C("desktop_login_complete_error",{method:"oauth",error:"enterprise_ip_not_allowed"}),Z();return}let b=g instanceof Error?g.message:"Failed to complete authentication. Please try again.";C("desktop_login_complete_error",{method:"oauth",error:b}),console.error("Error completing device authentication:",g),W(b)}return}if(Ie){console.log("Auto-signin enabled - checking existing session"),R();try{if(await s.checkAndSetSession(),s.sessionData&&s.setCookies(s.sessionData.access_token,s.sessionData.refresh_token),s.sessionData?.access_token&&s.sessionData?.refresh_token){console.log("Existing session found - auto-completing authentication"),await B(s.sessionData.access_token,s.sessionData?.user.user_metadata?.full_name),await N.applyPromoCodeFromCookie(s.sessionData.access_token),await K(s.sessionData.access_token,s.sessionData.refresh_token),C("desktop_login_auto_signin_success",{token_provider:Ge(s.sessionData.access_token)}),oe();return}console.log("No existing session - showing login form"),C("desktop_login_auto_signin_no_session"),ue()}catch(_){if(console.error("Auto-signin error:",_),_ instanceof Error&&_.message==="enterprise_ip_not_allowed"){C("desktop_login_auto_signin_error",{error:"enterprise_ip_not_allowed"}),Z();return}let g=_ instanceof Error?_.message:"Auto-signin failed. Please try logging in manually.";C("desktop_login_auto_signin_error",{error:g}),s.setCookie("access_token","",-1),s.setCookie("refresh_token","",-1),ue()}}else he?(C("desktop_login_mcp_entry"),ue()):(C("desktop_login_manual_signout"),s.setCookie("access_token","",-1),s.setCookie("refresh_token","",-1),localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("sms_submitted"),sessionStorage.removeItem("referral_status"),ue());let Le=(_,g)=>{console.log(`Redirecting to ${_} OAuth`);let b=window.posthog?.getFeatureFlag?.(Un)===!0,x=_e&&b;C("desktop_login_oauth_click",{provider:x?"workos":_,idp:_,mcp:!!he,workos_capable:_e,workos_enabled_webflow:b}),localStorage.setItem("signin_provider",_);let $=x?`authkit/${_}/sign_in`:`${_}/sign_in`,ee=`${Mr}/${$}?source=${ui}`;g&&(ee+=`&email=${encodeURIComponent(g)}`);let je=sessionStorage.getItem("wispr_skip_default_trial"),ye=sessionStorage.getItem("wispr_grant_weekly_bonus");je&&(ee+=`&skip_default_trial=${encodeURIComponent(je)}`),ye&&(ee+=`&grant_weekly_bonus=${encodeURIComponent(ye)}`),he&&(ee+=`&mcp_login_state=${encodeURIComponent(he)}`),window.location.href=ee};u&&u.addEventListener("click",()=>{Le("google")}),d&&d.addEventListener("click",()=>{Le("apple")}),f&&f.addEventListener("click",()=>{Le("microsoft")}),p&&(p.style.display="flex",p.addEventListener("click",_=>{_.preventDefault(),w&&(w.style.display="block"),h&&(h.style.display="none"),k?.focus()})),O&&O.addEventListener("click",()=>{w&&(w.style.display="none"),h&&(h.style.display="block"),k&&(k.value="",k.blur())}),S&&S.addEventListener("submit",_=>{_.preventDefault(),_.stopPropagation();let g=F(k?.value||"");g&&Le("sso",g)});let y=async(_,g,b)=>{try{await B(_,b),await N.applyPromoCodeFromCookie(_),await K(_,g)}catch(x){if(x instanceof Error&&x.message==="enterprise_ip_not_allowed"){C("desktop_login_complete_error",{method:"email",error:"enterprise_ip_not_allowed"}),Z();return}let $=x instanceof Error?x.message:"Failed to complete authentication. Please try again.";C("desktop_login_complete_error",{method:"email",error:$}),W($);return}C("desktop_login_complete_success",{method:"email"}),oe()},v=sessionStorage.getItem("wispr_device_code"),P=v?`${window.location.origin}/login?device_code=${v}`:`${window.location.origin}/login`,{reset:A}=ni(P,{onLoginSuccess:y,mcpLoginState:he,skipOAuthButtons:!0});D=A,de==="account_unsupported"&&(C("desktop_login_oauth_error",{error:de}),W("This account is not supported. Try signing in with another account.")),console.log("Desktop login page initialized")});})();
|
|
1
|
+
"use strict";(()=>{var pn=Object.create;var Rt=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var mn=Object.getOwnPropertyNames;var _n=Object.getPrototypeOf,yn=Object.prototype.hasOwnProperty;var wn=(r,e)=>()=>(r&&(e=r(r=0)),e);var te=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),vn=(r,e)=>{for(var t in e)Rt(r,t,{get:e[t],enumerable:!0})},Ns=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of mn(e))!yn.call(r,n)&&n!==t&&Rt(r,n,{get:()=>e[n],enumerable:!(s=gn(e,n))||s.enumerable});return r};var qs=(r,e,t)=>(t=r!=null?pn(_n(r)):{},Ns(e||!r||!r.__esModule?Rt(t,"default",{value:r,enumerable:!0}):t,r)),bn=r=>Ns(Rt({},"__esModule",{value:!0}),r);var we={};vn(we,{Headers:()=>cs,Request:()=>In,Response:()=>Ln,default:()=>as,fetch:()=>On});var Rn,Ue,On,as,cs,In,Ln,fe=wn(()=>{"use strict";Rn=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")},Ue=Rn(),On=Ue.fetch,as=Ue.fetch.bind(Ue),cs=Ue.Headers,In=Ue.Request,Ln=Ue.Response});var Js=te(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});var ls=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};us.default=ls});var hs=te(st=>{"use strict";var Vs=st&&st.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(st,"__esModule",{value:!0});var $n=Vs((fe(),bn(we))),Un=Vs(Js()),ds=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=$n.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,n=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var o,a,c;let l=null,u=null,d=null,f=i.status,p=i.statusText;if(i.ok){if(this.method!=="HEAD"){let O=await i.text();O===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=O:u=JSON.parse(O))}let k=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),S=(a=i.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");k&&S&&S.length>1&&(d=parseInt(S[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(l={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,d=null,f=406,p="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{let k=await i.text();try{l=JSON.parse(k),Array.isArray(l)&&i.status===404&&(u=[],l=null,f=200,p="OK")}catch{i.status===404&&k===""?(f=204,p="No Content"):l={message:k}}if(l&&this.isMaybeSingle&&(!((c=l?.details)===null||c===void 0)&&c.includes("0 rows"))&&(l=null,f=200,p="OK"),l&&this.shouldThrowOnError)throw new Un.default(l)}return{error:l,data:u,count:d,status:f,statusText:p}});return this.shouldThrowOnError||(n=n.catch(i=>{var o,a,c;return{error:{message:`${(o=i?.name)!==null&&o!==void 0?o:"FetchError"}: ${i?.message}`,details:`${(a=i?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=i?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),n.then(e,t)}};st.default=ds});var ps=te(rt=>{"use strict";var Dn=rt&&rt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(rt,"__esModule",{value:!0});var Mn=Dn(hs()),fs=class extends Mn.default{select(e){let t=!1,s=(e??"*").split("").map(n=>/\s/.test(n)&&!t?"":(n==='"'&&(t=!t),n)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:n,referencedTable:i=n}={}){let o=i?`${i}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let n=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:n=s}={}){let i=typeof n>"u"?"offset":`${n}.offset`,o=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:n=!1,wal:i=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${l}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};rt.default=fs});var Dt=te(nt=>{"use strict";var Nn=nt&&nt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(nt,"__esModule",{value:!0});var qn=Nn(ps()),gs=class extends qn.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(n=>typeof n=="string"&&new RegExp("[,()]").test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:n}={}){let i="";n==="plain"?i="pl":n==="phrase"?i="ph":n==="websearch"&&(i="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${i}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let n=s?`${s}.or`:"or";return this.url.searchParams.append(n,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};nt.default=gs});var _s=te(ot=>{"use strict";var Fn=ot&&ot.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ot,"__esModule",{value:!0});var it=Fn(Dt()),ms=class{constructor(e,{headers:t={},schema:s,fetch:n}){this.url=e,this.headers=t,this.schema=s,this.fetch=n}select(e,{head:t=!1,count:s}={}){let n=t?"HEAD":"GET",i=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!i?"":(a==='"'&&(i=!i),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new it.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let n="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),s||i.push("missing=default"),this.headers.Prefer=i.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new it.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:n,defaultToNull:i=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),n&&a.push(`count=${n}`),i||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(c.length>0){let l=[...new Set(c)].map(u=>`"${u}"`);this.url.searchParams.set("columns",l.join(","))}}return new it.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",n=[];return this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),this.headers.Prefer=n.join(","),new it.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new it.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ot.default=ms});var Ks=te(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.version=void 0;Mt.version="0.0.0-automated"});var Ys=te(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.DEFAULT_HEADERS=void 0;var Hn=Ks();Nt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Hn.version}`}});var Qs=te(at=>{"use strict";var Xs=at&&at.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(at,"__esModule",{value:!0});var Wn=Xs(_s()),Bn=Xs(Dt()),zn=Ys(),ys=class r{constructor(e,{headers:t={},schema:s,fetch:n}={}){this.url=e,this.headers=Object.assign(Object.assign({},zn.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=n}from(e){let t=new URL(`${this.url}/${e}`);return new Wn.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:n=!1,count:i}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||n?(o=s?"HEAD":"GET",Object.entries(t).filter(([u,d])=>d!==void 0).map(([u,d])=>[u,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([u,d])=>{a.searchParams.append(u,d)})):(o="POST",c=t);let l=Object.assign({},this.headers);return i&&(l.Prefer=`count=${i}`),new Bn.default({method:o,url:a,headers:l,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};at.default=ys});var nr=te(q=>{"use strict";var ct=q&&q.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(q,"__esModule",{value:!0});q.PostgrestBuilder=q.PostgrestTransformBuilder=q.PostgrestFilterBuilder=q.PostgrestQueryBuilder=q.PostgrestClient=void 0;var Zs=ct(Qs());q.PostgrestClient=Zs.default;var er=ct(_s());q.PostgrestQueryBuilder=er.default;var tr=ct(Dt());q.PostgrestFilterBuilder=tr.default;var sr=ct(ps());q.PostgrestTransformBuilder=sr.default;var rr=ct(hs());q.PostgrestBuilder=rr.default;q.default={PostgrestClient:Zs.default,PostgrestQueryBuilder:er.default,PostgrestFilterBuilder:tr.default,PostgrestTransformBuilder:sr.default,PostgrestBuilder:rr.default}});var fr=te((Ro,hr)=>{"use strict";hr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Qe=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var x=(r,e,t=10)=>{window.posthog&&typeof window.posthog.capture=="function"?(t<10&&window.posthog.capture("event_fired_after_retry",{event_name:r,retry_attempt:10-t}),window.posthog.capture(r,e)):t>0&&setTimeout(()=>x(r,e,t-1),200)};var It=r=>r.verification_method==="email_otp"&&typeof r.pending_authentication_token=="string"&&r.pending_authentication_token.length>0,j="https://api.wisprflow.ai",Q=class extends Error{constructor(t,s,n,i=null){super(n);this.status=t;this.code=s;this.passwordRejectionMessage=i;this.name="AriaAuthError"}},F=r=>r.trim().toLowerCase(),Fs=(r,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 r.code=="string"?r.code:r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"&&typeof r.detail.code=="string"?r.detail.code:typeof r.detail=="string"&&t.has(r.detail)?r.detail:{401:"invalid_credentials",409:"identity_conflict",422:"validation_error",429:"rate_limited",503:"provider_unavailable"}[e]??"authentication_failed"},Ze=(r,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."})[r]??(e===403?"This sign-in method is not available for this account.":"Unable to complete authentication. Please try again."),kn=(r,e,t)=>[r.message,r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"?r.detail.message:null,typeof r.detail=="string"?r.detail:null].find(i=>typeof i=="string"&&i.length>0&&i!==e)??Ze(e,t),$e=(r,e)=>{let t=Fs(r,e);return new Q(e,t,kn(r,t,e),e===400&&typeof r.detail=="string"&&r.detail.length>0?r.detail:null)},Sn=(r,e)=>{let t=Fs(r,e);return new Q(e,t,Ze(t,e))},Ot="promo_code",En=4e3,Tn=new Set([200,400,403,404,409,422]),Hs=r=>{let{hostname:e}=window.location,t=e.includes("wisprflow.ai")?".wisprflow.ai":e;document.cookie=`${r}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${t}`},Ws=r=>{if(!r)return"";try{return decodeURIComponent(r).trim()}catch{return""}},An=()=>{let r=Qe()[Ot];if(r===void 0)return"";let e=Ws(r);return e||Hs(Ot),e},Cn=r=>{Ws(Qe()[Ot])===r&&Hs(Ot)},xn=r=>r instanceof DOMException&&(r.name==="TimeoutError"||r.name==="AbortError"),Pn=(r,e)=>e===403?"forbidden":e===404?"not_found":e===409?"already_redeemed":r.detail&&!Array.isArray(r.detail)&&typeof r.detail=="object"&&typeof r.detail.code=="string"?r.detail.code:e===422?"validation_error":"unknown",os=class{static async signupUser(e){try{let t=`${j}/signup`,n=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),i=n&&n.trim().split("=")[1];(i==="3mo"||i==="2mo")&&(t+=`?trial_promo=${i}`);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(`${j}/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(`${j}/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(`${j}/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(`${j}/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=F(e),s=await fetch(`${j}/user_status?email=${encodeURIComponent(t)}`),n=await s.json().catch(()=>({}));if(!s.ok)throw $e(n,s.status);return n}static async requestPasswordReset(e,t){let s=await fetch(`${j}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:F(e),captcha_token:t})});if(!s.ok){let n=await s.json().catch(()=>({}));throw $e(n,s.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${j}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw $e(s,t.status);return s}static async signInWithCaptcha(e){let t=await fetch(`${j}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw $e(s,t.status);return s}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${j}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw $e(s,t.status);return s}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new Q(422,"invalid_code",Ze("invalid_code",422));let t=await fetch(`${j}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok){let n=Sn(s,t.status);throw n.code==="rate_limited"||n.code==="provider_unavailable"||n.code==="validation_error"?n:new Q(t.status,"verification_failed",Ze("verification_failed",t.status))}if(s.provider!=="workos"||!s.access_token||!s.refresh_token||!s.user_id||!s.email)throw new Q(t.status,"authentication_failed",Ze("authentication_failed",t.status));return s}static async signInWithEmail(e){let t=await fetch(`${j}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:F(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw $e(s,t.status);return s}static async applyPromoCodeFromCookie(e,t=An()){if(t)try{let s=await fetch(`${j}/api/v1/promos/campaign/apply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e},body:JSON.stringify({code:t,source:"web"}),signal:AbortSignal.timeout(En)}),{status:n}=s;if(!Tn.has(n)){x("promo_cookie_apply",{outcome:"deferred",status:n});return}if(Cn(t),s.ok){x("promo_cookie_apply",{outcome:"attached",status:n});return}let i=await s.json().catch(()=>({}));x("promo_cookie_apply",{outcome:"rejected",status:n,reason:Pn(i,n)})}catch(s){console.error("Promo cookie apply deferred:",s),x("promo_cookie_apply",xn(s)?{outcome:"deferred",reason:"timeout"}:{outcome:"deferred"})}}static async getSubscriptionStatus(e){return await fetch(`${j}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${j}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s){let n=`${j}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(n+=`¤cy=${s}`),await(await fetch(n,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${j}/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(`${j}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${j}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${j}/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,s){let n=new FormData;return n.append("screenshot",e),await fetch(`${j}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:n,signal:s})}};function Bs(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}function zs(r){return r==="azure"?"Microsoft":r==="workos"?"SSO":r.charAt(0).toUpperCase()+r.slice(1)}var N=os;var Gs=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(fe(),we)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var et=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},Lt=class extends et{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},jt=class extends et{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},$t=class extends et{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Ut;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(Ut||(Ut={}));var jn=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},tt=class{constructor(e,{headers:t={},customFetch:s,region:n=Ut.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=Gs(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return jn(this,void 0,void 0,function*(){try{let{headers:n,method:i,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let l;o&&(n&&!Object.prototype.hasOwnProperty.call(n,"Content-Type")||!n)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",l=o):typeof o=="string"?(a["Content-Type"]="text/plain",l=o):typeof FormData<"u"&&o instanceof FormData?l=o:(a["Content-Type"]="application/json",l=JSON.stringify(o)));let u=yield this.fetch(`${this.url}/${e}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),n),body:l}).catch(w=>{throw new Lt(w)}),d=u.headers.get("x-relay-error");if(d&&d==="true")throw new jt(u);if(!u.ok)throw new $t(u);let f=((s=u.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),p;return f==="application/json"?p=yield u.json():f==="application/octet-stream"?p=yield u.blob():f==="text/event-stream"?p=u:f==="multipart/form-data"?p=yield u.formData():p=yield u.text(),{data:p,error:null}}catch(n){return{data:null,error:n}}})}};var ir=qs(nr(),1),{PostgrestClient:or,PostgrestQueryBuilder:uo,PostgrestFilterBuilder:ho,PostgrestTransformBuilder:fo,PostgrestBuilder:po}=ir.default;var ar="2.10.2";var cr={"X-Client-Info":`realtime-js/${ar}`},lr="1.0.0",Ft=1e4,ur=1e3,ve;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(ve||(ve={}));var H;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(H||(H={}));var z;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(z||(z={}));var qt;(function(r){r.websocket="websocket"})(qt||(qt={}));var pe;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(pe||(pe={}));var lt=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let n=t.getUint8(1),i=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+n));o=o+n;let c=s.decode(e.slice(o,o+i));o=o+i;let l=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:l}}};var be=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 I;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(I||(I={}));var vs=(r,e,t={})=>{var s;let n=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((i,o)=>(i[o]=Gn(o,r,e,n),i),{})},Gn=(r,e,t,s)=>{let n=e.find(a=>a.name===r),i=n?.type,o=t[r];return i&&!s.includes(i)?dr(i,o):ws(o)},dr=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return Yn(e,t)}switch(r){case I.bool:return Jn(e);case I.float4:case I.float8:case I.int2:case I.int4:case I.int8:case I.numeric:case I.oid:return Vn(e);case I.json:case I.jsonb:return Kn(e);case I.timestamp:return Xn(e);case I.abstime:case I.date:case I.daterange:case I.int4range:case I.int8range:case I.money:case I.reltime:case I.text:case I.time:case I.timestamptz:case I.timetz:case I.tsrange:case I.tstzrange:return ws(e);default:return ws(e)}},ws=r=>r,Jn=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},Vn=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},Kn=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},Yn=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let i,o=r.slice(1,t);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>dr(e,a))}return r},Xn=r=>typeof r=="string"?r.replace(" ","T"):r,Ht=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var ke=class{constructor(e,t,s={},n=Ft){this.channel=e,this.event=t,this.payload=s,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var bs;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(bs||(bs={}));var De=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,n,i,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=r.syncDiff(this.state,n,i,o),a())}),this.onJoin((n,i,o)=>{this.channel._trigger("presence",{event:"join",key:n,currentPresences:i,newPresences:o})}),this.onLeave((n,i,o)=>{this.channel._trigger("presence",{event:"leave",key:n,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,n){let i=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(i,(l,u)=>{o[l]||(c[l]=u)}),this.map(o,(l,u)=>{let d=i[l];if(d){let f=u.map(S=>S.presence_ref),p=d.map(S=>S.presence_ref),w=u.filter(S=>p.indexOf(S.presence_ref)<0),k=d.filter(S=>f.indexOf(S.presence_ref)<0);w.length>0&&(a[l]=w),k.length>0&&(c[l]=k)}else a[l]=u}),this.syncDiff(i,{joins:a,leaves:c},s,n)}static syncDiff(e,t,s,n){let{joins:i,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),n||(n=()=>{}),this.map(i,(a,c)=>{var l;let u=(l=e[a])!==null&&l!==void 0?l:[];if(e[a]=this.cloneDeep(c),u.length>0){let d=e[a].map(p=>p.presence_ref),f=u.filter(p=>d.indexOf(p.presence_ref)<0);e[a].unshift(...f)}s(a,u,c)}),this.map(o,(a,c)=>{let l=e[a];if(!l)return;let u=c.map(d=>d.presence_ref);l=l.filter(d=>u.indexOf(d.presence_ref)<0),e[a]=l,n(a,l,c),l.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let n=e[s];return"metas"in n?t[s]=n.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):t[s]=n,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 ks;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(ks||(ks={}));var Ss;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(Ss||(Ss={}));var Es;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Es||(Es={}));var Me=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=H.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 ke(this,z.join,this.params,this.timeout),this.rejoinTimer=new be(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=H.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=H.closed,this.socket._remove(this)}),this._onError(n=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,n),this.state=H.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=H.errored,this.rejoinTimer.scheduleTimeout())}),this._on(z.reply,{},(n,i)=>{this._trigger(this._replyEventName(i),n)}),this.presence=new De(this),this.broadcastEndpointURL=Ht(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,n;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:i,presence:o,private:a}}=this.params;this._onError(u=>e&&e("CHANNEL_ERROR",u)),this._onClose(()=>e&&e("CLOSED"));let c={},l={broadcast:i,presence:o,postgres_changes:(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(u=>u.filter))!==null&&n!==void 0?n:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:l},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:u})=>{var d;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),u===void 0){e&&e("SUBSCRIBED");return}else{let f=this.bindings.postgres_changes,p=(d=f?.length)!==null&&d!==void 0?d:0,w=[];for(let k=0;k<p;k++){let S=f[k],{filter:{event:O,schema:h,table:m,filter:R}}=S,L=u&&u[k];if(L&&L.event===O&&L.schema===h&&L.table===m&&L.filter===R)w.push(Object.assign(Object.assign({},S),{id:L.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=w,e&&e("SUBSCRIBED");return}}).receive("error",u=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,n;if(!this._canPush()&&e.type==="broadcast"){let{event:i,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:i,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=c.body)===null||n===void 0?void 0:n.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,c;let l=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),l.receive("ok",()=>i("ok")),l.receive("error",()=>i("error")),l.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=H.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(z.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let n=new ke(this,z.leave,{},e);n.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),n.send(),this._canPush()||n.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(i),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new ke(this,e,t,s);return this._canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var n,i;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:l,join:u}=z;if(s&&[a,c,l,u].indexOf(o)>=0&&s!==this._joinRef())return;let f=this._onMessage(o,t,s);if(t&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(n=this.bindings.postgres_changes)===null||n===void 0||n.filter(p=>{var w,k,S;return((w=p.filter)===null||w===void 0?void 0:w.event)==="*"||((S=(k=p.filter)===null||k===void 0?void 0:k.event)===null||S===void 0?void 0:S.toLocaleLowerCase())===o}).map(p=>p.callback(f,s)):(i=this.bindings[o])===null||i===void 0||i.filter(p=>{var w,k,S,O,h,m;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){let R=p.id,L=(w=p.filter)===null||w===void 0?void 0:w.event;return R&&((k=t.ids)===null||k===void 0?void 0:k.includes(R))&&(L==="*"||L?.toLocaleLowerCase()===((S=t.data)===null||S===void 0?void 0:S.type.toLocaleLowerCase()))}else{let R=(h=(O=p?.filter)===null||O===void 0?void 0:O.event)===null||h===void 0?void 0:h.toLocaleLowerCase();return R==="*"||R===((m=t?.event)===null||m===void 0?void 0:m.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof f=="object"&&"ids"in f){let w=f.data,{schema:k,table:S,commit_timestamp:O,type:h,errors:m}=w;f=Object.assign(Object.assign({},{schema:k,table:S,commit_timestamp:O,eventType:h,new:{},old:{},errors:m}),this._getPayloadRecords(w))}p.callback(f,s)})}_isClosed(){return this.state===H.closed}_isJoined(){return this.state===H.joined}_isJoining(){return this.state===H.joining}_isLeaving(){return this.state===H.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let n=e.toLocaleLowerCase(),i={type:n,filter:t,callback:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(n=>{var i;return!(((i=n.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===s&&r.isEqual(n.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(z.close,{},e)}_onError(e){this._on(z.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=H.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=vs(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=vs(e.columns,e.old_record)),t}};var Zn=()=>{},ei=typeof WebSocket<"u",Ne=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=cr,this.params={},this.timeout=Ft,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Zn,this.conn=null,this.sendBuffer=[],this.serializer=new lt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=i=>{let o;return i?o=i:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(fe(),we)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${qt.websocket}`,this.httpEndpoint=Ht(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 n=(s=t?.params)===null||s===void 0?void 0:s.apikey;n&&(this.accessToken=n,this.apiKey=n),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=t?.encode?t.encode:(i,o)=>o(JSON.stringify(i)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new be(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(ei){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Ts(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>qs(fr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case ve.connecting:return pe.Connecting;case ve.open:return pe.Open;case ve.closing:return pe.Closing;default:return pe.Closed}}isConnected(){return this.connectionState()===pe.Open}channel(e,t={config:{}}){let s=new Me(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:n,ref:i}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${s} (${i})`,n),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(z.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:lr}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:n,payload:i,ref:o}=t;(o&&o===this.pendingHeartbeatRef||n===i?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${s} ${n} ${o&&"("+o+")"||""}`,i),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(n,i,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(z.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",n=new URLSearchParams(t);return`${e}${s}${n}`}_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(ur,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Ts=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=ve.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var qe=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function U(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Wt=class extends qe{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},ut=class extends qe{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var ti=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},Bt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(fe(),we)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},pr=()=>ti(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(fe(),we))).Response:Response});var Fe=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},As=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),si=(r,e)=>Fe(void 0,void 0,void 0,function*(){let t=yield pr();r instanceof t?r.json().then(s=>{e(new Wt(As(s),r.status||500))}).catch(s=>{e(new ut(As(s),s))}):e(new ut(As(r),r))}),ri=(r,e,t,s)=>{let n={method:r,headers:e?.headers||{}};return r==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),t))};function zt(r,e,t,s,n,i){return Fe(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,ri(e,s,n,i)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>si(c,a))})})}function dt(r,e,t,s){return Fe(this,void 0,void 0,function*(){return zt(r,"GET",e,t,s)})}function se(r,e,t,s,n){return Fe(this,void 0,void 0,function*(){return zt(r,"POST",e,s,n,t)})}function gr(r,e,t,s,n){return Fe(this,void 0,void 0,function*(){return zt(r,"PUT",e,s,n,t)})}function Gt(r,e,t,s,n){return Fe(this,void 0,void 0,function*(){return zt(r,"DELETE",e,s,n,t)})}var J=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},ni={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},mr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ht=class{constructor(e,t={},s,n){this.url=e,this.headers=t,this.bucketId=s,this.fetch=Bt(n)}uploadOrUpdate(e,t,s,n){return J(this,void 0,void 0,function*(){try{let i,o=Object.assign(Object.assign({},mr),n),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),i.append("",s)):typeof FormData<"u"&&s instanceof FormData?(i=s,i.append("cacheControl",o.cacheControl)):(i=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),l=this._getFinalPath(c),u=yield this.fetch(`${this.url}/object/${l}`,Object.assign({method:e,body:i,headers:a},o?.duplex?{duplex:o.duplex}:{})),d=yield u.json();return u.ok?{data:{path:c,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(i){if(U(i))return{data:null,error:i};throw i}})}upload(e,t,s){return J(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,n){return J(this,void 0,void 0,function*(){let i=this._removeEmptyFolders(e),o=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,l=Object.assign({upsert:mr.upsert},n),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(l.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",l.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",l.cacheControl)):(c=s,u["cache-control"]=`max-age=${l.cacheControl}`,u["content-type"]=l.contentType);let d=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:u}),f=yield d.json();return d.ok?{data:{path:i,fullPath:f.Key},error:null}:{data:null,error:f}}catch(c){if(U(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return J(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),n=Object.assign({},this.headers);t?.upsert&&(n["x-upsert"]="true");let i=yield se(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:n}),o=new URL(this.url+i.url),a=o.searchParams.get("token");if(!a)throw new qe("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}})}update(e,t,s){return J(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return J(this,void 0,void 0,function*(){try{return{data:yield se(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}copy(e,t,s){return J(this,void 0,void 0,function*(){try{return{data:{path:(yield se(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}createSignedUrl(e,t,s){return J(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e),i=yield se(this.fetch,`${this.url}/object/sign/${n}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}createSignedUrls(e,t,s){return J(this,void 0,void 0,function*(){try{let n=yield se(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:n.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${i}`):null})),error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}download(e,t){return J(this,void 0,void 0,function*(){let n=typeof t?.transform<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString(t?.transform||{}),o=i?`?${i}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield dt(this.fetch,`${this.url}/${n}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(U(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),n=[],i=t?.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&n.push(i);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&n.push(c);let l=n.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${l}`)}}}remove(e){return J(this,void 0,void 0,function*(){try{return{data:yield Gt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}list(e,t,s){return J(this,void 0,void 0,function*(){try{let n=Object.assign(Object.assign(Object.assign({},ni),t),{prefix:e||""});return{data:yield se(this.fetch,`${this.url}/object/list/${this.bucketId}`,n,{headers:this.headers},s),error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}})}_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 _r="2.6.0";var yr={"X-Client-Info":`storage-js/${_r}`};var He=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},ft=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},yr),t),this.fetch=Bt(s)}listBuckets(){return He(this,void 0,void 0,function*(){try{return{data:yield dt(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}})}getBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield dt(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return He(this,void 0,void 0,function*(){try{return{data:yield se(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return He(this,void 0,void 0,function*(){try{return{data:yield gr(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(U(s))return{data:null,error:s};throw s}})}emptyBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield se(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}deleteBucket(e){return He(this,void 0,void 0,function*(){try{return{data:yield Gt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(U(t))return{data:null,error:t};throw t}})}};var pt=class extends ft{constructor(e,t={},s){super(e,t,s)}from(e){return new ht(this.url,this.headers,e,this.fetch)}};var wr="2.44.4";var gt="";typeof Deno<"u"?gt="deno":typeof document<"u"?gt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?gt="react-native":gt="node";var ii={"X-Client-Info":`supabase-js-${gt}/${wr}`},vr={headers:ii},br={schema:"public"},kr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Sr={};fe();var oi=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},ai=r=>{let e;return r?e=r:typeof fetch>"u"?e=as:e=fetch,(...t)=>e(...t)},ci=()=>typeof Headers>"u"?cs:Headers,Er=(r,e,t)=>{let s=ai(t),n=ci();return(i,o)=>oi(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,l=new n(o?.headers);return l.has("apikey")||l.set("apikey",r),l.has("Authorization")||l.set("Authorization",`Bearer ${c}`),s(i,Object.assign(Object.assign({},o),{headers:l}))})};function Tr(r){return r.replace(/\/$/,"")}function Ar(r,e){let{db:t,auth:s,realtime:n,global:i}=r,{db:o,auth:a,realtime:c,global:l}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),n),global:Object.assign(Object.assign({},l),i)}}var Jt="2.64.4";var Cr="http://localhost:9999",xr="supabase.auth.token";var Pr={"X-Client-Info":`gotrue-js/${Jt}`},Cs=10;var mt="X-Supabase-Api-Version",xs={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Rr(r){return Math.round(Date.now()/1e3)+r}function Or(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}var V=()=>typeof document<"u",Se={tested:!1,writable:!1},ge=()=>{if(!V())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Se.tested)return Se.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Se.tested=!0,Se.writable=!0}catch{Se.tested=!0,Se.writable=!1}return Se.writable};function Vt(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return t.searchParams.forEach((s,n)=>{e[n]=s}),e}var Kt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(fe(),we)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Ir=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",Ps=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},yt=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Yt=async(r,e)=>{await r.removeItem(e)};function li(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,n,i,o,a,c,l,u=0;for(r=r.replace("-","+").replace("_","/");u<r.length;)o=e.indexOf(r.charAt(u++)),a=e.indexOf(r.charAt(u++)),c=e.indexOf(r.charAt(u++)),l=e.indexOf(r.charAt(u++)),s=o<<2|a>>4,n=(a&15)<<4|c>>2,i=(c&3)<<6|l,t=t+String.fromCharCode(s),c!=64&&n!=0&&(t=t+String.fromCharCode(n)),l!=64&&i!=0&&(t=t+String.fromCharCode(i));return t}var _t=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};_t.promiseConstructor=Promise;function Rs(r){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=r.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let s=t[1];return JSON.parse(li(s))}async function Lr(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function jr(r,e){return new Promise((s,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await r(i);if(!e(i,null,o)){s(o);return}}catch(o){if(!e(i,o)){n(o);return}}})()})}function ui(r){return("0"+r.toString(16)).substr(-2)}function di(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,n="";for(let i=0;i<56;i++)n+=t.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,ui).join("")}async function hi(r){let t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(s);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}function fi(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function pi(r){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."),r;let t=await hi(r);return fi(t)}async function Ee(r,e,t=!1){let s=di(),n=s;t&&(n+="/PASSWORD_RECOVERY"),await Ps(r,`${e}-code-verifier`,n);let i=await pi(s);return[i,s===i?"plain":"s256"]}var gi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function $r(r){let e=r.headers.get(mt);if(!e||!e.match(gi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var wt=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function E(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Xt=class extends wt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function Ur(r){return E(r)&&r.name==="AuthApiError"}var We=class extends wt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ae=class extends wt{constructor(e,t,s,n){super(e,s,n),this.name=t,this.status=s}},re=class extends ae{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Be=class extends ae{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Te=class extends ae{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Ae=class extends ae{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}}},vt=class extends ae{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 ae{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Qt(r){return E(r)&&r.name==="AuthRetryableFetchError"}var bt=class extends ae{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var mi=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(r);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(r,s[n])&&(t[s[n]]=r[s[n]]);return t},Ce=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),_i=[502,503,504];async function Dr(r){var e;if(!Ir(r))throw new ze(Ce(r),0);if(_i.includes(r.status))throw new ze(Ce(r),r.status);let t;try{t=await r.json()}catch(i){throw new We(Ce(i),i)}let s,n=$r(r);if(n&&n.getTime()>=xs["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new bt(Ce(t),r.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((i,o)=>i&&typeof o=="string",!0))throw new bt(Ce(t),r.status,t.weak_password.reasons);throw new Xt(Ce(t),r.status||500,s)}var yi=(r,e,t,s)=>{let n={method:r,headers:e?.headers||{}};return r==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),t))};async function T(r,e,t,s){var n;let i=Object.assign({},s?.headers);i[mt]||(i[mt]=xs["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);let o=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await wi(r,e,t+a,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function wi(r,e,t,s,n,i){let o=yi(e,s,n,i),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new ze(Ce(c),0)}if(a.ok||await Dr(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await Dr(c)}}function ce(r){var e;let t=null;vi(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=Rr(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function Os(r){let e=ce(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=r.weak_password),e}function ne(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function Mr(r){return{data:r,error:null}}function Nr(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:n,verification_type:i}=r,o=mi(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:n,verification_type:i},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function qr(r){return r}function vi(r){return r.access_token&&r.refresh_token&&r.expires_in}var bi=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(r);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(r,s[n])&&(t[s[n]]=r[s[n]]);return t},xe=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=Kt(s),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(s){if(E(s))return{data:null,error:s};throw s}}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:ne})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=bi(e,["options"]),n=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await T(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Nr,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:ne})}catch(t){if(E(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,n,i,o,a,c;try{let l={nextPage:null,lastPage:0,total:0},u=await T(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:qr});if(u.error)throw u.error;let d=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(w=>{let k=parseInt(w.split(";")[0].split("=")[1].substring(0,1)),S=JSON.parse(w.split(";")[1].split("=")[1]);l[`${S}Page`]=k}),l.total=parseInt(f)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(E(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){try{return await T(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ne})}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:ne})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}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:ne})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await T(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:t,error:s}}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 Fr={getItem:r=>ge()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{ge()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{ge()&&globalThis.localStorage.removeItem(r)}};function Is(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function Hr(){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 Pe={debug:!!(globalThis&&ge()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},kt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Zt=class extends kt{};async function Ls(r,e,t){Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async n=>{if(n){Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,n.name);try{return await t()}finally{Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,n.name)}}else{if(e===0)throw Pe.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Zt(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Pe.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}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()}})}Hr();var ki={url:Cr,storageKey:xr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Pr,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},St=30*1e3,Wr=3;async function Br(r,e,t){return await t()}var Re=class r{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=r.nextInstanceID,r.nextInstanceID+=1,this.instanceID>0&&V()&&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 n=Object.assign(Object.assign({},ki),e);if(this.logDebugMessages=!!n.debug,typeof n.debug=="function"&&(this.logger=n.debug),this.persistSession=n.persistSession,this.storageKey=n.storageKey,this.autoRefreshToken=n.autoRefreshToken,this.admin=new xe({url:n.url,headers:n.headers,fetch:n.fetch}),this.url=n.url,this.headers=n.headers,this.fetch=Kt(n.fetch),this.lock=n.lock||Br,this.detectSessionInUrl=n.detectSessionInUrl,this.flowType=n.flowType,this.hasCustomAuthorizationHeader=n.hasCustomAuthorizationHeader,n.lock?this.lock=n.lock:V()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Ls:this.lock=Br,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?n.storage?this.storage=n.storage:ge()?this.storage=Fr:(this.memoryStorage={},this.storage=Is(this.memoryStorage)):(this.memoryStorage={},this.storage=Is(this.memoryStorage)),V()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Jt}) ${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=V()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:n,redirectType:i}=t;return this._debug("#_initialize()","detected session in URL",n,"redirect type",i),await this._saveSession(n),setTimeout(async()=>{i==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return E(e)?{error:e}:{error:new We("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,n;try{let i=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:ce}),{data:o,error:a}=i;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(i){if(E(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var t,s,n;try{let i;if("email"in e){let{email:u,password:d,options:f}=e,p=null,w=null;this.flowType==="pkce"&&([p,w]=await Ee(this.storage,this.storageKey)),i=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:u,password:d,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:p,code_challenge_method:w},xform:ce})}else if("phone"in e){let{phone:u,password:d,options:f}=e;i=await T(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:ce})}else throw new Te("You must provide either an email or phone number and a password");let{data:o,error:a}=i;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(i){if(E(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:o,options:a}=e;t=await T(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Os})}else if("phone"in e){let{phone:i,password:o,options:a}=e;t=await T(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Os})}else throw new Te("You must provide either an email or phone number and a password");let{data:s,error:n}=t;return n?{data:{user:null,session:null},error:n}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new Be}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await yt(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(t??"").split("/"),{data:i,error:o}=await T(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:ce});return await Yt(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Be}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:n,access_token:i,nonce:o}=e,a=await T(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:ce}),{data:c,error:l}=a;return l?{data:{user:null,session:null},error:l}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Be}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:l})}catch(t){if(E(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,n,i,o;try{if("email"in e){let{email:a,options:c}=e,l=null,u=null;this.flowType==="pkce"&&([l,u]=await Ee(this.storage,this.storageKey));let{error:d}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:l,code_challenge_method:u},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){let{phone:a,options:c}=e,{data:l,error:u}=await T(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=c?.data)!==null&&n!==void 0?n:{},create_user:(i=c?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:l?.message_id},error:u}}throw new Te("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,s;try{let n,i;"options"in e&&(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.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:i}}),redirectTo:n,xform:ce});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:l,session:c},error:null}}catch(n){if(E(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithSSO(e){var t,s,n;try{let i=null,o=null;return this.flowType==="pkce"&&([i,o]=await Ee(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:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:o}),headers:this.headers,xform:Mr})}catch(i){if(E(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new re;let{error:n}=await T(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:n}})}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:s,type:n,options:i}=e,{error:o}=await T(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:n,options:i}=e,{data:o,error:a}=await T(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new Te("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 s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await yt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,l,u)=>(!o&&l==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,l,u))})}return{data:{session:e},error:null}}let{session:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:n},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:ne}):await this._useSession(async t=>{var s,n,i;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new re}:await T(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:ne})})}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 s=>{let{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new re;let o=n.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await Ee(this.storage,this.storageKey));let{data:l,error:u}=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:c}),jwt:o.access_token,xform:ne});if(u)throw u;return o.user=l.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(E(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return Rs(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 re;let t=Date.now()/1e3,s=t,n=!0,i=null,o=Rs(e.access_token);if(o.exp&&(s=o.exp,n=s<=t),n){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};i=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},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 s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new re;let{session:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:n?{data:{user:n.user,session:n},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(!V())throw new Ae("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Ae("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new vt("Not a valid PKCE flow url.");let t=Vt(window.location.href);if(e){if(!t.code)throw new vt("No code detected.");let{data:h,error:m}=await this._exchangeCodeForSession(t.code);if(m)throw m;let R=new URL(window.location.href);return R.searchParams.delete("code"),window.history.replaceState(window.history.state,"",R.toString()),{data:{session:h.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Ae(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:o,expires_in:a,expires_at:c,token_type:l}=t;if(!i||!a||!o||!l)throw new Ae("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),f=u+d;c&&(f=parseInt(c));let p=f-u;p*1e3<=St&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${d}s`);let w=f-d;u-w>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",w,f,u):u-w<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",w,f,u);let{data:k,error:S}=await this._getUser(i);if(S)throw S;let O={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:d,expires_at:f,refresh_token:o,token_type:l,user:k.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:O,redirectType:t.type},error:null}}catch(t){if(E(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Vt(window.location.href);return!!(V()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Vt(window.location.href),t=await yt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;let{data:n,error:i}=t;if(i)return{error:i};let o=(s=n.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Ur(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Yt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Or(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,n;try{let{data:{session:i},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await Ee(this.storage,this.storageKey,!0));try{return await T(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(E(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(E(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:n}=await this._useSession(async i=>{var o,a,c,l,u;let{data:d,error:f}=i;if(f)throw f;let p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await T(this.fetch,"GET",p,{headers:this.headers,jwt:(u=(l=d.session)===null||l===void 0?void 0:l.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return V()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(E(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,n;let{data:i,error:o}=t;if(o)throw o;return await T(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n: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 s=Date.now();return await jr(async n=>(n>0&&await Lr(200*Math.pow(2,n-1)),this._debug(t,"refreshing attempt",n),await T(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ce})),(n,i)=>{let o=200*Math.pow(2,n);return i&&Qt(i)&&Date.now()+o-s<St})}catch(s){if(this._debug(t,"error",s),E(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),V()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await yt(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}let n=Math.round(Date.now()/1e3),i=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<n+Cs;if(this._debug(t,`session has${i?"":" not"} expired with margin of ${Cs}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Qt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new re;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new _t;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new re;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let a={session:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(n,"error",i),E(i)){let o={session:null,error:i};return Qt(i)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,t,s=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Ps(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Yt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&V()&&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(),St);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/St);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${St}ms, refresh threshold is ${Wr} ticks`),n<=Wr&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof kt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!V()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let n=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[i,o]=await Ee(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(a.toString())}if(s?.queryParams){let i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s?.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:n,error:i}=t;return i?{data:null,error:i}:await T(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.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 s,n;let{data:i,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await T(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((n=a?.totp)===null||n===void 0)&&n.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 s;let{data:n,error:i}=t;if(i)return{data:null,error:i};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:(s=n?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(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 s;let{data:n,error:i}=t;return i?{data:null,error:i}:await T(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(E(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],n=s.filter(i=>i.factor_type==="totp"&&i.status==="verified");return{data:{all:s,totp:n},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:n},error:i}=e;if(i)return{data:null,error:i};if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(n.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=n.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let u=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:u},error:null}}))}};Re.nextInstanceID=0;var Si=Re,js=Si;var es=class extends js{constructor(e){super(e)}};var Ei=function(r,e,t,s){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(d){o(d)}}function c(u){try{l(s.throw(u))}catch(d){o(d)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(r,e||[])).next())})},Et=class{constructor(e,t,s){var n,i,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=Tr(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,l={db:br,realtime:Sr,auth:Object.assign(Object.assign({},kr),{storageKey:c}),global:vr},u=Ar(s??{},l);this.storageKey=(n=u.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=u.global.headers)!==null&&i!==void 0?i:{},this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=Er(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},u.realtime)),this.rest=new or(`${a}/rest/v1`,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new tt(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new pt(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Ei(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:n,storageKey:i,flowType:o,debug:a},c,l){var u;let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new es({url:this.authUrl,headers:Object.assign(Object.assign({},d),c),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:n,flowType:o,debug:a,fetch:l,hasCustomAuthorizationHeader:(u="Authorization"in this.headers)!==null&&u!==void 0?u:!1})}_initRealtimeClient(e){return new Ne(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var zr=(r,e,t)=>new Et(r,e,t);var le={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Ti=r=>{try{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},ts=r=>{let[e,t]=r.split(".");return!e||!t?null:Ti(t)},Ge=r=>{let e=ts(r);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 Ai="https://api.workos.com",Ci=60,Je=(r,e)=>typeof r[e]=="string"?r[e]:void 0,Gr=(r,e,t)=>{let s=ts(r);if(!s)return null;let n=Je(s,"urn:wispr:user_external_id")??Je(s,"sub"),i=t?.email??Je(s,"email"),o=[t?.first_name,t?.last_name].filter(Boolean).join(" ")||void 0,a=typeof s.exp=="number"?s.exp:void 0,c={id:n??"",aud:"authenticated",email:i,app_metadata:{provider:"workos"},user_metadata:o?{full_name:o}:{},created_at:""};return{access_token:r,refresh_token:e,token_type:"bearer",expires_at:a,expires_in:a?Math.max(0,a-Math.floor(Date.now()/1e3)):0,user:c}},xi=async(r,e,t,s)=>{let n=t?.startsWith("https://")?t.replace(/\/$/,""):Ai,i=await fetch(`${n}/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:r,organization_id:s})});if(!i.ok){let o=await i.json().catch(()=>({}));throw new Error(o.error_description||`WorkOS token refresh failed with status ${i.status}`)}return await i.json()},Jr=async(r,e)=>{let t=ts(r);if(!t)throw new Error("Invalid WorkOS access token");let s=Math.floor(Date.now()/1e3),n=typeof t.exp=="number"?t.exp:0,i=Je(t,"client_id");if(n-s<Ci&&i){let c=await xi(e,i,Je(t,"iss"),Je(t,"org_id")),l=Gr(c.access_token,c.refresh_token,c.user);if(!l)throw new Error("WorkOS refresh returned an invalid access token");return l}if(n<=s)throw new Error("WorkOS session expired");let a=Gr(r,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var Ve=class{constructor(){this.sessionData=null;this.supabase=zr(le.supaBaseUrl,le.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||le.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||le.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||le.redirectUri,scopes:"email openid profile"}}),console.log("Signed in with Microsoft")}catch(t){throw console.error("Error signing in with Microsoft:",t),t}}async setSession(e,t){try{let{data:s,error:n}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(n)throw n;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw console.error("Error setting session:",s),s}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,s){let n=new Date;n.setTime(n.getTime()+s*24*60*60*1e3);let i=`expires=${n.toUTCString()}`;document.cookie=`${e}=${t};${i};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,s=e.refresh_token;if(t&&s)try{if(Ge(t)==="workos"){this.sessionData=await Jr(t,s),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,s)}catch(n){throw n}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,n]=t.split("=");return e[s]=n,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e,t){try{let{error:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||le.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,n,i,o){try{if(!i)throw new Error("Please complete the verification");let a=await N.signUpWithCaptcha({email:e,password:t,full_name:s,captcha_token:i,redirect_url:n||le.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,s,n){try{if(!s)throw new Error("Please complete the verification");let i=await N.signInWithCaptcha({email:e,password:t,captcha_token:s,provision:n?.provision??!1,workos_capable:n?.workosCapable||void 0});if(It(i))return{kind:"otp",challenge:i};if(!i.access_token||!i.refresh_token)throw new Error(i.error||"Invalid login credentials");return console.log("Sign in request completed"),{kind:"authenticated",accessToken:i.access_token,refreshToken:i.refresh_token,fullName:[i.first_name,i.last_name].filter(Boolean).join(" ")||void 0,provider:i.provider||void 0}}catch(i){throw console.error("Error signing in with password:",i),i}}async resendVerificationEmail(e,t,s,n){try{if(!s)throw new Error("Please complete the verification");let i=await N.resendVerificationEmailCaptcha({email:e,captcha_token:s,redirect_url:t||le.redirectUri,workos_capable:n?.workosCapable||void 0});return console.log("Verification request completed"),i}catch(i){throw console.error("Error resending verification email:",i),i}}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 ss=null,Vr=(r,e)=>{if(!(r instanceof Error)||r.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:s}=r;return s&&t[s]||e},rs=()=>{ss!==null&&(window.clearInterval(ss),ss=null)};function Ke(){let r=document.querySelector("[otp-verification]");r&&(r.style.display="none"),rs()}function Kr(r){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]")),s=document.querySelector("[otp-email]"),n=document.querySelector("[otp-verify]"),i=document.querySelector("[otp-error]"),o=document.querySelector("[otp-error-message]"),a=document.querySelector("[otp-resend]"),c=document.querySelector("[otp-resend-countdown]"),l=document.querySelector("[otp-resend-seconds]"),u=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")}),i&&(i.style.display="none"),c&&(c.style.display="none"),a&&(a.style.display=""),n&&(n.textContent="Verify",n.style.pointerEvents="",n.removeAttribute("aria-disabled")),rs(),s&&(s.textContent=r.email),e.style.display="block",t[0]?.focus();let d=h=>{i&&(i.style.display="block"),o&&(o.textContent=h)},f=()=>{i&&(i.style.display="none")},p=!1,w=!1,k=h=>{n&&(n.style.pointerEvents=h?"none":"",h?n.setAttribute("aria-disabled","true"):n.removeAttribute("aria-disabled"),n instanceof HTMLButtonElement&&(n.disabled=h),a&&a.style.display!=="none"&&(a.style.pointerEvents=h?"none":"",h?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},S=async()=>{if(p)return;let h=t.map(m=>m.value).join("");if(h.length!==6){d("Please enter all 6 digits.");return}p=!0,k(!0),t.forEach(m=>m.setAttribute("disabled","true")),f();try{await r.onVerify(h),f(),n&&(n.textContent="Verified \u2705")}catch(m){p=!1,k(!1),t.forEach(R=>{R.value="",R.removeAttribute("disabled")}),d(Vr(m,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((h,m)=>{h.oninput=()=>{h.value=h.value.replace(/\D/g,"").slice(0,1),h.value&&m<t.length-1&&t[m+1].focus(),f()},h.onkeydown=R=>{R.key==="Backspace"&&!h.value&&m>0?t[m-1].focus():R.key==="Enter"&&(R.preventDefault(),S())},h.onpaste=R=>{R.preventDefault();let L=(R.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);L.split("").forEach((W,Z)=>{t[Z]&&(t[Z].value=W)});let oe=Math.min(L.length,t.length-1);t[oe]?.focus(),f()}}),n&&(n.onclick=h=>{h.preventDefault(),S()});let O=()=>{let h=30;a&&(a.style.display="none"),c&&(c.style.display="block"),l&&(l.textContent=String(h)),rs(),ss=window.setInterval(()=>{h-=1,l&&(l.textContent=String(h)),h<=0&&(rs(),a&&(a.style.display=""),c&&(c.style.display="none"))},1e3)};a&&(a.onclick=async h=>{if(h.preventDefault(),!(w||a.style.display==="none")){w=!0,t.forEach(m=>{m.value="",m.removeAttribute("disabled")}),t[0]?.focus(),f(),O();try{await r.onResend?.()}catch(m){d(Vr(m,"We couldn't send a new code. Please try again when the timer ends."))}finally{w=!1}}}),u&&(u.onclick=h=>{h.preventDefault(),Ke(),r.onReset?.()})}var Oe=()=>window.hcaptcha,ns=async()=>{let r=Oe();if(!r)throw new Error("Verification system not loaded");let e=await r.execute({async:!0}),t=typeof e=="string"?e:e.response;if(!t)throw new Error("Verification cancelled");return t},Tt=(r,e)=>r instanceof Error?r.message:e,Yr=(r,e)=>r instanceof Q?r.code==="sso_required"?(e.showSso(),!0):r.code==="scim_managed_domain"?(e.showScim(),!0):(r.code==="sign_in_to_continue"&&e.showLogin(),e.showError(r.message),!0):!1,Xr=r=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(s){e={pendingAuthenticationToken:s.pendingAuthenticationToken,email:F(s.email)},r.beforeShow(),Kr({email:e.email,onVerify:async n=>{if(!e)throw Ke(),r.onMissingChallenge(),new Error("Missing OTP challenge");let i=await N.verifyEmailOtp({code:n,pending_authentication_token:e.pendingAuthenticationToken});t(),await r.onAuthenticated(i)},onResend:async()=>{if(!e)throw Ke(),r.onMissingChallenge(),new Error("Missing OTP challenge");let n=await ns();try{await r.client.resendVerificationEmail(e.email,r.redirectUrl,n,{workosCapable:r.isWorkosCapable(e.email)})}finally{Oe()?.reset()}},onReset:()=>{t(),r.onReset()}})}}};var ie=null;function $s(r,e=30,t){ie&&(clearInterval(ie),ie=null);let s=e;r.style.pointerEvents="none",r.textContent=`Resend (${s}s)`,ie=setInterval(()=>{s=s-1,r.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(r.style.pointerEvents="auto",ie&&(clearInterval(ie),ie=null),t&&t())},1e3)}function Qr(){ie&&(clearInterval(ie),ie=null)}var Zr=/^[\p{L}\p{M}\s\-'.]+$/u;function Pi(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":Zr.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 Us(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":Zr.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 en(r,e,t){let s="full-name-match-error",n=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let l=document.getElementById(s);l||(l=document.createElement("div"),l.id=s,l.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",l)),l.textContent=c},i=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(s)?.remove()},o=()=>{let c=Pi(e.value,r.value);c?n(c):i()},a=()=>{let c=Us(e.value,r.value);c?n(c):i()};r.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var tn="password-rejection-error",sn=r=>r instanceof Q?r.passwordRejectionMessage:null,At=r=>{r.classList.remove("error"),document.getElementById(tn)?.remove()},Ds=(r,e)=>{if(At(r),e.length===0)return;r.classList.add("error");let t=document.createElement("div");t.id=tn,t.style.fontSize="0.875rem",t.textContent=e,r.insertAdjacentElement("afterend",t)};var Ri="wisprjam.com",Oi="wispr.ai",Ii="wispr_workos_capable",Li=r=>r.trim().toLowerCase().split("@")[1]??"",nn=r=>{let e=Li(r);return e===Ri||e===Oi},rn=()=>{try{return window.sessionStorage.getItem(Ii)==="true"}catch{return!1}};function on(r,e){let t=new Ve,s="email_input",n=null,i=()=>{n?.clear()},o=document.querySelector("#email-form"),a=document.querySelector("#email-input"),c=document.querySelector("#password-input"),l=document.querySelector("#full-name"),u=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),f=document.querySelector("#microsoft-login"),p=document.querySelector("[email-element]"),w=document.querySelector("[different-provider]"),k=document.querySelector("[different-provider-name]"),S=document.querySelector("[different-provider-reset]"),O=document.querySelector("[email-signup-success]"),h=document.querySelector("[email-signup-error]"),m=document.querySelector("[error-message]"),R=document.querySelector("[verification-email]"),L=document.querySelector("[email-signup-retry]"),oe=document.querySelector("[email-signup-reset]"),W=document.querySelector("[scim-div]"),Z=document.querySelector("[scim-reset]"),D=document.querySelector("[forgot-password]"),me=document.querySelector("[forgot-password-success]"),ue=document.querySelector("[forgot-password-email]"),B=document.querySelector("[unverified-email]"),Ct=document.querySelector("[unverified-email-address]"),K=document.querySelector("[resend-verification-email]"),M=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(u&&u.addEventListener("click",async()=>{try{i(),localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(r)}catch(y){console.error("Error during Google sign-in:",y)}}),d&&d.addEventListener("click",async()=>{try{i(),localStorage.setItem("signin_provider","apple"),await t.signInWithApple(r)}catch(y){console.error("Error during Apple sign-in:",y)}}),f&&f.addEventListener("click",async()=>{try{i(),localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(r)}catch(y){console.error("Error during Microsoft sign-in:",y)}}));let Y=()=>{i(),w&&(w.style.display="none"),O&&(O.style.display="none"),h&&(h.style.display="none"),B&&(B.style.display="none"),W&&(W.style.display="none"),D&&(D.style.display="none"),me&&(me.style.display="none"),Ke();let y=document.querySelector(".gs-hero_form-block");y&&(y.style.display="block"),p&&(p.style.display="flex"),a&&(a.value="",a.removeAttribute("readonly"),a.classList.remove("disabled")),c&&(c.value="",c.style.display="none",c.removeAttribute("required"),At(c)),l&&(l.value="",l.style.display="none",l.removeAttribute("required"));let v=document.querySelector("[captcha-embed]"),P=document.querySelector("#h-captcha-container");v&&(v.style.display="none"),P&&(P.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),s="email_input",a&&a.focus()},de=()=>{p&&(p.style.display="flex"),a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),c&&(c.style.display="block",c.setAttribute("required","true"),c.focus()),l&&(l.style.display="none",l.removeAttribute("required"));let y=document.querySelector("[captcha-embed]"),v=document.querySelector("#h-captcha-container");y&&(y.style.display="block"),v&&(v.style.display="block"),D&&(D.style.display="block",D.onclick=async()=>{let P=a?.value||"",A=D.textContent||"";try{let{hcaptcha:_}=window;if(!_)throw new Error("Verification system not loaded. Please refresh the page.");D.style.pointerEvents="none",D.textContent="Sending...";let{response:g}=await _.execute({async:!0});if(!g)throw new Error("Verification cancelled");await N.requestPasswordReset(P,g),_.reset(),p&&(p.style.display="none"),D&&(D.style.display="none"),me&&(me.style.display="block"),ue&&(ue.textContent=P)}catch(_){console.error("Error sending password reset email:",_),D.textContent=A,D.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),h&&(h.style.display="block",m&&(m.textContent=_ instanceof Error?_.message:"Failed to send reset email"))}}),s="login"},Ye=()=>{a&&(a.setAttribute("readonly","true"),a.classList.add("disabled")),c&&(c.style.display="block",c.setAttribute("required","true"),c.focus()),l&&(l.style.display="block",l.setAttribute("required","true"));let y=document.querySelector("[captcha-embed]"),v=document.querySelector("#h-captcha-container");y&&(y.style.display="block"),v&&(v.style.display="block"),s="signup"},_e=()=>{let y=document.querySelector(".gs-hero_form-block");y&&(y.style.display="none"),W&&(W.style.display="block"),Z&&(Z.onclick=()=>{W&&(W.style.display="none"),y&&(y.style.display="block"),Y()})},Ie=y=>{i();let v=zs(y);p&&(p.style.display="none"),w&&(w.style.display="block"),k&&(k.textContent=v),S&&(S.onclick=()=>{w&&(w.style.display="none"),Y()}),s="oauth_user"};n=Xr({client:t,redirectUrl:r,isWorkosCapable:()=>!0,beforeShow:()=>{p&&(p.style.display="none"),B&&(B.style.display="none")},onAuthenticated:async y=>{i(),t.setCookies(y.access_token,y.refresh_token),localStorage.setItem("email",y.email),localStorage.setItem("user_id",y.user_id),localStorage.setItem("signin_provider","email");let v=[y.first_name,y.last_name].filter(Boolean).join(" ")||void 0;e?.onLoginSuccess?await e.onLoginSuccess(y.access_token,y.refresh_token,v):window.location.href=r},onMissingChallenge:de,onReset:Y});let G=y=>{p&&(p.style.display="none"),B&&(B.style.display="block"),Ct&&(Ct.textContent=y),K&&(K.onclick=async()=>{let v=K.textContent||"";try{let P=await ns();await t.resendVerificationEmail(y,r,P),K.textContent="Verification email resent! \u2705",K.style.textDecoration="none"}catch(P){K.textContent=v,h&&(h.style.display="block"),m&&(m.textContent=Tt(P,"Unable to resend verification."))}finally{Oe()?.reset()}}),M&&(M.onclick=()=>{B&&(B.style.display="none"),Y()}),s="unverified_email"},X=y=>Yr(y,{showSso:()=>Ie("workos"),showScim:_e,showLogin:de,showError:v=>{h&&(h.style.display="block"),m&&(m.textContent=v)}}),he=async(y,v)=>{let P=v.value;v.classList.add("loading"),v.value="";try{let A=await N.checkUserStatus(y);v.classList.remove("loading"),v.value=P,!A.exists&&A.scim_managed?_e():A.enforce_sso?Ie("workos"):A.exists&&A.provider&&A.provider!=="email"&&A.provider!=="workos"?Ie(A.provider):A.exists&&A.provider==="workos"?de():A.exists&&A.provider==="email"&&!A.verified?G(y):A.exists&&A.provider==="email"?de():Ye()}catch(A){console.error("Error checking user status:",A),v.classList.remove("loading"),v.value=P,X(A)||Ye()}},Xe=async(y,v,P,A)=>{if(!v||v.length<8){h&&(h.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}let _=window.hcaptcha?.getResponse()||"";if(!_){h&&(h.style.display="block",m&&(m.textContent="Please complete the verification"));return}P.classList.add("loading"),P.value="";try{if(e?.mcpLoginState){let C=await N.signInWithEmail({email:y,password:v,mcp_login_state:e.mcpLoginState,workos_capable:rn()});if(!C.redirect_url)throw new Error(C.error||"Unable to continue connector login. Please try again.");x("desktop_login_complete_success",{method:"email",mcp:!0}),window.location.href=C.redirect_url;return}let g=rn(),b=await t.signInWithPassword(y,v,_,{workosCapable:g,provision:!1});if(b.kind==="otp"){if(!g)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let C={pendingAuthenticationToken:b.challenge.pending_authentication_token,email:F(b.challenge.email||y)};Oe()?.reset(),P.classList.remove("loading"),P.value=A,n?.show(C);return}t.setCookies(b.accessToken,b.refreshToken),localStorage.setItem("email",y),e?.onLoginSuccess?await e.onLoginSuccess(b.accessToken,b.refreshToken,b.fullName):window.location.href=r}catch(g){window.hcaptcha&&window.hcaptcha.reset(),P.classList.remove("loading"),P.value=A,!X(g)&&h&&(h.style.display="block",m&&(m.textContent=Tt(g,"Unable to sign in. Please try again.")))}},Le=async(y,v,P,A,_)=>{if(!v||v.length<8){h&&(h.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}if(v.trim().toLowerCase()===y.trim().toLowerCase()){Ds(c,"Password can't be the same as your email address.");return}if(!P||P.trim().length<2){h&&(h.style.display="block",m&&(m.textContent="Please enter your full name"));return}let g=Us(P,v);if(g){h&&(h.style.display="block",m&&(m.textContent=g));return}let b=window.hcaptcha?.getResponse()||"";if(!b){h&&(h.style.display="block",m&&(m.textContent="Please complete the verification"));return}A.classList.add("loading"),A.value="";try{let C=await t.signUpWithPassword(y,v,P,r,b,{workosCapable:!0});if(window.hcaptcha&&window.hcaptcha.reset(),A.classList.remove("loading"),A.value=_,p&&(p.style.display="none"),h&&(h.style.display="none"),It(C)){let $={pendingAuthenticationToken:C.pending_authentication_token,email:F(C.email||y)};n?.show($);return}O&&(O.style.display="block"),R&&(R.textContent=y),L&&($s(L,30),L.onclick=async()=>{if(L.style.pointerEvents!=="none")try{let $=await ns();await t.resendVerificationEmail(y,r,$,{workosCapable:!0}),$s(L,30)}catch($){h&&(h.style.display="block"),m&&(m.textContent=Tt($,"Unable to resend verification. Please try again."))}finally{Oe()?.reset()}}),oe&&(oe.onclick=()=>{O&&(O.style.display="none"),Qr(),Y()})}catch(C){A.classList.remove("loading"),A.value=_,Oe()?.reset();let $=sn(C);$&&c?Ds(c,$):!X(C)&&h&&(h.style.display="block",m&&(m.textContent=Tt(C,"Unable to create the account. Please try again.")))}};return o&&c&&l&&(en(c,l,o.querySelector('[type="submit"]')),c.addEventListener("input",()=>At(c))),o&&o.addEventListener("submit",async y=>{y.stopPropagation(),y.preventDefault();let v=F(a?.value||"");a&&(a.value=v);let P=c?.value||"",A=l?.value||"";if(!v||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)){h&&(h.style.display="block",m&&(m.textContent="Please enter a valid email address"));return}h&&(h.style.display="none"),m&&(m.textContent=""),c&&At(c);let g=o.querySelector('[type="submit"]'),b=g?.value||"";localStorage.setItem("signin_provider","email");try{s==="email_input"?await he(v,g):s==="login"?await Xe(v,P,g,b):s==="signup"&&await Le(v,P,A,g,b)}catch(C){console.error("Auth flow error:",C),g&&(g.classList.remove("loading"),g.value=b),h&&(h.style.display="block")}}),{reset:Y}}var ji="wf_first_landing_url";var an=()=>{try{return localStorage.getItem(ji)||void 0}catch{return}};var $i=/google ads|google adservices|adwords/i,Ui=/marketing|advertising/i,ln="JQ2XQxIk",Di="linkedin insight tag",Mi=r=>{let e=r.filter(s=>$i.test(s.name??""));if(e.length>0)return e.every(s=>s.decision===!0)?{ad_user_data:!0,ad_personalization:!0}:e.every(s=>s.decision===!1)?{ad_user_data:!1,ad_personalization:!1}:void 0;let t=r.filter(s=>Ui.test(s.category??""));if(t.length!==0){if(t.some(s=>s.decision===!0))return{ad_user_data:!0,ad_personalization:!0};if(t.every(s=>s.decision===!1))return{ad_user_data:!1,ad_personalization:!1}}},cn=r=>{let e=Mi(r),t=r.filter(i=>i.id===ln),s=t.length?t:r.filter(i=>typeof i.name=="string"&&i.name.trim().toLowerCase()===Di),n=s.length===1?s[0].linkedinConsent:void 0;if(!(!e&&n===void 0))return{...e,...n===void 0?{}:{linkedin_ads_consent:n.given,linkedin_ads_consent_type:n.type}}},un=(r,e)=>{if(typeof r=="boolean")return{given:r,...e==="EXPLICIT"||e==="IMPLICIT"?{type:e}:{}}},Ni=r=>{if(typeof r?.status!="boolean")return;let e={given:r.status},{history:t}=r;if(!Array.isArray(t)||!t.length||t.some(o=>!Number.isFinite(o?.timestamp)))return e;let s=Math.max(...t.map(o=>o.timestamp)),n=t.filter(o=>o.timestamp===s),i=un(r.status,n[0].type);return i?.type&&n.every(o=>o.type===i.type&&o.status===i.given)?i:e},qi=async()=>{try{let{__ucCmp:r,UC_UI:e}=window;if(r?.getConsentDetails){let t=await r.getConsentDetails();return cn(Object.entries(t?.services??{}).map(([s,n])=>({id:s,name:n?.name,category:n?.category,linkedinConsent:un(n?.consent?.given,n?.consent?.type),decision:n?.consent?.type==="EXPLICIT"&&typeof n.consent.given=="boolean"?n.consent.given:void 0})))}if(e?.getServicesBaseInfo)return cn((e.getServicesBaseInfo()??[]).map(t=>{let s=Ni(t.consent);return{id:t?.id,name:t?.name,category:t?.categorySlug,linkedinConsent:s,decision:t?.id===ln?s?.type==="EXPLICIT"?s.given:void 0:t?.consent?.history?.some(n=>n?.type==="EXPLICIT")&&typeof t.consent.status=="boolean"?t.consent.status:void 0}}))}catch{}},dn=()=>{let r=new Promise(e=>{setTimeout(()=>e(void 0),1500)});return Promise.race([qi(),r])};function hn(r){try{let e=r._gcl_aw;if(e){let t;try{t=decodeURIComponent(e)}catch{t=e}let s=t.split(".");if(s.length>=3){let n=s.slice(2).join(".");if(n)return n}}return new URLSearchParams(window.location.search).get("gclid")||void 0}catch{return}}var Ms="https://api.wisprflow.ai",fn="https://wisprflow.ai",Fi="workos_enabled_webflow";window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let r=new Ve,e=document.querySelector("[loading-div]"),t=document.querySelector("[success-div]"),s=document.querySelector("[error-div]"),n=document.querySelector("[error-message-api]"),i=document.querySelector("[signup-card]"),o=document.querySelector("[logo-wrap]"),a=document.querySelector("[ip-blocked-div]"),c=document.querySelector('#email-form [type="submit"]'),l=c?.value??"",u=document.querySelector("#google-login"),d=document.querySelector("#apple-login"),f=document.querySelector("#microsoft-login"),p=document.querySelector("#sso-login"),w=document.querySelector("[sso-login-div]"),k=document.querySelector("#sso-email"),S=document.querySelector("#sso-signup-form"),O=document.querySelector('[sso-login="go-back"]'),h=document.querySelector(".gs-hero_form-block"),m=localStorage.getItem("last_authed_provider");m&&{google:u,apple:d,microsoft:f,sso:p,email:document.querySelector("#email-input")}[m]?.classList.add("last-used");let R=()=>{e&&(e.style.display="block"),t&&(t.style.display="none"),s&&(s.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},L=()=>{let g=document.querySelector("[open-button]")?.getAttribute("href")||"wispr-flow://open";x("desktop_login_auto_launch",{deep_link:g}),window.location.href=g},oe=()=>{let _=localStorage.getItem("signin_provider");_&&localStorage.setItem("last_authed_provider",_),e&&(e.style.display="none"),t&&(t.style.display="block"),s&&(s.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible",L()},W=_=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="block"),n&&(n.textContent=_),i&&(i.style.display="none"),o&&(o.style.display="none"),document.body.style.visibility="visible"},Z=()=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="none"),i&&(i.style.display="none"),o&&(o.style.display="none"),a&&(a.style.display="block"),document.body.style.visibility="visible"},D=null,me=document.querySelector("[retry-button]");me&&me.addEventListener("click",()=>ue());let ue=()=>{e&&(e.style.display="none"),s&&(s.style.display="none"),a&&(a.style.display="none"),i&&(i.style.display="block"),o&&(o.style.display="block"),document.body.style.visibility="visible",c&&(c.classList.remove("loading"),c.value=l),D&&D()},B=async(_,g)=>{try{let[b,C]=Bs(g||" "),$=N.signupUser({access_token:_,first_name:b,last_name:C}),ee=new Promise((je,ye)=>setTimeout(()=>ye(new Error("signup timeout")),4e3));await Promise.race([$,ee])}catch(b){x("signup_sync_error",{error_message:b instanceof Error?b.message:String(b)})}},Ct=()=>{let _=sessionStorage.getItem("wispr_fbclid");return _?`fb.1.${Date.now()}.${_}`:null},K=async(_,g)=>{let b=sessionStorage.getItem("wispr_device_code");if(!b)throw new Error("Device code not found. Please restart authentication from desktop app.");let C=Qe(),$=await dn(),ee=localStorage.getItem("wf_utm_source")||void 0,je=localStorage.getItem("wf_utm_medium")||void 0,ye=localStorage.getItem("wf_utm_campaign")||void 0,xt=await fetch(`${Ms}/device/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${_}`},body:JSON.stringify({device_code:b,access_token:_,refresh_token:g,fbp:C._fbp||void 0,fbc:C._fbc||Ct()||void 0,gclid:hn(C),utm:ee||je||ye?{utm_source:ee,utm_medium:je,utm_campaign:ye}:void 0,first_landing_url:an(),ad_user_data:$?.ad_user_data,ad_personalization:$?.ad_personalization,linkedin_ads_consent:$?.linkedin_ads_consent,linkedin_ads_consent_type:$?.linkedin_ads_consent_type})});if(!xt.ok){let Pt=await xt.json().catch(()=>({}));throw xt.status===403&&Pt?.detail?.code==="enterprise_ip_not_allowed"?new Error("enterprise_ip_not_allowed"):new Error(Pt?.detail?.message||Pt.message||`Server error: ${xt.status}`)}console.log("Device authentication complete"),sessionStorage.removeItem("wispr_device_code"),Ge(_)==="workos"&&r.setCookie("refresh_token",g,30/86400)},M=new URLSearchParams(window.location.search),Y=M.get("device_code"),de=M.get("error"),Ye=M.get("workos_capable");Ye==="true"?sessionStorage.setItem("wispr_workos_capable","true"):Ye==="false"&&sessionStorage.removeItem("wispr_workos_capable");let _e=sessionStorage.getItem("wispr_workos_capable")==="true",Ie=M.get("auto_signin")==="true",is=new URLSearchParams(window.location.hash.slice(1)),G=M.get("access_token")||is.get("access_token"),X=M.get("refresh_token")||is.get("refresh_token"),he=M.get("mcp_login_state");if(!Y&&!G&&!X&&!he&&!sessionStorage.getItem("wispr_device_code")){console.log("No device_code found - redirecting to /get-started"),x("desktop_login_no_device_code"),window.location.href="/get-started";return}if(x("desktop_login_page_view",{auto_signin:Ie,workos_capable:_e}),Y){sessionStorage.setItem("wispr_device_code",Y);let _=M.get("fbclid");_&&sessionStorage.setItem("wispr_fbclid",_);let g=M.get("skip_default_trial"),b=M.get("grant_weekly_bonus");g&&sessionStorage.setItem("wispr_skip_default_trial",g),b&&sessionStorage.setItem("wispr_grant_weekly_bonus",b)}(Y||G||X||de)&&window.history.replaceState({},"","/login");let Xe="wispr_workos_second_hop_attempted";if(G&&X){console.log("OAuth callback detected - handling tokens");let _=Ge(G);if(x("desktop_login_oauth_callback",{provider:localStorage.getItem("signin_provider")??"unknown",token_provider:_}),R(),_==="workos"){sessionStorage.removeItem(Xe);try{r.setCookies(G,X);let g=M.get("email");g&&localStorage.setItem("email",g);let b=M.get("user_id");b&&localStorage.setItem("user_id",b),await B(G,M.get("name")??void 0),await N.applyPromoCodeFromCookie(G),await K(G,X),x("desktop_login_complete_success",{method:"oauth",provider:"workos"}),oe()}catch(g){if(g instanceof Error&&g.message==="enterprise_ip_not_allowed"){x("desktop_login_complete_error",{method:"oauth",provider:"workos",error:"enterprise_ip_not_allowed"}),Z();return}let b=g instanceof Error?g.message:"Failed to complete authentication. Please try again.";x("desktop_login_complete_error",{method:"oauth",provider:"workos",error:b}),console.error("Error completing WorkOS device authentication:",g),W(b)}return}try{let g=G,b=X;try{r.setCookies(G,X),await r.checkAndSetSession(),r.sessionData&&(g=r.sessionData.access_token,b=r.sessionData.refresh_token,r.setCookies(g,b),localStorage.setItem("email",r.sessionData.user.email),r.sessionData.user.id&&localStorage.setItem("user_id",r.sessionData.user.id))}catch{}let C=r.sessionData?.user.email;if(_e&&C&&nn(C)&&localStorage.getItem("signin_provider")==="google"&&!sessionStorage.getItem(Xe)){sessionStorage.setItem(Xe,"true"),x("desktop_login_workos_second_hop",{email_domain:C.split("@")[1]??"unknown"}),window.location.href=`${Ms}/authkit/google/sign_in?source=${fn}`;return}await B(g,r.sessionData?.user.user_metadata?.full_name),await N.applyPromoCodeFromCookie(g),await K(g,b),x("desktop_login_complete_success",{method:"oauth"}),oe()}catch(g){if(g instanceof Error&&g.message==="enterprise_ip_not_allowed"){x("desktop_login_complete_error",{method:"oauth",error:"enterprise_ip_not_allowed"}),Z();return}let b=g instanceof Error?g.message:"Failed to complete authentication. Please try again.";x("desktop_login_complete_error",{method:"oauth",error:b}),console.error("Error completing device authentication:",g),W(b)}return}if(Ie){console.log("Auto-signin enabled - checking existing session"),R();try{if(await r.checkAndSetSession(),r.sessionData&&r.setCookies(r.sessionData.access_token,r.sessionData.refresh_token),r.sessionData?.access_token&&r.sessionData?.refresh_token){console.log("Existing session found - auto-completing authentication"),await B(r.sessionData.access_token,r.sessionData?.user.user_metadata?.full_name),await N.applyPromoCodeFromCookie(r.sessionData.access_token),await K(r.sessionData.access_token,r.sessionData.refresh_token),x("desktop_login_auto_signin_success",{token_provider:Ge(r.sessionData.access_token)}),oe();return}console.log("No existing session - showing login form"),x("desktop_login_auto_signin_no_session"),ue()}catch(_){if(console.error("Auto-signin error:",_),_ instanceof Error&&_.message==="enterprise_ip_not_allowed"){x("desktop_login_auto_signin_error",{error:"enterprise_ip_not_allowed"}),Z();return}let g=_ instanceof Error?_.message:"Auto-signin failed. Please try logging in manually.";x("desktop_login_auto_signin_error",{error:g}),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),ue()}}else he?(x("desktop_login_mcp_entry"),ue()):(x("desktop_login_manual_signout"),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),localStorage.removeItem("email"),localStorage.removeItem("user_id"),localStorage.removeItem("conversion_sent"),localStorage.removeItem("android_waitlist_joined"),localStorage.removeItem("sms_submitted"),sessionStorage.removeItem("referral_status"),ue());let Le=(_,g)=>{console.log(`Redirecting to ${_} OAuth`);let b=window.posthog?.getFeatureFlag?.(Fi)===!0,C=_e&&b;x("desktop_login_oauth_click",{provider:C?"workos":_,idp:_,mcp:!!he,workos_capable:_e,workos_enabled_webflow:b}),localStorage.setItem("signin_provider",_);let $=C?`authkit/${_}/sign_in`:`${_}/sign_in`,ee=`${Ms}/${$}?source=${fn}`;g&&(ee+=`&email=${encodeURIComponent(g)}`);let je=sessionStorage.getItem("wispr_skip_default_trial"),ye=sessionStorage.getItem("wispr_grant_weekly_bonus");je&&(ee+=`&skip_default_trial=${encodeURIComponent(je)}`),ye&&(ee+=`&grant_weekly_bonus=${encodeURIComponent(ye)}`),he&&(ee+=`&mcp_login_state=${encodeURIComponent(he)}`),window.location.href=ee};u&&u.addEventListener("click",()=>{Le("google")}),d&&d.addEventListener("click",()=>{Le("apple")}),f&&f.addEventListener("click",()=>{Le("microsoft")}),p&&(p.style.display="flex",p.addEventListener("click",_=>{_.preventDefault(),w&&(w.style.display="block"),h&&(h.style.display="none"),k?.focus()})),O&&O.addEventListener("click",()=>{w&&(w.style.display="none"),h&&(h.style.display="block"),k&&(k.value="",k.blur())}),S&&S.addEventListener("submit",_=>{_.preventDefault(),_.stopPropagation();let g=F(k?.value||"");g&&Le("sso",g)});let y=async(_,g,b)=>{try{await B(_,b),await N.applyPromoCodeFromCookie(_),await K(_,g)}catch(C){if(C instanceof Error&&C.message==="enterprise_ip_not_allowed"){x("desktop_login_complete_error",{method:"email",error:"enterprise_ip_not_allowed"}),Z();return}let $=C instanceof Error?C.message:"Failed to complete authentication. Please try again.";x("desktop_login_complete_error",{method:"email",error:$}),W($);return}x("desktop_login_complete_success",{method:"email"}),oe()},v=sessionStorage.getItem("wispr_device_code"),P=v?`${window.location.origin}/login?device_code=${v}`:`${window.location.origin}/login`,{reset:A}=on(P,{onLoginSuccess:y,mcpLoginState:he,skipOAuthButtons:!0});D=A,de==="account_unsupported"&&(x("desktop_login_oauth_error",{error:de}),W("This account is not supported. Try signing in with another account.")),console.log("Desktop login page initialized")});})();
|