@tanay-wispr/webflow-package 6.8.13 → 6.8.14
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/signup.js +1 -1
- package/package.json +1 -1
package/dist/signup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var Ei=Object.create;var Et=Object.defineProperty;var Ti=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var Ai=Object.getPrototypeOf,Pi=Object.prototype.hasOwnProperty;var Ri=(r,e)=>()=>(r&&(e=r(r=0)),e);var Q=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ci=(r,e)=>{for(var t in e)Et(r,t,{get:e[t],enumerable:!0})},Qs=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of xi(e))!Pi.call(r,i)&&i!==t&&Et(r,i,{get:()=>e[i],enumerable:!(s=Ti(e,i))||s.enumerable});return r};var Xs=(r,e,t)=>(t=r!=null?Ei(Ai(r)):{},Qs(e||!r||!r.__esModule?Et(t,"default",{value:r,enumerable:!0}):t,r)),Oi=r=>Qs(Et({},"__esModule",{value:!0}),r);var fe={};Ci(fe,{Headers:()=>cs,Request:()=>Fi,Response:()=>Wi,default:()=>as,fetch:()=>Hi});var qi,Ce,Hi,as,cs,Fi,Wi,le=Ri(()=>{"use strict";qi=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")},Ce=qi(),Hi=Ce.fetch,as=Ce.fetch.bind(Ce),cs=Ce.Headers,Fi=Ce.Request,Wi=Ce.Response});var ur=Q(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=Q(Ye=>{"use strict";var dr=Ye&&Ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ye,"__esModule",{value:!0});var Gi=dr((le(),Oi(fe))),zi=dr(ur()),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=Gi.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,i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let u=null,l=null,d=null,f=n.status,p=n.statusText;if(n.ok){if(this.method!=="HEAD"){let C=await n.text();C===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=C:l=JSON.parse(C))}let E=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),w=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");E&&w&&w.length>1&&(d=parseInt(w[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(u={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,d=null,f=406,p="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let E=await n.text();try{u=JSON.parse(E),Array.isArray(u)&&n.status===404&&(l=[],u=null,f=200,p="OK")}catch{n.status===404&&E===""?(f=204,p="No Content"):u={message:E}}if(u&&this.isMaybeSingle&&(!((c=u?.details)===null||c===void 0)&&c.includes("0 rows"))&&(u=null,f=200,p="OK"),u&&this.shouldThrowOnError)throw new zi.default(u)}return{error:u,data:l,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)}};Ye.default=ds});var ps=Q(Qe=>{"use strict";var Ji=Qe&&Qe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Qe,"__esModule",{value:!0});var Ki=Ji(hs()),fs=class extends Ki.default{select(e){let t=!1,s=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).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: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"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:i=s}={}){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:s=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),u=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; 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}};Qe.default=fs});var Lt=Q(Xe=>{"use strict";var Vi=Xe&&Xe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xe,"__esModule",{value:!0});var Yi=Vi(ps()),ms=class extends Yi.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(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).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:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let i=s?`${s}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};Xe.default=ms});var ys=Q(et=>{"use strict";var Qi=et&&et.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(et,"__esModule",{value:!0});var Ze=Qi(Lt()),gs=class{constructor(e,{headers:t={},schema:s,fetch:i}){this.url=e,this.headers=t,this.schema=s,this.fetch=i}select(e,{head:t=!1,count:s}={}){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),s&&(this.headers.Prefer=`count=${s}`),new Ze.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new Ze.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((u,l)=>u.concat(Object.keys(l)),[]);if(c.length>0){let u=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",u.join(","))}}return new Ze.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",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new Ze.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 Ze.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};et.default=gs});var hr=Q(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.version=void 0;It.version="0.0.0-automated"});var fr=Q(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.DEFAULT_HEADERS=void 0;var Xi=hr();jt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Xi.version}`}});var mr=Q(tt=>{"use strict";var pr=tt&&tt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(tt,"__esModule",{value:!0});var Zi=pr(ys()),en=pr(Lt()),tn=fr(),_s=class r{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},tn.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new Zi.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:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||i?(o=s?"HEAD":"GET",Object.entries(t).filter(([l,d])=>d!==void 0).map(([l,d])=>[l,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([l,d])=>{a.searchParams.append(l,d)})):(o="POST",c=t);let u=Object.assign({},this.headers);return n&&(u.Prefer=`count=${n}`),new en.default({method:o,url:a,headers:u,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};tt.default=_s});var br=Q(D=>{"use strict";var st=D&&D.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(D,"__esModule",{value:!0});D.PostgrestBuilder=D.PostgrestTransformBuilder=D.PostgrestFilterBuilder=D.PostgrestQueryBuilder=D.PostgrestClient=void 0;var gr=st(mr());D.PostgrestClient=gr.default;var yr=st(ys());D.PostgrestQueryBuilder=yr.default;var _r=st(Lt());D.PostgrestFilterBuilder=_r.default;var wr=st(ps());D.PostgrestTransformBuilder=wr.default;var vr=st(hs());D.PostgrestBuilder=vr.default;D.default={PostgrestClient:gr.default,PostgrestQueryBuilder:yr.default,PostgrestFilterBuilder:_r.default,PostgrestTransformBuilder:wr.default,PostgrestBuilder:vr.default}});var Cr=Q((zo,Rr)=>{"use strict";Rr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var ss=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var J=(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(()=>J(r,e,t-1),200)};var ze=r=>r.verification_method==="email_otp"&&typeof r.pending_authentication_token=="string"&&r.pending_authentication_token.length>0,O="https://api.wisprflow.ai",K=class extends Error{constructor(t,s,i,n=null){super(i);this.status=t;this.code=s;this.passwordRejectionMessage=n;this.name="AriaAuthError"}},N=r=>r.trim().toLowerCase(),Zs=(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"},Ge=(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."),Li=(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(n=>typeof n=="string"&&n.length>0&&n!==e)??Ge(e,t),Pe=(r,e)=>{let t=Zs(r,e);return new K(e,t,Li(r,t,e),e===400&&typeof r.detail=="string"&&r.detail.length>0?r.detail:null)},Ii=(r,e)=>{let t=Zs(r,e);return new K(e,t,Ge(t,e))},Tt="promo_code",ji=4e3,$i=new Set([200,400,403,404,409,422]),er=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}`},tr=r=>{if(!r)return"";try{return decodeURIComponent(r).trim()}catch{return""}},Ui=()=>{let r=ss()[Tt];if(r===void 0)return"";let e=tr(r);return e||er(Tt),e},Mi=r=>{tr(ss()[Tt])===r&&er(Tt)},Di=r=>r instanceof DOMException&&(r.name==="TimeoutError"||r.name==="AbortError"),Ni=(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",rs=class{static async signupUser(e){try{let t=`${O}/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(`${O}/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(`${O}/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(`${O}/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(`${O}/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=N(e),s=await fetch(`${O}/user_status?email=${encodeURIComponent(t)}`),i=await s.json().catch(()=>({}));if(!s.ok)throw Pe(i,s.status);return i}static async requestPasswordReset(e,t){let s=await fetch(`${O}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:N(e),captcha_token:t})});if(!s.ok){let i=await s.json().catch(()=>({}));throw Pe(i,s.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${O}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:N(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw Pe(s,t.status);return s}static async signInWithCaptcha(e){let t=await fetch(`${O}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:N(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw Pe(s,t.status);return s}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${O}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:N(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw Pe(s,t.status);return s}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new K(422,"invalid_code",Ge("invalid_code",422));let t=await fetch(`${O}/email/verify-email-otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await t.json().catch(()=>({}));if(!t.ok){let i=Ii(s,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new K(t.status,"verification_failed",Ge("verification_failed",t.status))}if(s.provider!=="workos"||!s.access_token||!s.refresh_token||!s.user_id||!s.email)throw new K(t.status,"authentication_failed",Ge("authentication_failed",t.status));return s}static async signInWithEmail(e){let t=await fetch(`${O}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:N(e.email)})}),s=await t.json().catch(()=>({}));if(!t.ok)throw Pe(s,t.status);return s}static async applyPromoCodeFromCookie(e,t=Ui()){if(t)try{let s=await fetch(`${O}/api/v1/promos/campaign/apply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e},body:JSON.stringify({code:t,source:"web"}),signal:AbortSignal.timeout(ji)}),{status:i}=s;if(!$i.has(i)){J("promo_cookie_apply",{outcome:"deferred",status:i});return}if(Mi(t),s.ok){J("promo_cookie_apply",{outcome:"attached",status:i});return}let n=await s.json().catch(()=>({}));J("promo_cookie_apply",{outcome:"rejected",status:i,reason:Ni(n,i)})}catch(s){console.error("Promo cookie apply deferred:",s),J("promo_cookie_apply",Di(s)?{outcome:"deferred",reason:"timeout"}:{outcome:"deferred"})}}static async getSubscriptionStatus(e){return await fetch(`${O}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${O}/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,i){let n=new URLSearchParams({plan:e,custom_redirect:"true"});s&&n.set("currency",s),i?.trim()&&n.set("promo_code",i.trim());let o=`${O}/api/v1/payment/create-checkout-session?${n}`,a=await fetch(o,{method:"POST",headers:{accept:"application/json",Authorization:t}});if(!a.ok&&a.status!==303)throw new Error(`Checkout request failed (${a.status})`);let c=await a.json();if(!c||typeof c.url!="string"||!c.url)throw new Error("Checkout response is missing a URL");return c}static async sendDownloadLink(e,t){return await fetch(`${O}/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(`${O}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${O}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${O}/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 i=new FormData;return i.append("screenshot",e),await fetch(`${O}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:s})}};function is(r){return r==="azure"?"Microsoft":r==="workos"?"SSO":r.charAt(0).toUpperCase()+r.slice(1)}var X=rs;var xt=null,sr=(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},At=()=>{xt!==null&&(window.clearInterval(xt),xt=null)};function he(){let r=document.querySelector("[otp-verification]");r&&(r.style.display="none"),At()}function rr(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]"),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]"),u=document.querySelector("[otp-resend-seconds]"),l=document.querySelector("[otp-reset]");t.forEach(g=>{g.value="",g.removeAttribute("disabled"),g.setAttribute("inputmode","numeric"),g.setAttribute("autocomplete","one-time-code"),g.setAttribute("data-ph-no-capture",""),g.setAttribute("data-1p-ignore",""),g.setAttribute("data-private",""),g.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")),At(),s&&(s.textContent=r.email),e.style.display="block",t[0]?.focus();let d=g=>{n&&(n.style.display="block"),o&&(o.textContent=g)},f=()=>{n&&(n.style.display="none")},p=!1,b=!1,E=g=>{i&&(i.style.pointerEvents=g?"none":"",g?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled"),i instanceof HTMLButtonElement&&(i.disabled=g),a&&a.style.display!=="none"&&(a.style.pointerEvents=g?"none":"",g?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},w=async()=>{if(p)return;let g=t.map(x=>x.value).join("");if(g.length!==6){d("Please enter all 6 digits.");return}p=!0,E(!0),t.forEach(x=>x.setAttribute("disabled","true")),f();try{await r.onVerify(g),f(),i&&(i.textContent="Verified \u2705")}catch(x){p=!1,E(!1),t.forEach(P=>{P.value="",P.removeAttribute("disabled")}),d(sr(x,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((g,x)=>{g.oninput=()=>{g.value=g.value.replace(/\D/g,"").slice(0,1),g.value&&x<t.length-1&&t[x+1].focus(),f()},g.onkeydown=P=>{P.key==="Backspace"&&!g.value&&x>0?t[x-1].focus():P.key==="Enter"&&(P.preventDefault(),w())},g.onpaste=P=>{P.preventDefault();let j=(P.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);j.split("").forEach(($,re)=>{t[re]&&(t[re].value=$)});let V=Math.min(j.length,t.length-1);t[V]?.focus(),f()}}),i&&(i.onclick=g=>{g.preventDefault(),w()});let C=()=>{let g=30;a&&(a.style.display="none"),c&&(c.style.display="block"),u&&(u.textContent=String(g)),At(),xt=window.setInterval(()=>{g-=1,u&&(u.textContent=String(g)),g<=0&&(At(),a&&(a.style.display=""),c&&(c.style.display="none"))},1e3)};a&&(a.onclick=async g=>{if(g.preventDefault(),!(b||a.style.display==="none")){b=!0,t.forEach(x=>{x.value="",x.removeAttribute("disabled")}),t[0]?.focus(),f(),C();try{await r.onResend?.()}catch(x){d(sr(x,"We couldn't send a new code. Please try again when the timer ends."))}finally{b=!1}}}),l&&(l.onclick=g=>{g.preventDefault(),he(),r.onReset?.()})}var M=()=>window.hcaptcha,Je=async()=>{let r=M();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},Re=(r,e)=>r instanceof Error?r.message:e,ns=(r,e)=>r instanceof K?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,os=r=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(s){e={pendingAuthenticationToken:s.pendingAuthenticationToken,email:N(s.email)},r.beforeShow(),rr({email:e.email,onVerify:async i=>{if(!e)throw he(),r.onMissingChallenge(),new Error("Missing OTP challenge");let n=await X.verifyEmailOtp({code:i,pending_authentication_token:e.pendingAuthenticationToken});t(),await r.onAuthenticated(n)},onResend:async()=>{if(!e)throw he(),r.onMissingChallenge(),new Error("Missing OTP challenge");let i=await Je();try{await r.client.resendVerificationEmail(e.email,r.redirectUrl,i,{workosCapable:r.isWorkosCapable(e.email)})}finally{M()?.reset()}},onReset:()=>{t(),r.onReset()}})}}};var ir=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var nr=()=>{let r=window.location.hash.substring(1),e=new URLSearchParams(r);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var or=()=>{let{access_token:r,refresh_token:e}=nr(),t=new URLSearchParams(window.location.search),s=t.get("access_token")||r,i=t.get("refresh_token")||e;if(!s||!i){let n=ir();s=n.access_token,i=n.refresh_token}return{accessToken:s,refreshToken:i}};var ar=["access_token","refresh_token","email","user_id","name"],cr=({includeError:r=!1}={})=>{let e=new URL(window.location.href),t=r?[...ar,"error"]:ar;if(t.some(s=>e.searchParams.has(s))){for(let s of t)e.searchParams.delete(s);window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`)}};var lr=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(le(),fe)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var Ke=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},Pt=class extends Ke{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Rt=class extends Ke{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Ct=class extends Ke{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Ot;(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"})(Ot||(Ot={}));var Bi=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(d){o(d)}}function c(l){try{u(s.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},Ve=class{constructor(e,{headers:t={},customFetch:s,region:i=Ot.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=lr(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Bi(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 u;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",u=o):typeof o=="string"?(a["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(a["Content-Type"]="application/json",u=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:u}).catch(b=>{throw new Pt(b)}),d=l.headers.get("x-relay-error");if(d&&d==="true")throw new Rt(l);if(!l.ok)throw new Ct(l);let f=((s=l.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),p;return f==="application/json"?p=yield l.json():f==="application/octet-stream"?p=yield l.blob():f==="text/event-stream"?p=l:f==="multipart/form-data"?p=yield l.formData():p=yield l.text(),{data:p,error:null}}catch(i){return{data:null,error:i}}})}};var kr=Xs(br(),1),{PostgrestClient:Sr,PostgrestQueryBuilder:Ao,PostgrestFilterBuilder:Po,PostgrestTransformBuilder:Ro,PostgrestBuilder:Co}=kr.default;var Er="2.10.2";var Tr={"X-Client-Info":`realtime-js/${Er}`},xr="1.0.0",Ut=1e4,Ar=1e3,pe;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(pe||(pe={}));var q;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(q||(q={}));var F;(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"})(F||(F={}));var $t;(function(r){r.websocket="websocket"})($t||($t={}));var ue;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(ue||(ue={}));var rt=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 i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+i));o=o+i;let c=s.decode(e.slice(o,o+n));o=o+n;let u=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:u}}};var me=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 R;(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"})(R||(R={}));var vs=(r,e,t={})=>{var s;let i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=sn(o,r,e,i),n),{})},sn=(r,e,t,s)=>{let i=e.find(a=>a.name===r),n=i?.type,o=t[r];return n&&!s.includes(n)?Pr(n,o):ws(o)},Pr=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return an(e,t)}switch(r){case R.bool:return rn(e);case R.float4:case R.float8:case R.int2:case R.int4:case R.int8:case R.numeric:case R.oid:return nn(e);case R.json:case R.jsonb:return on(e);case R.timestamp:return cn(e);case R.abstime:case R.date:case R.daterange:case R.int4range:case R.int8range:case R.money:case R.reltime:case R.text:case R.time:case R.timestamptz:case R.timetz:case R.tsrange:case R.tstzrange:return ws(e);default:return ws(e)}},ws=r=>r,rn=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},nn=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},on=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},an=(r,e)=>{if(typeof r!="string")return r;let t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let n,o=r.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Pr(e,a))}return r},cn=r=>typeof r=="string"?r.replace(" ","T"):r,Mt=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var ge=class{constructor(e,t,s={},i=Ut){this.channel=e,this.event=t,this.payload=s,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 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 Oe=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,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=r.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,s,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(u,l)=>{o[u]||(c[u]=l)}),this.map(o,(u,l)=>{let d=n[u];if(d){let f=l.map(w=>w.presence_ref),p=d.map(w=>w.presence_ref),b=l.filter(w=>p.indexOf(w.presence_ref)<0),E=d.filter(w=>f.indexOf(w.presence_ref)<0);b.length>0&&(a[u]=b),E.length>0&&(c[u]=E)}else a[u]=l}),this.syncDiff(n,{joins:a,leaves:c},s,i)}static syncDiff(e,t,s,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var u;let l=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(c),l.length>0){let d=e[a].map(p=>p.presence_ref),f=l.filter(p=>d.indexOf(p.presence_ref)<0);e[a].unshift(...f)}s(a,l,c)}),this.map(o,(a,c)=>{let u=e[a];if(!u)return;let l=c.map(d=>d.presence_ref);u=u.filter(d=>l.indexOf(d.presence_ref)<0),e[a]=u,i(a,u,c),u.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 i=e[s];return"metas"in i?t[s]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=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 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 Le=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=q.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 ge(this,F.join,this.params,this.timeout),this.rejoinTimer=new me(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=q.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=q.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=q.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=q.errored,this.rejoinTimer.scheduleTimeout())}),this._on(F.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new Oe(this),this.broadcastEndpointURL=Mt(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,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(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},u={broadcast:n,presence:o,postgres_changes:(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:u},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var d;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let f=this.bindings.postgres_changes,p=(d=f?.length)!==null&&d!==void 0?d:0,b=[];for(let E=0;E<p;E++){let w=f[E],{filter:{event:C,schema:g,table:x,filter:P}}=w,j=l&&l[E];if(j&&j.event===C&&j.schema===g&&j.table===x&&j.filter===P)b.push(Object.assign(Object.assign({},w),{id:j.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=b,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,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,(s=t.timeout)!==null&&s!==void 0?s: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 u=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"),u.receive("ok",()=>n("ok")),u.receive("error",()=>n("error")),u.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=q.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(F.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let i=new ge(this,F.leave,{},e);i.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,s){let i=new AbortController,n=setTimeout(()=>i.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new ge(this,e,t,s);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:u,join:l}=F;if(s&&[a,c,u,l].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)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(p=>{var b,E,w;return((b=p.filter)===null||b===void 0?void 0:b.event)==="*"||((w=(E=p.filter)===null||E===void 0?void 0:E.event)===null||w===void 0?void 0:w.toLocaleLowerCase())===o}).map(p=>p.callback(f,s)):(n=this.bindings[o])===null||n===void 0||n.filter(p=>{var b,E,w,C,g,x;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){let P=p.id,j=(b=p.filter)===null||b===void 0?void 0:b.event;return P&&((E=t.ids)===null||E===void 0?void 0:E.includes(P))&&(j==="*"||j?.toLocaleLowerCase()===((w=t.data)===null||w===void 0?void 0:w.type.toLocaleLowerCase()))}else{let P=(g=(C=p?.filter)===null||C===void 0?void 0:C.event)===null||g===void 0?void 0:g.toLocaleLowerCase();return P==="*"||P===((x=t?.event)===null||x===void 0?void 0:x.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof f=="object"&&"ids"in f){let b=f.data,{schema:E,table:w,commit_timestamp:C,type:g,errors:x}=b;f=Object.assign(Object.assign({},{schema:E,table:w,commit_timestamp:C,eventType:g,new:{},old:{},errors:x}),this._getPayloadRecords(b))}p.callback(f,s)})}_isClosed(){return this.state===q.closed}_isJoined(){return this.state===q.joined}_isJoining(){return this.state===q.joining}_isLeaving(){return this.state===q.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:s};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&r.isEqual(i.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(F.close,{},e)}_onError(e){this._on(F.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=q.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 un=()=>{},dn=typeof WebSocket<"u",Ie=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Tr,this.params={},this.timeout=Ut,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=un,this.conn=null,this.sendBuffer=[],this.serializer=new rt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(le(),fe)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${$t.websocket}`,this.httpEndpoint=Mt(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=(s=t?.params)===null||s===void 0?void 0:s.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 me(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(dn){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Ts(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Xs(Cr())).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 pe.connecting:return ue.Connecting;case pe.open:return ue.Open;case pe.closing:return ue.Closing;default:return ue.Closed}}isConnected(){return this.connectionState()===ue.Open}channel(e,t={config:{}}){let s=new Le(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,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} ${s} (${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(F.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:xr}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${s} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(s)).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(F.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${s}${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(Ar,"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=pe.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var je=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function I(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Dt=class extends je{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},it=class extends je{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var hn=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(d){o(d)}}function c(l){try{u(s.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},Nt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(le(),fe)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Or=()=>hn(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(le(),fe))).Response:Response});var $e=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(d){o(d)}}function c(l){try{u(s.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},xs=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),fn=(r,e)=>$e(void 0,void 0,void 0,function*(){let t=yield Or();r instanceof t?r.json().then(s=>{e(new Dt(xs(s),r.status||500))}).catch(s=>{e(new it(xs(s),s))}):e(new it(xs(r),r))}),pn=(r,e,t,s)=>{let i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};function qt(r,e,t,s,i,n){return $e(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,pn(e,s,i,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>fn(c,a))})})}function nt(r,e,t,s){return $e(this,void 0,void 0,function*(){return qt(r,"GET",e,t,s)})}function Z(r,e,t,s,i){return $e(this,void 0,void 0,function*(){return qt(r,"POST",e,s,i,t)})}function Lr(r,e,t,s,i){return $e(this,void 0,void 0,function*(){return qt(r,"PUT",e,s,i,t)})}function Ht(r,e,t,s,i){return $e(this,void 0,void 0,function*(){return qt(r,"DELETE",e,s,i,t)})}var B=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(d){o(d)}}function c(l){try{u(s.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},mn={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ir={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ot=class{constructor(e,t={},s,i){this.url=e,this.headers=t,this.bucketId=s,this.fetch=Nt(i)}uploadOrUpdate(e,t,s,i){return B(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Ir),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),u=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),d=yield l.json();return l.ok?{data:{path:c,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(n){if(I(n))return{data:null,error:n};throw n}})}upload(e,t,s){return B(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return B(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,u=Object.assign({upsert:Ir.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",u.cacheControl)):(c=s,l["cache-control"]=`max-age=${u.cacheControl}`,l["content-type"]=u.contentType);let d=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),f=yield d.json();return d.ok?{data:{path:n,fullPath:f.Key},error:null}:{data:null,error:f}}catch(c){if(I(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return B(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield Z(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new je("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(I(s))return{data:null,error:s};throw s}})}update(e,t,s){return B(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return B(this,void 0,void 0,function*(){try{return{data:yield Z(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(I(i))return{data:null,error:i};throw i}})}copy(e,t,s){return B(this,void 0,void 0,function*(){try{return{data:{path:(yield Z(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(I(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return B(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield Z(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(I(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return B(this,void 0,void 0,function*(){try{let i=yield Z(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(I(i))return{data:null,error:i};throw i}})}download(e,t){return B(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 nt(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(I(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=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 u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${u}`)}}}remove(e){return B(this,void 0,void 0,function*(){try{return{data:yield Ht(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(I(t))return{data:null,error:t};throw t}})}list(e,t,s){return B(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},mn),t),{prefix:e||""});return{data:yield Z(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if(I(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 jr="2.6.0";var $r={"X-Client-Info":`storage-js/${jr}`};var Ue=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(d){o(d)}}function c(l){try{u(s.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},at=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},$r),t),this.fetch=Nt(s)}listBuckets(){return Ue(this,void 0,void 0,function*(){try{return{data:yield nt(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(I(e))return{data:null,error:e};throw e}})}getBucket(e){return Ue(this,void 0,void 0,function*(){try{return{data:yield nt(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(I(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Ue(this,void 0,void 0,function*(){try{return{data:yield Z(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(I(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return Ue(this,void 0,void 0,function*(){try{return{data:yield Lr(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(I(s))return{data:null,error:s};throw s}})}emptyBucket(e){return Ue(this,void 0,void 0,function*(){try{return{data:yield Z(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(I(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Ue(this,void 0,void 0,function*(){try{return{data:yield Ht(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(I(t))return{data:null,error:t};throw t}})}};var ct=class extends at{constructor(e,t={},s){super(e,t,s)}from(e){return new ot(this.url,this.headers,e,this.fetch)}};var Ur="2.44.4";var lt="";typeof Deno<"u"?lt="deno":typeof document<"u"?lt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?lt="react-native":lt="node";var gn={"X-Client-Info":`supabase-js-${lt}/${Ur}`},Mr={headers:gn},Dr={schema:"public"},Nr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},qr={};le();var yn=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(d){o(d)}}function c(l){try{u(s.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},_n=r=>{let e;return r?e=r:typeof fetch>"u"?e=as:e=fetch,(...t)=>e(...t)},wn=()=>typeof Headers>"u"?cs:Headers,Hr=(r,e,t)=>{let s=_n(t),i=wn();return(n,o)=>yn(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,u=new i(o?.headers);return u.has("apikey")||u.set("apikey",r),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:u}))})};function Fr(r){return r.replace(/\/$/,"")}function Wr(r,e){let{db:t,auth:s,realtime:i,global:n}=r,{db:o,auth:a,realtime:c,global:u}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},u),n)}}var Ft="2.64.4";var Br="http://localhost:9999",Gr="supabase.auth.token";var zr={"X-Client-Info":`gotrue-js/${Ft}`},As=10;var ut="X-Supabase-Api-Version",Ps={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Jr(r){return Math.round(Date.now()/1e3)+r}function Kr(){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 G=()=>typeof document<"u",ye={tested:!1,writable:!1},de=()=>{if(!G())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ye.tested)return ye.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),ye.tested=!0,ye.writable=!0}catch{ye.tested=!0,ye.writable=!1}return ye.writable};function Wt(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((s,i)=>{e[i]=s}),e}var Bt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(le(),fe)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Vr=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",Rs=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},ht=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Gt=async(r,e)=>{await r.removeItem(e)};function vn(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,i,n,o,a,c,u,l=0;for(r=r.replace("-","+").replace("_","/");l<r.length;)o=e.indexOf(r.charAt(l++)),a=e.indexOf(r.charAt(l++)),c=e.indexOf(r.charAt(l++)),u=e.indexOf(r.charAt(l++)),s=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|u,t=t+String.fromCharCode(s),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),u!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var dt=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};dt.promiseConstructor=Promise;function Cs(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(vn(s))}async function Yr(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function Qr(r,e){return new Promise((s,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await r(n);if(!e(n,null,o)){s(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function bn(r){return("0"+r.toString(16)).substr(-2)}function kn(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*s));return i}return crypto.getRandomValues(e),Array.from(e,bn).join("")}async function Sn(r){let t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(s);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function En(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Tn(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 Sn(r);return En(t)}async function _e(r,e,t=!1){let s=kn(),i=s;t&&(i+="/PASSWORD_RECOVERY"),await Rs(r,`${e}-code-verifier`,i);let n=await Tn(s);return[n,s===n?"plain":"s256"]}var xn=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Xr(r){let e=r.headers.get(ut);if(!e||!e.match(xn))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var ft=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function _(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var zt=class extends ft{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function Zr(r){return _(r)&&r.name==="AuthApiError"}var Me=class extends ft{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ie=class extends ft{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}},ee=class extends ie{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},De=class extends ie{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},we=class extends ie{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},ve=class extends ie{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}}},pt=class extends ie{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}}},Ne=class extends ie{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Jt(r){return _(r)&&r.name==="AuthRetryableFetchError"}var mt=class extends ie{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var An=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 i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},be=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Pn=[502,503,504];async function ei(r){var e;if(!Vr(r))throw new Ne(be(r),0);if(Pn.includes(r.status))throw new Ne(be(r),r.status);let t;try{t=await r.json()}catch(n){throw new Me(be(n),n)}let s,i=Xr(r);if(i&&i.getTime()>=Ps["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 mt(be(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((n,o)=>n&&typeof o=="string",!0))throw new mt(be(t),r.status,t.weak_password.reasons);throw new zt(be(t),r.status||500,s)}var Rn=(r,e,t,s)=>{let i={method:r,headers:e?.headers||{}};return r==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),t))};async function k(r,e,t,s){var i;let n=Object.assign({},s?.headers);n[ut]||(n[ut]=Ps["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(i=s?.query)!==null&&i!==void 0?i:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Cn(r,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function Cn(r,e,t,s,i,n){let o=Rn(e,s,i,n),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new Ne(be(c),0)}if(a.ok||await ei(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await ei(c)}}function ne(r){var e;let t=null;On(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=Jr(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=ne(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 te(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function ti(r){return{data:r,error:null}}function si(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=An(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function ri(r){return r}function On(r){return r.access_token&&r.refresh_token&&r.expires_in}var Ln=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 i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},ke=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=Bt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await k(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(_(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await k(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:te})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=Ln(e,["options"]),i=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(i.new_email=s?.newEmail,delete i.newEmail),await k(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:si,redirectTo:t?.redirectTo})}catch(t){if(_(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await k(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:te})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,i,n,o,a,c;try{let u={nextPage:null,lastPage:0,total:0},l=await k(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:ri});if(l.error)throw l.error;let d=await l.json(),f=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(b=>{let E=parseInt(b.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse(b.split(";")[1].split("=")[1]);u[`${w}Page`]=E}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(_(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){try{return await k(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:te})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await k(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:te})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await k(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:te})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await k(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(_(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await k(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}};var ii={getItem:r=>de()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{de()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{de()&&globalThis.localStorage.removeItem(r)}};function Ls(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function ni(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var Se={debug:!!(globalThis&&de()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},gt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Kt=class extends gt{};async function Is(r,e,t){Se.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Se.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 i=>{if(i){Se.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{Se.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw Se.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Kt(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Se.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}ni();var In={url:Br,storageKey:Gr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:zr,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},yt=30*1e3,oi=3;async function ai(r,e,t){return await t()}var Ee=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&&G()&&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({},In),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 ke({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Bt(i.fetch),this.lock=i.lock||ai,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:G()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Is:this.lock=ai,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:de()?this.storage=ii:(this.memoryStorage={},this.storage=Ls(this.memoryStorage)):(this.memoryStorage={},this.storage=Ls(this.memoryStorage)),G()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Ft}) ${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=G()?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: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)?{error:e}:{error:new Me("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{let n=await k(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:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:ne}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(_(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,i;try{let n;if("email"in e){let{email:l,password:d,options:f}=e,p=null,b=null;this.flowType==="pkce"&&([p,b]=await _e(this.storage,this.storageKey)),n=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:l,password:d,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:p,code_challenge_method:b},xform:ne})}else if("phone"in e){let{phone:l,password:d,options:f}=e;n=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:d,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(i=f?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:ne})}else throw new we("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,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(_(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 k(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:Os})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await k(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:Os})}else throw new we("You must provide either an email or phone number and a password");let{data:s,error:i}=t;return i?{data:{user:null,session:null},error:i}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new De}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(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 ht(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(t??"").split("/"),{data:n,error:o}=await k(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:ne});return await Gt(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new De}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:i,access_token:n,nonce:o}=e,a=await k(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:ne}),{data:c,error:u}=a;return u?{data:{user:null,session:null},error:u}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new De}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:u})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,i,n,o;try{if("email"in e){let{email:a,options:c}=e,u=null,l=null;this.flowType==="pkce"&&([u,l]=await _e(this.storage,this.storageKey));let{error:d}=await k(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:u,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){let{phone:a,options:c}=e,{data:u,error:l}=await k(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:u?.message_id},error:l}}throw new we("You must provide either an email or phone number.")}catch(a){if(_(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await k(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:ne});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(i){if(_(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,s,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await _e(this.storage,this.storageKey)),await k(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}),!((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:ti})}catch(n){if(_(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new ee;let{error:i}=await k(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))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:i,options:n}=e,{error:o}=await k(this.fetch,"POST",t,{headers:this.headers,body:{email:s,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:s,type:i,options:n}=e,{data:o,error:a}=await k(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new we("You must provide either an email or phone number and a type")}catch(t){if(_(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(),i=(async()=>(await s,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 s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.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 ht(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,u,l)=>(!o&&u==="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,u,l))})}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 k(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:te}):await this._useSession(async t=>{var s,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ee}:await k(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:te})})}catch(t){if(_(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:i,error:n}=s;if(n)throw n;if(!i.session)throw new ee;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await _e(this.storage,this.storageKey));let{data:u,error:l}=await k(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:te});if(l)throw l;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return Cs(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 ee;let t=Date.now()/1e3,s=t,i=!0,n=null,o=Cs(e.access_token);if(o.exp&&(s=o.exp,i=s<=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:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(_(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 ee;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(_(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!G())throw new ve("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ve("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new pt("Not a valid PKCE flow url.");let t=Wt(window.location.href);if(e){if(!t.code)throw new pt("No code detected.");let{data:g,error:x}=await this._exchangeCodeForSession(t.code);if(x)throw x;let P=new URL(window.location.href);return P.searchParams.delete("code"),window.history.replaceState(window.history.state,"",P.toString()),{data:{session:g.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new ve(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:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:u}=t;if(!n||!a||!o||!u)throw new ve("No session defined in URL");let l=Math.round(Date.now()/1e3),d=parseInt(a),f=l+d;c&&(f=parseInt(c));let p=f-l;p*1e3<=yt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${d}s`);let b=f-d;l-b>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",b,f,l):l-b<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",b,f,l);let{data:E,error:w}=await this._getUser(n);if(w)throw w;let C={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:d,expires_at:f,refresh_token:o,token_type:u,user:E.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:C,redirectType:t.type},error:null}}catch(t){if(_(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Wt(window.location.href);return!!(G()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Wt(window.location.href),t=await ht(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:i,error:n}=t;if(n)return{error:n};let o=(s=i.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Zr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Gt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Kr(),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,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((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 s=null,i=null;this.flowType==="pkce"&&([s,i]=await _e(this.storage,this.storageKey,!0));try{return await k(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(_(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:i}=await this._useSession(async n=>{var o,a,c,u,l;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 k(this.fetch,"GET",p,{headers:this.headers,jwt:(l=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return G()&&!(!((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(_(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)throw o;return await k(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(_(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 Qr(async i=>(i>0&&await Yr(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await k(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ne})),(i,n)=>{let o=200*Math.pow(2,i);return n&&Jt(n)&&Date.now()+o-s<yt})}catch(s){if(this._debug(t,"error",s),_(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),G()&&!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 ht(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 i=Math.round(Date.now()/1e3),n=((e=s.expires_at)!==null&&e!==void 0?e:1/0)<i+As;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${As}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Jt(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 ee;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new dt;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new ee;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),_(n)){let o={session:null,error:n};return Jt(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,s=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Rs(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Gt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&G()&&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(),yt);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 i=Math.floor((s.expires_at*1e3-e)/yt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${yt}ms, refresh threshold is ${oi} ticks`),i<=oi&&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 gt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!G()||!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 i=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await _e(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);i.push(n.toString())}return s?.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await k(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await k(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((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(_(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:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await k(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=i?.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(_(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:i,error:n}=t;return n?{data:null,error:n}:await k(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(_(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||[],i=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;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;((s=(t=i.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};Ee.nextInstanceID=0;var jn=Ee,js=jn;var Vt=class extends js{constructor(e){super(e)}};var $n=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{u(s.next(l))}catch(d){o(d)}}function c(l){try{u(s.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((s=s.apply(r,e||[])).next())})},_t=class{constructor(e,t,s){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=Fr(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`,u={db:Dr,realtime:qr,auth:Object.assign(Object.assign({},Nr),{storageKey:c}),global:Mr},l=Wr(s??{},u);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=Hr(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new Sr(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Ve(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ct(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 $n(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:i,storageKey:n,flowType:o,debug:a},c,u){var l;let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Vt({url:this.authUrl,headers:Object.assign(Object.assign({},d),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,flowType:o,debug:a,fetch:u,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new Ie(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 ci=(r,e,t)=>new _t(r,e,t);var oe={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Un=r=>{try{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(r.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},Yt=r=>{let[e,t]=r.split(".");return!e||!t?null:Un(t)},li=r=>{let e=Yt(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 Mn="https://api.workos.com",Dn=60,qe=(r,e)=>typeof r[e]=="string"?r[e]:void 0,ui=(r,e,t)=>{let s=Yt(r);if(!s)return null;let i=qe(s,"urn:wispr:user_external_id")??qe(s,"sub"),n=t?.email??qe(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:i??"",aud:"authenticated",email:n,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}},Nn=async(r,e,t,s)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):Mn,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:r,organization_id:s})});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()},di=async(r,e)=>{let t=Yt(r);if(!t)throw new Error("Invalid WorkOS access token");let s=Math.floor(Date.now()/1e3),i=typeof t.exp=="number"?t.exp:0,n=qe(t,"client_id");if(i-s<Dn&&n){let c=await Nn(e,n,qe(t,"iss"),qe(t,"org_id")),u=ui(c.access_token,c.refresh_token,c.user);if(!u)throw new Error("WorkOS refresh returned an invalid access token");return u}if(i<=s)throw new Error("WorkOS session expired");let a=ui(r,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var wt=class{constructor(){this.sessionData=null;this.supabase=ci(oe.supaBaseUrl,oe.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||oe.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||oe.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||oe.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:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;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 i=new Date;i.setTime(i.getTime()+s*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,s=e.refresh_token;if(t&&s)try{if(li(t)==="workos"){this.sessionData=await di(t,s),this.setCookies(this.sessionData.access_token,this.sessionData.refresh_token);return}await this.setSession(t,s)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[s,i]=t.split("=");return e[s]=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:s}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:t||oe.redirectUri}});if(s)throw s}catch(s){throw console.error("Error sending magic link:",s),s}}async signUpWithPassword(e,t,s,i,n,o){try{if(!n)throw new Error("Please complete the verification");let a=o?.deviceCode,c=a&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?a:void 0,u=await X.signUpWithCaptcha({email:e,password:t,full_name:s,captcha_token:n,device_code:c,redirect_url:i||oe.redirectUri,workos_capable:o?.workosCapable||void 0});return console.log("Signup request completed"),u}catch(a){throw console.error("Error signing up:",a),a}}async signInWithPassword(e,t,s,i){try{if(!s)throw new Error("Please complete the verification");let n=await X.signInWithCaptcha({email:e,password:t,captcha_token:s,provision:i?.provision??!1,workos_capable:i?.workosCapable||void 0});if(ze(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,s,i){try{if(!s)throw new Error("Please complete the verification");let n=await X.resendVerificationEmailCaptcha({email:e,captcha_token:s,redirect_url:t||oe.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 se=null;function Qt(r,e=30,t){se&&(clearInterval(se),se=null);let s=e;r.style.pointerEvents="none",r.textContent=`Resend (${s}s)`,se=setInterval(()=>{s=s-1,r.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(r.style.pointerEvents="auto",se&&(clearInterval(se),se=null),t&&t())},1e3)}function $s(){se&&(clearInterval(se),se=null)}var hi=/^[\p{L}\p{M}\s\-'.]+$/u;function qn(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":hi.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 Xt(r,e){let t=r.trim();return t?/\d/.test(t)?"Your name can't include numbers":hi.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 Us(r,e,t){let s="full-name-match-error",i=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let u=document.getElementById(s);u||(u=document.createElement("div"),u.id=s,u.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",u)),u.textContent=c},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(s)?.remove()},o=()=>{let c=qn(e.value,r.value);c?i(c):n()},a=()=>{let c=Xt(e.value,r.value);c?i(c):n()};r.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var fi="password-rejection-error",Ms=r=>r instanceof K?r.passwordRejectionMessage:null,He=r=>{r.classList.remove("error"),document.getElementById(fi)?.remove()},Zt=(r,e)=>{if(He(r),e.length===0)return;r.classList.add("error");let t=document.createElement("div");t.id=fi,t.style.fontSize="0.875rem",t.textContent=e,r.insertAdjacentElement("afterend",t)};var Hn="wisprjam.com",Fn="wispr.ai";var Wn=r=>r.trim().toLowerCase().split("@")[1]??"",pi=r=>{let e=Wn(r);return e===Hn||e===Fn};var mi="/granola-switch",Ds="granola-switch",gi=r=>{let e=r.get("months");return e==="1"||e==="2"||e==="3"?e:null};var Bn="https://api.wisprflow.ai",Gn="workos_enabled_webflow";window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let r=localStorage.getItem("checkout_debug");if(r){try{let h=JSON.parse(r);J("checkout_debug",{...h,reported_from:"get_started",ms_since_error:Date.now()-(h.timestamp??Date.now())})}catch{}localStorage.removeItem("checkout_debug")}let e=!1,t=setTimeout(()=>{e||(document.body.style.visibility="visible")},4e3),s=new wt,i=null,n=()=>{i?.clear()},{accessToken:o,refreshToken:a}=or(),c=document.querySelector("#email-form"),u=document.querySelector("#email-input"),l=document.querySelector("#password-input"),d=document.querySelector("#full-name"),f=document.querySelector("#google-login"),p=document.querySelector("#apple-login"),b=document.querySelector("#microsoft-login"),E=document.querySelector("#sso-login"),w=document.querySelector("[sso-login-div]"),C=document.querySelector("#sso-email"),g=document.querySelector("#sso-signup-form"),x=document.querySelector('[sso-login="go-back"]'),P=document.querySelector(".gs-hero_form-block"),j;(A=>(A.EMAIL_INPUT="email_input",A.LOGIN="login",A.SIGNUP="signup",A.OAUTH_USER="oauth_user",A.UNVERIFIED_EMAIL="unverified_email"))(j||(j={}));let V="email_input",$=document.querySelector("[email-element]"),re=document.querySelector("[different-provider]"),Ns=document.querySelector("[different-provider-name]"),qs=document.querySelector("[different-provider-reset]"),Te=document.querySelector("[email-signup-success]"),v=document.querySelector("[email-signup-error]"),T=document.querySelector("[error-message]"),Hs=document.querySelector("[verification-email]"),Fe=document.querySelector("[email-signup-retry]"),Fs=document.querySelector("[email-signup-reset]"),xe=document.querySelector("[scim-div]"),Ws=document.querySelector("[scim-reset]"),W=document.querySelector("[forgot-password]"),vt=document.querySelector("[forgot-password-success]"),Bs=document.querySelector("[forgot-password-email]"),ae=document.querySelector("[unverified-email]"),Gs=document.querySelector("[unverified-email-address]"),Y=document.querySelector("[resend-verification-email]"),zs=document.querySelector("[unverified-email-reset]"),yi=localStorage.getItem("email"),Js=localStorage.getItem("last_authed_provider");Js&&{google:f,apple:p,microsoft:b,sso:E,email:u}[Js]?.classList.add("last-used");let We=new URLSearchParams(window.location.search),Ks=We.get("redirect"),bt=We.get("error"),zn=We.get("code"),_i=Ks===Ds?mi:"/downloads",H=`${window.location.origin}${_i}`,Ae=new URLSearchParams(We);if(Ae.delete("redirect"),Ae.delete("months"),Ks===Ds){Ae.set("auth_return","1");let h=gi(We);h&&Ae.set("months",h)}if(Ae.toString()&&(H+=`?${Ae.toString()}`),bt){let h=bt==="account_unsupported"?"This account is not supported. Try signing in with another account.":"Unable to complete authentication. Please try again.";J("get_started_oauth_error",{error:bt,surface:"get-started"}),v&&(v.style.display="block"),T&&(T.textContent=h),document.body.style.visibility="visible"}cr({includeError:!!bt});let wi=()=>{try{let h=document.cookie.split("; ");for(let m of h){let y=m.indexOf("=");if(y===-1||m.slice(0,y)!=="wispr_auth")continue;let L=m.slice(y+1),A=decodeURIComponent(L);return JSON.parse(A)}return null}catch{return null}};if(o&&a)try{s.setCookies(o,a),await s.checkAndSetSession(),s.sessionData&&s.setCookies(s.sessionData.access_token,s.sessionData.refresh_token);let h=s.sessionData?.user.email;localStorage.setItem("email",h),e=!0,clearTimeout(t),window.location.href=H}catch(h){console.error("Error during session setup:",h),document.body.style.visibility="visible"}else{let h=wi();if(h?.access_token&&h?.refresh_token)try{s.setCookies(h.access_token,h.refresh_token),await s.checkAndSetSession(),s.sessionData&&s.setCookies(s.sessionData.access_token,s.sessionData.refresh_token);let m=s.sessionData?.user.email,y=s.sessionData?.user.app_metadata.provider||"typing_test";localStorage.setItem("email",m),localStorage.setItem("signin_provider",y),e=!0,clearTimeout(t),window.location.href=H}catch(m){console.error("Error authenticating from typing test session:",m),h.email&&(u.value=h.email),document.body.style.visibility="visible"}else h?.email?(u.value=h.email,document.body.style.visibility="visible"):(yi&&localStorage.removeItem("email"),document.body.style.visibility="visible")}let kt=async(h,m)=>{try{n(),localStorage.setItem("signin_provider",h);let y=window.posthog?.getFeatureFlag?.(Gn)===!0;if(J("get_started_oauth_click",{provider:y?"workos":h,idp:h,surface:"get-started",workos_enabled_webflow:y}),h==="sso"||y){let S=y?`authkit/${h}/sign_in`:`${h}/sign_in`,L=new URL(`${Bn}/${S}`);L.searchParams.set("source",H),m&&L.searchParams.set("email",m),window.location.href=L.toString();return}h==="google"?await s.signInWithGoogle(H):h==="apple"?await s.signInWithApple(H):await s.signInWithMicrosoft(H)}catch(y){console.error("Error during sign-in:",y)}};f.addEventListener("click",async()=>{await kt("google")}),p.addEventListener("click",async()=>{await kt("apple")}),b.addEventListener("click",async()=>{await kt("microsoft")}),E&&(E.style.display="flex",E.addEventListener("click",h=>{h.preventDefault(),w&&(w.style.display="block"),P&&(P.style.display="none"),C?.focus()})),x&&x.addEventListener("click",h=>{h.preventDefault(),w&&(w.style.display="none"),P&&(P.style.display="block"),C&&(C.value="",C.blur())}),g&&g.addEventListener("submit",h=>{h.preventDefault(),h.stopPropagation();let m=N(C?.value||"");m&&kt("sso",m)});let Be=()=>{n(),re&&(re.style.display="none"),Te&&(Te.style.display="none"),v&&(v.style.display="none"),ae&&(ae.style.display="none"),xe&&(xe.style.display="none"),W&&(W.style.display="none"),vt&&(vt.style.display="none"),he();let h=document.querySelector(".gs-hero_form-block");h&&(h.style.display="block"),$&&($.style.display="flex"),u.value="",u.removeAttribute("readonly"),u.classList.remove("disabled"),l.value="",l.style.display="none",l.removeAttribute("required"),He(l),d.value="",d.style.display="none",d.removeAttribute("required");let m=document.querySelector("[captcha-embed]"),y=document.querySelector("#h-captcha-container");m&&(m.style.display="none"),y&&(y.style.display="none"),M()?.reset(),V="email_input",u.focus()},St=()=>{$&&($.style.display="flex"),u.setAttribute("readonly","true"),u.classList.add("disabled"),l.style.display="block",l.setAttribute("required","true"),l.focus(),d.style.display="none",d.removeAttribute("required");let h=document.querySelector("[captcha-embed]"),m=document.querySelector("#h-captcha-container");h&&(h.style.display="block"),m&&(m.style.display="block"),W&&(W.style.display="block",W.onclick=async()=>{let y=u.value,S=W.textContent||"";try{let L=M();if(!L)throw new Error("Verification system not loaded. Please refresh the page.");W.style.pointerEvents="none",W.textContent="Sending...";let A=await L.execute({async:!0}),U=typeof A=="string"?A:A.response;if(!U)throw new Error("Verification cancelled");await X.requestPasswordReset(y,U),L.reset(),$&&($.style.display="none"),W&&(W.style.display="none"),vt&&(vt.style.display="block"),Bs&&(Bs.textContent=y)}catch(L){console.error("\u274C Error sending password reset email:",L),W.textContent=S,W.style.pointerEvents="auto",M()?.reset(),v&&(v.style.display="block",T&&(T.textContent=L instanceof Error?L.message:"Failed to send reset email"))}}),V="login",console.log("\u2705 Existing user detected - showing login form")},Vs=()=>{u.setAttribute("readonly","true"),u.classList.add("disabled"),l.style.display="block",l.setAttribute("required","true"),d.style.display="block",d.setAttribute("required","true"),l.focus();let h=document.querySelector("[captcha-embed]"),m=document.querySelector("#h-captcha-container");h&&(h.style.display="block"),m&&(m.style.display="block"),V="signup",console.log("\u2705 New user detected - showing signup form")},Ys=()=>{let h=document.querySelector(".gs-hero_form-block");h&&(h.style.display="none"),xe&&(xe.style.display="block"),Ws&&(Ws.onclick=()=>{xe&&(xe.style.display="none"),h&&(h.style.display="block"),Be()})},es=h=>{n();let m=is(h);$&&($.style.display="none"),re&&(re.style.display="block"),Ns&&(Ns.textContent=m),qs&&(qs.onclick=()=>{re&&(re.style.display="none"),Be()}),V="oauth_user"};i=os({client:s,redirectUrl:H,isWorkosCapable:()=>!0,beforeShow:()=>{$&&($.style.display="none"),ae&&(ae.style.display="none")},onAuthenticated:async h=>{n(),s.setCookies(h.access_token,h.refresh_token),localStorage.setItem("email",h.email),localStorage.setItem("user_id",h.user_id),localStorage.setItem("signin_provider","email"),e=!0,clearTimeout(t),window.location.href=H},onMissingChallenge:St,onReset:Be});let vi=h=>{$&&($.style.display="none"),ae&&(ae.style.display="block"),Gs&&(Gs.textContent=h),Y&&(Y.onclick=async()=>{let m=Y.textContent||"";try{Y.textContent="Verifying...",Y.style.pointerEvents="none";let y=await Je();Y.textContent="Sending...",await s.resendVerificationEmail(h,H,y),Y.textContent="Verification email resent! \u2705",Y.style.textDecoration="none",v&&(v.style.display="none")}catch(y){Y.textContent=m,Y.style.pointerEvents="auto",v&&(v.style.display="block"),T&&(T.textContent=Re(y,"Unable to resend verification."))}finally{M()?.reset()}}),zs&&(zs.onclick=()=>{ae&&(ae.style.display="none"),Be()}),V="unverified_email",console.log("\u26A0\uFE0F Unverified user detected - showing resend verification UI")},ts=h=>ns(h,{showSso:()=>es("workos"),showScim:Ys,showLogin:St,showError:m=>{v&&(v.style.display="block"),T&&(T.textContent=m)}}),bi=async(h,m)=>{let y=m.value;m.classList.add("loading"),m.value="";try{let S=await X.checkUserStatus(h);console.log("User status check:",S),m.classList.remove("loading"),m.value=y,!S.exists&&S.scim_managed?Ys():S.enforce_sso?es("workos"):S.exists&&S.provider&&S.provider!=="email"&&S.provider!=="workos"?es(S.provider):S.exists&&S.provider==="workos"?St():S.exists&&S.provider==="email"&&!S.verified?vi(h):S.exists&&S.provider==="email"?St():Vs()}catch(S){console.error("\u274C Error checking user status:",S),m.classList.remove("loading"),m.value=y,ts(S)||Vs()}},ki=async(h,m,y,S)=>{if(!m||m.length<8){v&&(v.style.display="block",T&&(T.textContent="Password must be at least 8 characters"));return}let L=M()?.getResponse()||"";if(!L){v&&(v.style.display="block",T&&(T.textContent="Please complete the verification"));return}y.classList.add("loading"),y.value="";try{let A=pi(h),U=await s.signInWithPassword(h,m,L,{workosCapable:A,provision:!1});if(U.kind==="otp"){if(!A)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let z={pendingAuthenticationToken:U.challenge.pending_authentication_token,email:N(U.challenge.email||h)};M()?.reset(),y.classList.remove("loading"),y.value=S,i?.show(z);return}s.setCookies(U.accessToken,U.refreshToken),localStorage.setItem("email",h),e=!0,clearTimeout(t),window.location.href=H}catch(A){M()?.reset(),y.classList.remove("loading"),y.value=S,!ts(A)&&v&&(v.style.display="block",T&&(T.textContent=Re(A,"Unable to sign in. Please try again.")))}},Si=async(h,m,y,S,L)=>{if(!m||m.length<8){v&&(v.style.display="block",T&&(T.textContent="Password must be at least 8 characters"));return}if(m.trim().toLowerCase()===h.trim().toLowerCase()){Zt(l,"Password can't be the same as your email address.");return}if(!y||y.trim().length<2){v&&(v.style.display="block",T&&(T.textContent="Please enter your full name"));return}let A=Xt(y,m);if(A){v&&(v.style.display="block",T&&(T.textContent=A));return}let U=M()?.getResponse()||"";if(!U){v&&(v.style.display="block",T&&(T.textContent="Please complete the verification"));return}S.classList.add("loading"),S.value="";try{let z=await s.signUpWithPassword(h,m,y,H,U,{workosCapable:!0});if(M()?.reset(),S.classList.remove("loading"),S.value=L,$&&($.style.display="none"),v&&(v.style.display="none"),ze(z)){let ce={pendingAuthenticationToken:z.pending_authentication_token,email:N(z.email||h)};i?.show(ce);return}Te&&(Te.style.display="block"),Hs&&(Hs.textContent=h),Fe&&(Qt(Fe,30),Fe.onclick=async()=>{if(Fe.style.pointerEvents!=="none")try{let ce=await Je();await s.resendVerificationEmail(h,H,ce,{workosCapable:!0}),Qt(Fe,30)}catch(ce){v&&(v.style.display="block"),T&&(T.textContent=Re(ce,"Unable to resend verification. Please try again."))}finally{M()?.reset()}}),Fs&&(Fs.onclick=()=>{Te&&(Te.style.display="none"),$s(),Be()})}catch(z){S.classList.remove("loading"),S.value=L,M()?.reset();let ce=Ms(z);ce?Zt(l,ce):!ts(z)&&v&&(v.style.display="block",T&&(T.textContent=Re(z,"Unable to create the account. Please try again.")))}};Us(l,d,c.querySelector('[type="submit"]')),l.addEventListener("input",()=>He(l)),c.addEventListener("submit",async h=>{h.stopPropagation(),h.preventDefault();let m=N(u.value);u.value=m;let y=l?.value||"",S=d?.value||"";if(!m||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m)){console.error("\u274C Email invalid"),v&&(v.style.display="block",T&&(T.textContent="Please enter a valid email address"));return}v&&(v.style.display="none"),T&&(T.textContent=""),He(l);let A=c.querySelector('[type="submit"]'),U=A?.value||"";localStorage.setItem("signin_provider","email");try{V==="email_input"?await bi(m,A):V==="login"?await ki(m,y,A,U):V==="signup"&&await Si(m,y,S,A,U)}catch(z){console.error("\u274C Signup error:",z),A&&(A.classList.remove("loading"),A.value=U),v&&(v.style.display="block")}})});})();
|
|
1
|
+
"use strict";(()=>{var Ei=Object.create;var Et=Object.defineProperty;var Ti=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var Ai=Object.getPrototypeOf,Pi=Object.prototype.hasOwnProperty;var Ri=(s,e)=>()=>(s&&(e=s(s=0)),e);var Q=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ci=(s,e)=>{for(var t in e)Et(s,t,{get:e[t],enumerable:!0})},Qr=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of xi(e))!Pi.call(s,i)&&i!==t&&Et(s,i,{get:()=>e[i],enumerable:!(r=Ti(e,i))||r.enumerable});return s};var Xr=(s,e,t)=>(t=s!=null?Ei(Ai(s)):{},Qr(e||!s||!s.__esModule?Et(t,"default",{value:s,enumerable:!0}):t,s)),Oi=s=>Qr(Et({},"__esModule",{value:!0}),s);var pe={};Ci(pe,{Headers:()=>cr,Request:()=>Fi,Response:()=>Wi,default:()=>ar,fetch:()=>Hi});var qi,Oe,Hi,ar,cr,Fi,Wi,le=Ri(()=>{"use strict";qi=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")},Oe=qi(),Hi=Oe.fetch,ar=Oe.fetch.bind(Oe),cr=Oe.Headers,Fi=Oe.Request,Wi=Oe.Response});var us=Q(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=Q(Ye=>{"use strict";var ds=Ye&&Ye.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ye,"__esModule",{value:!0});var Gi=ds((le(),Oi(pe))),zi=ds(us()),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=Gi.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 u=null,l=null,d=null,f=n.status,p=n.statusText;if(n.ok){if(this.method!=="HEAD"){let C=await n.text();C===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=C:l=JSON.parse(C))}let E=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),w=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");E&&w&&w.length>1&&(d=parseInt(w[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(u={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,d=null,f=406,p="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let E=await n.text();try{u=JSON.parse(E),Array.isArray(u)&&n.status===404&&(l=[],u=null,f=200,p="OK")}catch{n.status===404&&E===""?(f=204,p="No Content"):u={message:E}}if(u&&this.isMaybeSingle&&(!((c=u?.details)===null||c===void 0)&&c.includes("0 rows"))&&(u=null,f=200,p="OK"),u&&this.shouldThrowOnError)throw new zi.default(u)}return{error:u,data:l,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)}};Ye.default=dr});var pr=Q(Qe=>{"use strict";var Ji=Qe&&Qe.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Qe,"__esModule",{value:!0});var Ki=Ji(hr()),fr=class extends Ki.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("|"),u=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${u}"; 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}};Qe.default=fr});var Lt=Q(Xe=>{"use strict";var Vi=Xe&&Xe.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Xe,"__esModule",{value:!0});var Yi=Vi(pr()),mr=class extends Yi.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}};Xe.default=mr});var yr=Q(et=>{"use strict";var Qi=et&&et.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(et,"__esModule",{value:!0});var Ze=Qi(Lt()),gr=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 Ze.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 Ze.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((u,l)=>u.concat(Object.keys(l)),[]);if(c.length>0){let u=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",u.join(","))}}return new Ze.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 Ze.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 Ze.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};et.default=gr});var hs=Q(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.version=void 0;It.version="0.0.0-automated"});var fs=Q(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.DEFAULT_HEADERS=void 0;var Xi=hs();jt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Xi.version}`}});var ms=Q(tt=>{"use strict";var ps=tt&&tt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(tt,"__esModule",{value:!0});var Zi=ps(yr()),en=ps(Lt()),tn=fs(),_r=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},tn.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new Zi.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(([l,d])=>d!==void 0).map(([l,d])=>[l,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([l,d])=>{a.searchParams.append(l,d)})):(o="POST",c=t);let u=Object.assign({},this.headers);return n&&(u.Prefer=`count=${n}`),new en.default({method:o,url:a,headers:u,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};tt.default=_r});var bs=Q(D=>{"use strict";var rt=D&&D.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(D,"__esModule",{value:!0});D.PostgrestBuilder=D.PostgrestTransformBuilder=D.PostgrestFilterBuilder=D.PostgrestQueryBuilder=D.PostgrestClient=void 0;var gs=rt(ms());D.PostgrestClient=gs.default;var ys=rt(yr());D.PostgrestQueryBuilder=ys.default;var _s=rt(Lt());D.PostgrestFilterBuilder=_s.default;var ws=rt(pr());D.PostgrestTransformBuilder=ws.default;var vs=rt(hr());D.PostgrestBuilder=vs.default;D.default={PostgrestClient:gs.default,PostgrestQueryBuilder:ys.default,PostgrestFilterBuilder:_s.default,PostgrestTransformBuilder:ws.default,PostgrestBuilder:vs.default}});var Cs=Q((zo,Rs)=>{"use strict";Rs.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var rr=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var J=(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(()=>J(s,e,t-1),200)};var ze=s=>s.verification_method==="email_otp"&&typeof s.pending_authentication_token=="string"&&s.pending_authentication_token.length>0,O="https://api.wisprflow.ai",K=class extends Error{constructor(t,r,i,n=null){super(i);this.status=t;this.code=r;this.passwordRejectionMessage=n;this.name="AriaAuthError"}},N=s=>s.trim().toLowerCase(),Zr=(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"},Ge=(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."),Li=(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)??Ge(e,t),Re=(s,e)=>{let t=Zr(s,e);return new K(e,t,Li(s,t,e),e===400&&typeof s.detail=="string"&&s.detail.length>0?s.detail:null)},Ii=(s,e)=>{let t=Zr(s,e);return new K(e,t,Ge(t,e))},Tt="promo_code",ji=4e3,$i=new Set([200,400,403,404,409,422]),es=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}`},ts=s=>{if(!s)return"";try{return decodeURIComponent(s).trim()}catch{return""}},Ui=()=>{let s=rr()[Tt];if(s===void 0)return"";let e=ts(s);return e||es(Tt),e},Mi=s=>{ts(rr()[Tt])===s&&es(Tt)},Di=s=>s instanceof DOMException&&(s.name==="TimeoutError"||s.name==="AbortError"),Ni=(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",sr=class{static async signupUser(e){try{let t=`${O}/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(`${O}/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(`${O}/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(`${O}/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(`${O}/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=N(e),r=await fetch(`${O}/user_status?email=${encodeURIComponent(t)}`),i=await r.json().catch(()=>({}));if(!r.ok)throw Re(i,r.status);return i}static async requestPasswordReset(e,t){let r=await fetch(`${O}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:N(e),captcha_token:t})});if(!r.ok){let i=await r.json().catch(()=>({}));throw Re(i,r.status)}}static async signUpWithCaptcha(e){let t=await fetch(`${O}/email/signup-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:N(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Re(r,t.status);return r}static async signInWithCaptcha(e){let t=await fetch(`${O}/email/signin-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:N(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Re(r,t.status);return r}static async resendVerificationEmailCaptcha(e){let t=await fetch(`${O}/email/resend-verification-email-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:N(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Re(r,t.status);return r}static async verifyEmailOtp(e){if(!/^[0-9]{6}$/.test(e.code))throw new K(422,"invalid_code",Ge("invalid_code",422));let t=await fetch(`${O}/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=Ii(r,t.status);throw i.code==="rate_limited"||i.code==="provider_unavailable"||i.code==="validation_error"?i:new K(t.status,"verification_failed",Ge("verification_failed",t.status))}if(r.provider!=="workos"||!r.access_token||!r.refresh_token||!r.user_id||!r.email)throw new K(t.status,"authentication_failed",Ge("authentication_failed",t.status));return r}static async signInWithEmail(e){let t=await fetch(`${O}/email/signin`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,email:N(e.email)})}),r=await t.json().catch(()=>({}));if(!t.ok)throw Re(r,t.status);return r}static async applyPromoCodeFromCookie(e,t=Ui()){if(t)try{let r=await fetch(`${O}/api/v1/promos/campaign/apply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:e},body:JSON.stringify({code:t,source:"web"}),signal:AbortSignal.timeout(ji)}),{status:i}=r;if(!$i.has(i)){J("promo_cookie_apply",{outcome:"deferred",status:i});return}if(Mi(t),r.ok){J("promo_cookie_apply",{outcome:"attached",status:i});return}let n=await r.json().catch(()=>({}));J("promo_cookie_apply",{outcome:"rejected",status:i,reason:Ni(n,i)})}catch(r){console.error("Promo cookie apply deferred:",r),J("promo_cookie_apply",Di(r)?{outcome:"deferred",reason:"timeout"}:{outcome:"deferred"})}}static async getSubscriptionStatus(e){return await fetch(`${O}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${O}/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,i){let n=new URLSearchParams({plan:e,custom_redirect:"true"});r&&n.set("currency",r),i?.trim()&&n.set("promo_code",i.trim());let o=`${O}/api/v1/payment/create-checkout-session?${n}`,a=await fetch(o,{method:"POST",headers:{accept:"application/json",Authorization:t}});if(!a.ok&&a.status!==303)throw new Error(`Checkout request failed (${a.status})`);let c=await a.json();if(!c||typeof c.url!="string"||!c.url)throw new Error("Checkout response is missing a URL");return c}static async sendDownloadLink(e,t){return await fetch(`${O}/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(`${O}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${O}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${O}/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(`${O}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:r})}};function ir(s){return s==="azure"?"Microsoft":s==="workos"?"SSO":s.charAt(0).toUpperCase()+s.slice(1)}var X=sr;var xt=null,rs=(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},At=()=>{xt!==null&&(window.clearInterval(xt),xt=null)};function fe(){let s=document.querySelector("[otp-verification]");s&&(s.style.display="none"),At()}function ss(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]"),u=document.querySelector("[otp-resend-seconds]"),l=document.querySelector("[otp-reset]");t.forEach(g=>{g.value="",g.removeAttribute("disabled"),g.setAttribute("inputmode","numeric"),g.setAttribute("autocomplete","one-time-code"),g.setAttribute("data-ph-no-capture",""),g.setAttribute("data-1p-ignore",""),g.setAttribute("data-private",""),g.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")),At(),r&&(r.textContent=s.email),e.style.display="block",t[0]?.focus();let d=g=>{n&&(n.style.display="block"),o&&(o.textContent=g)},f=()=>{n&&(n.style.display="none")},p=!1,b=!1,E=g=>{i&&(i.style.pointerEvents=g?"none":"",g?i.setAttribute("aria-disabled","true"):i.removeAttribute("aria-disabled"),i instanceof HTMLButtonElement&&(i.disabled=g),a&&a.style.display!=="none"&&(a.style.pointerEvents=g?"none":"",g?a.setAttribute("aria-disabled","true"):a.removeAttribute("aria-disabled")))},w=async()=>{if(p)return;let g=t.map(x=>x.value).join("");if(g.length!==6){d("Please enter all 6 digits.");return}p=!0,E(!0),t.forEach(x=>x.setAttribute("disabled","true")),f();try{await s.onVerify(g),f(),i&&(i.textContent="Verified \u2705")}catch(x){p=!1,E(!1),t.forEach(P=>{P.value="",P.removeAttribute("disabled")}),d(rs(x,"Incorrect or expired code. Try again.")),t[0]?.focus()}};t.forEach((g,x)=>{g.oninput=()=>{g.value=g.value.replace(/\D/g,"").slice(0,1),g.value&&x<t.length-1&&t[x+1].focus(),f()},g.onkeydown=P=>{P.key==="Backspace"&&!g.value&&x>0?t[x-1].focus():P.key==="Enter"&&(P.preventDefault(),w())},g.onpaste=P=>{P.preventDefault();let j=(P.clipboardData?.getData("text")||"").replace(/\D/g,"").slice(0,6);j.split("").forEach(($,se)=>{t[se]&&(t[se].value=$)});let V=Math.min(j.length,t.length-1);t[V]?.focus(),f()}}),i&&(i.onclick=g=>{g.preventDefault(),w()});let C=()=>{let g=30;a&&(a.style.display="none"),c&&(c.style.display="block"),u&&(u.textContent=String(g)),At(),xt=window.setInterval(()=>{g-=1,u&&(u.textContent=String(g)),g<=0&&(At(),a&&(a.style.display=""),c&&(c.style.display="none"))},1e3)};a&&(a.onclick=async g=>{if(g.preventDefault(),!(b||a.style.display==="none")){b=!0,t.forEach(x=>{x.value="",x.removeAttribute("disabled")}),t[0]?.focus(),f(),C();try{await s.onResend?.()}catch(x){d(rs(x,"We couldn't send a new code. Please try again when the timer ends."))}finally{b=!1}}}),l&&(l.onclick=g=>{g.preventDefault(),fe(),s.onReset?.()})}var M=()=>window.hcaptcha,Je=async()=>{let s=M();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},Ce=(s,e)=>s instanceof Error?s.message:e,nr=(s,e)=>s instanceof K?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,or=s=>{let e=null,t=()=>{e=null};return window.addEventListener("pagehide",t),{clear:t,show(r){e={pendingAuthenticationToken:r.pendingAuthenticationToken,email:N(r.email)},s.beforeShow(),ss({email:e.email,onVerify:async i=>{if(!e)throw fe(),s.onMissingChallenge(),new Error("Missing OTP challenge");let n=await X.verifyEmailOtp({code:i,pending_authentication_token:e.pendingAuthenticationToken});t(),await s.onAuthenticated(n)},onResend:async()=>{if(!e)throw fe(),s.onMissingChallenge(),new Error("Missing OTP challenge");let i=await Je();try{await s.client.resendVerificationEmail(e.email,s.redirectUrl,i,{workosCapable:s.isWorkosCapable(e.email)})}finally{M()?.reset()}},onReset:()=>{t(),s.onReset()}})}}};var is=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var ns=()=>{let s=window.location.hash.substring(1),e=new URLSearchParams(s);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var os=()=>{let{access_token:s,refresh_token:e}=ns(),t=new URLSearchParams(window.location.search),r=t.get("access_token")||s,i=t.get("refresh_token")||e;if(!r||!i){let n=is();r=n.access_token,i=n.refresh_token}return{accessToken:r,refreshToken:i}};var as=["access_token","refresh_token","email","user_id","name"],cs=({includeError:s=!1}={})=>{let e=new URL(window.location.href),t=s?[...as,"error"]:as;if(t.some(r=>e.searchParams.has(r))){for(let r of t)e.searchParams.delete(r);window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`)}};var ls=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(le(),pe)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var Ke=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Pt=class extends Ke{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Rt=class extends Ke{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Ct=class extends Ke{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Ot;(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"})(Ot||(Ot={}));var Bi=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(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Ve=class{constructor(e,{headers:t={},customFetch:r,region:i=Ot.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=ls(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return Bi(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 u;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",u=o):typeof o=="string"?(a["Content-Type"]="text/plain",u=o):typeof FormData<"u"&&o instanceof FormData?u=o:(a["Content-Type"]="application/json",u=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:u}).catch(b=>{throw new Pt(b)}),d=l.headers.get("x-relay-error");if(d&&d==="true")throw new Rt(l);if(!l.ok)throw new Ct(l);let f=((r=l.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),p;return f==="application/json"?p=yield l.json():f==="application/octet-stream"?p=yield l.blob():f==="text/event-stream"?p=l:f==="multipart/form-data"?p=yield l.formData():p=yield l.text(),{data:p,error:null}}catch(i){return{data:null,error:i}}})}};var ks=Xr(bs(),1),{PostgrestClient:Ss,PostgrestQueryBuilder:Ao,PostgrestFilterBuilder:Po,PostgrestTransformBuilder:Ro,PostgrestBuilder:Co}=ks.default;var Es="2.10.2";var Ts={"X-Client-Info":`realtime-js/${Es}`},xs="1.0.0",Ut=1e4,As=1e3,me;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(me||(me={}));var q;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(q||(q={}));var F;(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"})(F||(F={}));var $t;(function(s){s.websocket="websocket"})($t||($t={}));var ue;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(ue||(ue={}));var st=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 u=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:u}}};var ge=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 R;(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"})(R||(R={}));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]=rn(o,s,e,i),n),{})},rn=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?Ps(n,o):wr(o)},Ps=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return an(e,t)}switch(s){case R.bool:return sn(e);case R.float4:case R.float8:case R.int2:case R.int4:case R.int8:case R.numeric:case R.oid:return nn(e);case R.json:case R.jsonb:return on(e);case R.timestamp:return cn(e);case R.abstime:case R.date:case R.daterange:case R.int4range:case R.int8range:case R.money:case R.reltime:case R.text:case R.time:case R.timestamptz:case R.timetz:case R.tsrange:case R.tstzrange:return wr(e);default:return wr(e)}},wr=s=>s,sn=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},nn=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},on=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},an=(s,e)=>{if(typeof s!="string")return s;let t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n,o=s.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Ps(e,a))}return s},cn=s=>typeof s=="string"?s.replace(" ","T"):s,Mt=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var ye=class{constructor(e,t,r={},i=Ut){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 Le=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,(u,l)=>{o[u]||(c[u]=l)}),this.map(o,(u,l)=>{let d=n[u];if(d){let f=l.map(w=>w.presence_ref),p=d.map(w=>w.presence_ref),b=l.filter(w=>p.indexOf(w.presence_ref)<0),E=d.filter(w=>f.indexOf(w.presence_ref)<0);b.length>0&&(a[u]=b),E.length>0&&(c[u]=E)}else a[u]=l}),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 u;let l=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(c),l.length>0){let d=e[a].map(p=>p.presence_ref),f=l.filter(p=>d.indexOf(p.presence_ref)<0);e[a].unshift(...f)}r(a,l,c)}),this.map(o,(a,c)=>{let u=e[a];if(!u)return;let l=c.map(d=>d.presence_ref);u=u.filter(d=>l.indexOf(d.presence_ref)<0),e[a]=u,i(a,u,c),u.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 Ie=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=q.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 ye(this,F.join,this.params,this.timeout),this.rejoinTimer=new ge(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=q.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=q.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=q.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=q.errored,this.rejoinTimer.scheduleTimeout())}),this._on(F.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new Le(this),this.broadcastEndpointURL=Mt(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(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},u={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:u},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var d;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let f=this.bindings.postgres_changes,p=(d=f?.length)!==null&&d!==void 0?d:0,b=[];for(let E=0;E<p;E++){let w=f[E],{filter:{event:C,schema:g,table:x,filter:P}}=w,j=l&&l[E];if(j&&j.event===C&&j.schema===g&&j.table===x&&j.filter===P)b.push(Object.assign(Object.assign({},w),{id:j.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=b,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,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 u=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"),u.receive("ok",()=>n("ok")),u.receive("error",()=>n("error")),u.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=q.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(F.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new ye(this,F.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 ye(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:u,join:l}=F;if(r&&[a,c,u,l].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 b,E,w;return((b=p.filter)===null||b===void 0?void 0:b.event)==="*"||((w=(E=p.filter)===null||E===void 0?void 0:E.event)===null||w===void 0?void 0:w.toLocaleLowerCase())===o}).map(p=>p.callback(f,r)):(n=this.bindings[o])===null||n===void 0||n.filter(p=>{var b,E,w,C,g,x;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){let P=p.id,j=(b=p.filter)===null||b===void 0?void 0:b.event;return P&&((E=t.ids)===null||E===void 0?void 0:E.includes(P))&&(j==="*"||j?.toLocaleLowerCase()===((w=t.data)===null||w===void 0?void 0:w.type.toLocaleLowerCase()))}else{let P=(g=(C=p?.filter)===null||C===void 0?void 0:C.event)===null||g===void 0?void 0:g.toLocaleLowerCase();return P==="*"||P===((x=t?.event)===null||x===void 0?void 0:x.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof f=="object"&&"ids"in f){let b=f.data,{schema:E,table:w,commit_timestamp:C,type:g,errors:x}=b;f=Object.assign(Object.assign({},{schema:E,table:w,commit_timestamp:C,eventType:g,new:{},old:{},errors:x}),this._getPayloadRecords(b))}p.callback(f,r)})}_isClosed(){return this.state===q.closed}_isJoined(){return this.state===q.joined}_isJoining(){return this.state===q.joining}_isLeaving(){return this.state===q.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(F.close,{},e)}_onError(e){this._on(F.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=q.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 un=()=>{},dn=typeof WebSocket<"u",je=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Ts,this.params={},this.timeout=Ut,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=un,this.conn=null,this.sendBuffer=[],this.serializer=new st,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(le(),pe)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${$t.websocket}`,this.httpEndpoint=Mt(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 ge(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(dn){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Tr(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Xr(Cs())).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 me.connecting:return ue.Connecting;case me.open:return ue.Open;case me.closing:return ue.Closing;default:return ue.Closed}}isConnected(){return this.connectionState()===ue.Open}channel(e,t={config:{}}){let r=new Ie(`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(F.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:xs}))}_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(F.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(As,"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=me.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var $e=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function I(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var Dt=class extends $e{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},it=class extends $e{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var hn=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(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},Nt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(le(),pe)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Os=()=>hn(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(le(),pe))).Response:Response});var Ue=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(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},xr=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),fn=(s,e)=>Ue(void 0,void 0,void 0,function*(){let t=yield Os();s instanceof t?s.json().then(r=>{e(new Dt(xr(r),s.status||500))}).catch(r=>{e(new it(xr(r),r))}):e(new it(xr(s),s))}),pn=(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 qt(s,e,t,r,i,n){return Ue(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,pn(e,r,i,n)).then(c=>{if(!c.ok)throw c;return r?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>fn(c,a))})})}function nt(s,e,t,r){return Ue(this,void 0,void 0,function*(){return qt(s,"GET",e,t,r)})}function Z(s,e,t,r,i){return Ue(this,void 0,void 0,function*(){return qt(s,"POST",e,r,i,t)})}function Ls(s,e,t,r,i){return Ue(this,void 0,void 0,function*(){return qt(s,"PUT",e,r,i,t)})}function Ht(s,e,t,r,i){return Ue(this,void 0,void 0,function*(){return qt(s,"DELETE",e,r,i,t)})}var B=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(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},mn={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Is={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ot=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=Nt(i)}uploadOrUpdate(e,t,r,i){return B(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Is),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),u=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),d=yield l.json();return l.ok?{data:{path:c,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(n){if(I(n))return{data:null,error:n};throw n}})}upload(e,t,r){return B(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return B(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,u=Object.assign({upsert:Is.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",u.cacheControl)):(c=r,l["cache-control"]=`max-age=${u.cacheControl}`,l["content-type"]=u.contentType);let d=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),f=yield d.json();return d.ok?{data:{path:n,fullPath:f.Key},error:null}:{data:null,error:f}}catch(c){if(I(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return B(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 Z(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 $e("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(I(r))return{data:null,error:r};throw r}})}update(e,t,r){return B(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return B(this,void 0,void 0,function*(){try{return{data:yield Z(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(I(i))return{data:null,error:i};throw i}})}copy(e,t,r){return B(this,void 0,void 0,function*(){try{return{data:{path:(yield Z(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(I(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return B(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield Z(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(I(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return B(this,void 0,void 0,function*(){try{let i=yield Z(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(I(i))return{data:null,error:i};throw i}})}download(e,t){return B(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 nt(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(I(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 u=i.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${u}`)}}}remove(e){return B(this,void 0,void 0,function*(){try{return{data:yield Ht(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(I(t))return{data:null,error:t};throw t}})}list(e,t,r){return B(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},mn),t),{prefix:e||""});return{data:yield Z(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(I(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 js="2.6.0";var $s={"X-Client-Info":`storage-js/${js}`};var Me=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(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},at=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},$s),t),this.fetch=Nt(r)}listBuckets(){return Me(this,void 0,void 0,function*(){try{return{data:yield nt(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(I(e))return{data:null,error:e};throw e}})}getBucket(e){return Me(this,void 0,void 0,function*(){try{return{data:yield nt(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(I(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Me(this,void 0,void 0,function*(){try{return{data:yield Z(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(I(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Me(this,void 0,void 0,function*(){try{return{data:yield Ls(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(I(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Me(this,void 0,void 0,function*(){try{return{data:yield Z(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(I(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Me(this,void 0,void 0,function*(){try{return{data:yield Ht(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(I(t))return{data:null,error:t};throw t}})}};var ct=class extends at{constructor(e,t={},r){super(e,t,r)}from(e){return new ot(this.url,this.headers,e,this.fetch)}};var Us="2.44.4";var lt="";typeof Deno<"u"?lt="deno":typeof document<"u"?lt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?lt="react-native":lt="node";var gn={"X-Client-Info":`supabase-js-${lt}/${Us}`},Ms={headers:gn},Ds={schema:"public"},Ns={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},qs={};le();var yn=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(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},_n=s=>{let e;return s?e=s:typeof fetch>"u"?e=ar:e=fetch,(...t)=>e(...t)},wn=()=>typeof Headers>"u"?cr:Headers,Hs=(s,e,t)=>{let r=_n(t),i=wn();return(n,o)=>yn(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:s,u=new i(o?.headers);return u.has("apikey")||u.set("apikey",s),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),r(n,Object.assign(Object.assign({},o),{headers:u}))})};function Fs(s){return s.replace(/\/$/,"")}function Ws(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:c,global:u}=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({},u),n)}}var Ft="2.64.4";var Bs="http://localhost:9999",Gs="supabase.auth.token";var zs={"X-Client-Info":`gotrue-js/${Ft}`},Ar=10;var ut="X-Supabase-Api-Version",Pr={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Js(s){return Math.round(Date.now()/1e3)+s}function Ks(){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 G=()=>typeof document<"u",_e={tested:!1,writable:!1},de=()=>{if(!G())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(_e.tested)return _e.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),_e.tested=!0,_e.writable=!0}catch{_e.tested=!0,_e.writable=!1}return _e.writable};function Wt(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 Bt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(le(),pe)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Vs=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",Rr=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},ht=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Gt=async(s,e)=>{await s.removeItem(e)};function vn(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,c,u,l=0;for(s=s.replace("-","+").replace("_","/");l<s.length;)o=e.indexOf(s.charAt(l++)),a=e.indexOf(s.charAt(l++)),c=e.indexOf(s.charAt(l++)),u=e.indexOf(s.charAt(l++)),r=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|u,t=t+String.fromCharCode(r),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),u!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var dt=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};dt.promiseConstructor=Promise;function Cr(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(vn(r))}async function Ys(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Qs(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 bn(s){return("0"+s.toString(16)).substr(-2)}function kn(){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,bn).join("")}async function Sn(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 En(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Tn(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 Sn(s);return En(t)}async function we(s,e,t=!1){let r=kn(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await Rr(s,`${e}-code-verifier`,i);let n=await Tn(r);return[n,r===n?"plain":"s256"]}var xn=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Xs(s){let e=s.headers.get(ut);if(!e||!e.match(xn))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var ft=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function _(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var zt=class extends ft{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function Zs(s){return _(s)&&s.name==="AuthApiError"}var De=class extends ft{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},ie=class extends ft{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},ee=class extends ie{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Ne=class extends ie{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},ve=class extends ie{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},be=class extends ie{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}}},pt=class extends ie{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}}},qe=class extends ie{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Jt(s){return _(s)&&s.name==="AuthRetryableFetchError"}var mt=class extends ie{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var An=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},ke=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Pn=[502,503,504];async function ei(s){var e;if(!Vs(s))throw new qe(ke(s),0);if(Pn.includes(s.status))throw new qe(ke(s),s.status);let t;try{t=await s.json()}catch(n){throw new De(ke(n),n)}let r,i=Xs(s);if(i&&i.getTime()>=Pr["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 mt(ke(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 mt(ke(t),s.status,t.weak_password.reasons);throw new zt(ke(t),s.status||500,r)}var Rn=(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 k(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[ut]||(n[ut]=Pr["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 Cn(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 Cn(s,e,t,r,i,n){let o=Rn(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(c){throw console.error(c),new qe(ke(c),0)}if(a.ok||await ei(a),r?.noResolveJson)return a;try{return await a.json()}catch(c){await ei(c)}}function ne(s){var e;let t=null;On(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Js(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=ne(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 te(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function ti(s){return{data:s,error:null}}function ri(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=An(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 si(s){return s}function On(s){return s.access_token&&s.refresh_token&&s.expires_in}var Ln=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},Se=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Bt(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await k(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(_(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await k(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:te})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Ln(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await k(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:ri,redirectTo:t?.redirectTo})}catch(t){if(_(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await k(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:te})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,c;try{let u={nextPage:null,lastPage:0,total:0},l=await k(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:si});if(l.error)throw l.error;let d=await l.json(),f=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(b=>{let E=parseInt(b.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse(b.split(";")[1].split("=")[1]);u[`${w}Page`]=E}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(_(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){try{return await k(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:te})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await k(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:te})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await k(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:te})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await k(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(_(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await k(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}};var ii={getItem:s=>de()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{de()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{de()&&globalThis.localStorage.removeItem(s)}};function Lr(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function ni(){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 Ee={debug:!!(globalThis&&de()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},gt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Kt=class extends gt{};async function Ir(s,e,t){Ee.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),Ee.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){Ee.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{Ee.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw Ee.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new Kt(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(Ee.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()}})}ni();var In={url:Bs,storageKey:Gs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:zs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},yt=30*1e3,oi=3;async function ai(s,e,t){return await t()}var Te=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&&G()&&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({},In),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 Se({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Bt(i.fetch),this.lock=i.lock||ai,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:G()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Ir:this.lock=ai,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:de()?this.storage=ii:(this.memoryStorage={},this.storage=Lr(this.memoryStorage)):(this.memoryStorage={},this.storage=Lr(this.memoryStorage)),G()&&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} (${Ft}) ${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=G()?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)?{error:e}:{error:new De("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await k(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:ne}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(_(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:l,password:d,options:f}=e,p=null,b=null;this.flowType==="pkce"&&([p,b]=await we(this.storage,this.storageKey)),n=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:l,password:d,data:(t=f?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:p,code_challenge_method:b},xform:ne})}else if("phone"in e){let{phone:l,password:d,options:f}=e;n=await k(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,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:ne})}else throw new ve("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,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(n){if(_(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 k(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 k(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 ve("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 Ne}:(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(_(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 ht(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await k(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:ne});return await Gt(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 Ne}:(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 k(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:ne}),{data:c,error:u}=a;return u?{data:{user:null,session:null},error:u}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Ne}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:u})}catch(t){if(_(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,u=null,l=null;this.flowType==="pkce"&&([u,l]=await we(this.storage,this.storageKey));let{error:d}=await k(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:u,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){let{phone:a,options:c}=e,{data:u,error:l}=await k(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:u?.message_id},error:l}}throw new ve("You must provide either an email or phone number.")}catch(a){if(_(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 k(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:ne});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,u=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:u,session:c},error:null}}catch(i){if(_(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 we(this.storage,this.storageKey)),await k(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:ti})}catch(n){if(_(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 ee;let{error:i}=await k(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))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 k(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 k(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 ve("You must provide either an email or phone number and a type")}catch(t){if(_(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 ht(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,u,l)=>(!o&&u==="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,u,l))})}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 k(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:te}):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 ee}:await k(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:te})})}catch(t){if(_(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 ee;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await we(this.storage,this.storageKey));let{data:u,error:l}=await k(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:te});if(l)throw l;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(_(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return Cr(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 ee;let t=Date.now()/1e3,r=t,i=!0,n=null,o=Cr(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(_(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 ee;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(_(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!G())throw new be("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new be("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new pt("Not a valid PKCE flow url.");let t=Wt(window.location.href);if(e){if(!t.code)throw new pt("No code detected.");let{data:g,error:x}=await this._exchangeCodeForSession(t.code);if(x)throw x;let P=new URL(window.location.href);return P.searchParams.delete("code"),window.history.replaceState(window.history.state,"",P.toString()),{data:{session:g.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new be(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:u}=t;if(!n||!a||!o||!u)throw new be("No session defined in URL");let l=Math.round(Date.now()/1e3),d=parseInt(a),f=l+d;c&&(f=parseInt(c));let p=f-l;p*1e3<=yt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${d}s`);let b=f-d;l-b>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",b,f,l):l-b<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",b,f,l);let{data:E,error:w}=await this._getUser(n);if(w)throw w;let C={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:d,expires_at:f,refresh_token:o,token_type:u,user:E.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:C,redirectType:t.type},error:null}}catch(t){if(_(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Wt(window.location.href);return!!(G()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Wt(window.location.href),t=await ht(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&&!(Zs(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Gt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Ks(),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 we(this.storage,this.storageKey,!0));try{return await k(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(_(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(_(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,u,l;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 k(this.fetch,"GET",p,{headers:this.headers,jwt:(l=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return G()&&!(!((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(_(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 k(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(_(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 Qs(async i=>(i>0&&await Ys(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await k(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ne})),(i,n)=>{let o=200*Math.pow(2,i);return n&&Jt(n)&&Date.now()+o-r<yt})}catch(r){if(this._debug(t,"error",r),_(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),G()&&!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 ht(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+Ar;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Ar}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),Jt(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 ee;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new dt;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new ee;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),_(n)){let o={session:null,error:n};return Jt(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 Rr(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Gt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&G()&&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(),yt);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)/yt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${yt}ms, refresh threshold is ${oi} ticks`),i<=oi&&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 gt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!G()||!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 we(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 k(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(_(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 k(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(_(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 k(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(_(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 k(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(_(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 l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};Te.nextInstanceID=0;var jn=Te,jr=jn;var Vt=class extends jr{constructor(e){super(e)}};var $n=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(l){try{u(r.next(l))}catch(d){o(d)}}function c(l){try{u(r.throw(l))}catch(d){o(d)}}function u(l){l.done?n(l.value):i(l.value).then(a,c)}u((r=r.apply(s,e||[])).next())})},_t=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=Fs(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`,u={db:Ds,realtime:qs,auth:Object.assign(Object.assign({},Ns),{storageKey:c}),global:Ms},l=Ws(r??{},u);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=Hs(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new Ss(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Ve(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ct(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 $n(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,u){var l;let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Vt({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:u,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new je(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var ci=(s,e,t)=>new _t(s,e,t);var oe={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Un=s=>{try{let e=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(s.length/4)*4,"=");return JSON.parse(atob(e))}catch{return null}},Yt=s=>{let[e,t]=s.split(".");return!e||!t?null:Un(t)},li=s=>{let e=Yt(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 Mn="https://api.workos.com",Dn=60,He=(s,e)=>typeof s[e]=="string"?s[e]:void 0,ui=(s,e,t)=>{let r=Yt(s);if(!r)return null;let i=He(r,"urn:wispr:user_external_id")??He(r,"sub"),n=t?.email??He(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}},Nn=async(s,e,t,r)=>{let i=t?.startsWith("https://")?t.replace(/\/$/,""):Mn,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()},di=async(s,e)=>{let t=Yt(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=He(t,"client_id");if(i-r<Dn&&n){let c=await Nn(e,n,He(t,"iss"),He(t,"org_id")),u=ui(c.access_token,c.refresh_token,c.user);if(!u)throw new Error("WorkOS refresh returned an invalid access token");return u}if(i<=r)throw new Error("WorkOS session expired");let a=ui(s,e);if(!a)throw new Error("Invalid WorkOS access token");return a};var wt=class{constructor(){this.sessionData=null;this.supabase=ci(oe.supaBaseUrl,oe.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||oe.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||oe.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||oe.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(li(t)==="workos"){this.sessionData=await di(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||oe.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=o?.deviceCode,c=a&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?a:void 0,u=await X.signUpWithCaptcha({email:e,password:t,full_name:r,captcha_token:n,device_code:c,redirect_url:i||oe.redirectUri,workos_capable:o?.workosCapable||void 0});return console.log("Signup request completed"),u}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 X.signInWithCaptcha({email:e,password:t,captcha_token:r,provision:i?.provision??!1,workos_capable:i?.workosCapable||void 0});if(ze(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 X.resendVerificationEmailCaptcha({email:e,captcha_token:r,redirect_url:t||oe.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 re=null;function Qt(s,e=30,t){re&&(clearInterval(re),re=null);let r=e;s.style.pointerEvents="none",s.textContent=`Resend (${r}s)`,re=setInterval(()=>{r=r-1,s.textContent=r>0?`Resend (${r}s)`:"Resend email",r===0&&(s.style.pointerEvents="auto",re&&(clearInterval(re),re=null),t&&t())},1e3)}function $r(){re&&(clearInterval(re),re=null)}var hi=/^[\p{L}\p{M}\s\-'.]+$/u;function qn(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":hi.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 Xt(s,e){let t=s.trim();return t?/\d/.test(t)?"Your name can't include numbers":hi.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 Ur(s,e,t){let r="full-name-match-error",i=c=>{e.classList.add("error"),t?.classList.add("pointer-events-none");let u=document.getElementById(r);u||(u=document.createElement("div"),u.id=r,u.style.fontSize="0.875rem",e.insertAdjacentElement("afterend",u)),u.textContent=c},n=()=>{e.classList.remove("error"),t?.classList.remove("pointer-events-none"),document.getElementById(r)?.remove()},o=()=>{let c=qn(e.value,s.value);c?i(c):n()},a=()=>{let c=Xt(e.value,s.value);c?i(c):n()};s.addEventListener("input",o),e.addEventListener("input",o),e.addEventListener("blur",a)}var fi="password-rejection-error",Mr=s=>s instanceof K?s.passwordRejectionMessage:null,Fe=s=>{s.classList.remove("error"),document.getElementById(fi)?.remove()},Zt=(s,e)=>{if(Fe(s),e.length===0)return;s.classList.add("error");let t=document.createElement("div");t.id=fi,t.style.fontSize="0.875rem",t.textContent=e,s.insertAdjacentElement("afterend",t)};var Hn="wisprjam.com",Fn="wispr.ai";var Wn=s=>s.trim().toLowerCase().split("@")[1]??"",pi=s=>{let e=Wn(s);return e===Hn||e===Fn};var mi="/granola-switch",Dr="granola-switch",gi=s=>{let e=s.get("months");return e==="1"||e==="2"||e==="3"?e:null};var Bn="https://api.wisprflow.ai",Gn="workos_enabled_webflow";window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=localStorage.getItem("checkout_debug");if(s){try{let h=JSON.parse(s);J("checkout_debug",{...h,reported_from:"get_started",ms_since_error:Date.now()-(h.timestamp??Date.now())})}catch{}localStorage.removeItem("checkout_debug")}let e=!1,t=setTimeout(()=>{e||(document.body.style.visibility="visible")},4e3),r=new wt,i=null,n=()=>{i?.clear()},{accessToken:o,refreshToken:a}=os(),c=document.querySelector("#email-form"),u=document.querySelector("#email-input"),l=document.querySelector("#password-input"),d=document.querySelector("#full-name"),f=document.querySelector("#google-login"),p=document.querySelector("#apple-login"),b=document.querySelector("#microsoft-login"),E=document.querySelector("#sso-login"),w=document.querySelector("[sso-login-div]"),C=document.querySelector("#sso-email"),g=document.querySelector("#sso-signup-form"),x=document.querySelector('[sso-login="go-back"]'),P=document.querySelector(".gs-hero_form-block"),j;(A=>(A.EMAIL_INPUT="email_input",A.LOGIN="login",A.SIGNUP="signup",A.OAUTH_USER="oauth_user",A.UNVERIFIED_EMAIL="unverified_email"))(j||(j={}));let V="email_input",$=document.querySelector("[email-element]"),se=document.querySelector("[different-provider]"),Nr=document.querySelector("[different-provider-name]"),qr=document.querySelector("[different-provider-reset]"),xe=document.querySelector("[email-signup-success]"),v=document.querySelector("[email-signup-error]"),T=document.querySelector("[error-message]"),Hr=document.querySelector("[verification-email]"),We=document.querySelector("[email-signup-retry]"),Fr=document.querySelector("[email-signup-reset]"),Ae=document.querySelector("[scim-div]"),Wr=document.querySelector("[scim-reset]"),W=document.querySelector("[forgot-password]"),vt=document.querySelector("[forgot-password-success]"),Br=document.querySelector("[forgot-password-email]"),ae=document.querySelector("[unverified-email]"),Gr=document.querySelector("[unverified-email-address]"),Y=document.querySelector("[resend-verification-email]"),zr=document.querySelector("[unverified-email-reset]"),yi=localStorage.getItem("email"),Jr=localStorage.getItem("last_authed_provider");Jr&&{google:f,apple:p,microsoft:b,sso:E,email:u}[Jr]?.classList.add("last-used");let he=new URLSearchParams(window.location.search),Kr=he.get("redirect"),bt=he.get("error"),zn=he.get("code"),_i=Kr===Dr?mi:"/downloads",H=`${window.location.origin}${_i}`,Pe=new URLSearchParams(he);if(Pe.delete("redirect"),Pe.delete("months"),Kr===Dr){Pe.set("auth_return","1");let h=gi(he);h&&Pe.set("months",h)}if(Pe.toString()&&(H+=`?${Pe.toString()}`),bt){let h=bt==="account_unsupported"?"This account is not supported. Try signing in with another account.":"Unable to complete authentication. Please try again.";J("get_started_oauth_error",{error:bt,error_code:he.get("error_code")??void 0,error_description:he.get("error_description")??void 0,surface:"get-started"}),v&&(v.style.display="block"),T&&(T.textContent=h),document.body.style.visibility="visible"}cs({includeError:!!bt});let wi=()=>{try{let h=document.cookie.split("; ");for(let m of h){let y=m.indexOf("=");if(y===-1||m.slice(0,y)!=="wispr_auth")continue;let L=m.slice(y+1),A=decodeURIComponent(L);return JSON.parse(A)}return null}catch{return null}};if(o&&a)try{r.setCookies(o,a),await r.checkAndSetSession(),r.sessionData&&r.setCookies(r.sessionData.access_token,r.sessionData.refresh_token);let h=r.sessionData?.user.email;localStorage.setItem("email",h),e=!0,clearTimeout(t),window.location.href=H}catch(h){console.error("Error during session setup:",h),document.body.style.visibility="visible"}else{let h=wi();if(h?.access_token&&h?.refresh_token)try{r.setCookies(h.access_token,h.refresh_token),await r.checkAndSetSession(),r.sessionData&&r.setCookies(r.sessionData.access_token,r.sessionData.refresh_token);let m=r.sessionData?.user.email,y=r.sessionData?.user.app_metadata.provider||"typing_test";localStorage.setItem("email",m),localStorage.setItem("signin_provider",y),e=!0,clearTimeout(t),window.location.href=H}catch(m){console.error("Error authenticating from typing test session:",m),h.email&&(u.value=h.email),document.body.style.visibility="visible"}else h?.email?(u.value=h.email,document.body.style.visibility="visible"):(yi&&localStorage.removeItem("email"),document.body.style.visibility="visible")}let kt=async(h,m)=>{try{n(),localStorage.setItem("signin_provider",h);let y=window.posthog?.getFeatureFlag?.(Gn)===!0;if(J("get_started_oauth_click",{provider:y?"workos":h,idp:h,surface:"get-started",workos_enabled_webflow:y}),h==="sso"||y){let S=y?`authkit/${h}/sign_in`:`${h}/sign_in`,L=new URL(`${Bn}/${S}`);L.searchParams.set("source",H),m&&L.searchParams.set("email",m),window.location.href=L.toString();return}h==="google"?await r.signInWithGoogle(H):h==="apple"?await r.signInWithApple(H):await r.signInWithMicrosoft(H)}catch(y){console.error("Error during sign-in:",y)}};f.addEventListener("click",async()=>{await kt("google")}),p.addEventListener("click",async()=>{await kt("apple")}),b.addEventListener("click",async()=>{await kt("microsoft")}),E&&(E.style.display="flex",E.addEventListener("click",h=>{h.preventDefault(),w&&(w.style.display="block"),P&&(P.style.display="none"),C?.focus()})),x&&x.addEventListener("click",h=>{h.preventDefault(),w&&(w.style.display="none"),P&&(P.style.display="block"),C&&(C.value="",C.blur())}),g&&g.addEventListener("submit",h=>{h.preventDefault(),h.stopPropagation();let m=N(C?.value||"");m&&kt("sso",m)});let Be=()=>{n(),se&&(se.style.display="none"),xe&&(xe.style.display="none"),v&&(v.style.display="none"),ae&&(ae.style.display="none"),Ae&&(Ae.style.display="none"),W&&(W.style.display="none"),vt&&(vt.style.display="none"),fe();let h=document.querySelector(".gs-hero_form-block");h&&(h.style.display="block"),$&&($.style.display="flex"),u.value="",u.removeAttribute("readonly"),u.classList.remove("disabled"),l.value="",l.style.display="none",l.removeAttribute("required"),Fe(l),d.value="",d.style.display="none",d.removeAttribute("required");let m=document.querySelector("[captcha-embed]"),y=document.querySelector("#h-captcha-container");m&&(m.style.display="none"),y&&(y.style.display="none"),M()?.reset(),V="email_input",u.focus()},St=()=>{$&&($.style.display="flex"),u.setAttribute("readonly","true"),u.classList.add("disabled"),l.style.display="block",l.setAttribute("required","true"),l.focus(),d.style.display="none",d.removeAttribute("required");let h=document.querySelector("[captcha-embed]"),m=document.querySelector("#h-captcha-container");h&&(h.style.display="block"),m&&(m.style.display="block"),W&&(W.style.display="block",W.onclick=async()=>{let y=u.value,S=W.textContent||"";try{let L=M();if(!L)throw new Error("Verification system not loaded. Please refresh the page.");W.style.pointerEvents="none",W.textContent="Sending...";let A=await L.execute({async:!0}),U=typeof A=="string"?A:A.response;if(!U)throw new Error("Verification cancelled");await X.requestPasswordReset(y,U),L.reset(),$&&($.style.display="none"),W&&(W.style.display="none"),vt&&(vt.style.display="block"),Br&&(Br.textContent=y)}catch(L){console.error("\u274C Error sending password reset email:",L),W.textContent=S,W.style.pointerEvents="auto",M()?.reset(),v&&(v.style.display="block",T&&(T.textContent=L instanceof Error?L.message:"Failed to send reset email"))}}),V="login",console.log("\u2705 Existing user detected - showing login form")},Vr=()=>{u.setAttribute("readonly","true"),u.classList.add("disabled"),l.style.display="block",l.setAttribute("required","true"),d.style.display="block",d.setAttribute("required","true"),l.focus();let h=document.querySelector("[captcha-embed]"),m=document.querySelector("#h-captcha-container");h&&(h.style.display="block"),m&&(m.style.display="block"),V="signup",console.log("\u2705 New user detected - showing signup form")},Yr=()=>{let h=document.querySelector(".gs-hero_form-block");h&&(h.style.display="none"),Ae&&(Ae.style.display="block"),Wr&&(Wr.onclick=()=>{Ae&&(Ae.style.display="none"),h&&(h.style.display="block"),Be()})},er=h=>{n();let m=ir(h);$&&($.style.display="none"),se&&(se.style.display="block"),Nr&&(Nr.textContent=m),qr&&(qr.onclick=()=>{se&&(se.style.display="none"),Be()}),V="oauth_user"};i=or({client:r,redirectUrl:H,isWorkosCapable:()=>!0,beforeShow:()=>{$&&($.style.display="none"),ae&&(ae.style.display="none")},onAuthenticated:async h=>{n(),r.setCookies(h.access_token,h.refresh_token),localStorage.setItem("email",h.email),localStorage.setItem("user_id",h.user_id),localStorage.setItem("signin_provider","email"),e=!0,clearTimeout(t),window.location.href=H},onMissingChallenge:St,onReset:Be});let vi=h=>{$&&($.style.display="none"),ae&&(ae.style.display="block"),Gr&&(Gr.textContent=h),Y&&(Y.onclick=async()=>{let m=Y.textContent||"";try{Y.textContent="Verifying...",Y.style.pointerEvents="none";let y=await Je();Y.textContent="Sending...",await r.resendVerificationEmail(h,H,y),Y.textContent="Verification email resent! \u2705",Y.style.textDecoration="none",v&&(v.style.display="none")}catch(y){Y.textContent=m,Y.style.pointerEvents="auto",v&&(v.style.display="block"),T&&(T.textContent=Ce(y,"Unable to resend verification."))}finally{M()?.reset()}}),zr&&(zr.onclick=()=>{ae&&(ae.style.display="none"),Be()}),V="unverified_email",console.log("\u26A0\uFE0F Unverified user detected - showing resend verification UI")},tr=h=>nr(h,{showSso:()=>er("workos"),showScim:Yr,showLogin:St,showError:m=>{v&&(v.style.display="block"),T&&(T.textContent=m)}}),bi=async(h,m)=>{let y=m.value;m.classList.add("loading"),m.value="";try{let S=await X.checkUserStatus(h);console.log("User status check:",S),m.classList.remove("loading"),m.value=y,!S.exists&&S.scim_managed?Yr():S.enforce_sso?er("workos"):S.exists&&S.provider&&S.provider!=="email"&&S.provider!=="workos"?er(S.provider):S.exists&&S.provider==="workos"?St():S.exists&&S.provider==="email"&&!S.verified?vi(h):S.exists&&S.provider==="email"?St():Vr()}catch(S){console.error("\u274C Error checking user status:",S),m.classList.remove("loading"),m.value=y,tr(S)||Vr()}},ki=async(h,m,y,S)=>{if(!m||m.length<8){v&&(v.style.display="block",T&&(T.textContent="Password must be at least 8 characters"));return}let L=M()?.getResponse()||"";if(!L){v&&(v.style.display="block",T&&(T.textContent="Please complete the verification"));return}y.classList.add("loading"),y.value="";try{let A=pi(h),U=await r.signInWithPassword(h,m,L,{workosCapable:A,provision:!1});if(U.kind==="otp"){if(!A)throw new Error("OTP challenge returned to a client that is not WorkOS-capable");let z={pendingAuthenticationToken:U.challenge.pending_authentication_token,email:N(U.challenge.email||h)};M()?.reset(),y.classList.remove("loading"),y.value=S,i?.show(z);return}r.setCookies(U.accessToken,U.refreshToken),localStorage.setItem("email",h),e=!0,clearTimeout(t),window.location.href=H}catch(A){M()?.reset(),y.classList.remove("loading"),y.value=S,!tr(A)&&v&&(v.style.display="block",T&&(T.textContent=Ce(A,"Unable to sign in. Please try again.")))}},Si=async(h,m,y,S,L)=>{if(!m||m.length<8){v&&(v.style.display="block",T&&(T.textContent="Password must be at least 8 characters"));return}if(m.trim().toLowerCase()===h.trim().toLowerCase()){Zt(l,"Password can't be the same as your email address.");return}if(!y||y.trim().length<2){v&&(v.style.display="block",T&&(T.textContent="Please enter your full name"));return}let A=Xt(y,m);if(A){v&&(v.style.display="block",T&&(T.textContent=A));return}let U=M()?.getResponse()||"";if(!U){v&&(v.style.display="block",T&&(T.textContent="Please complete the verification"));return}S.classList.add("loading"),S.value="";try{let z=await r.signUpWithPassword(h,m,y,H,U,{workosCapable:!0});if(M()?.reset(),S.classList.remove("loading"),S.value=L,$&&($.style.display="none"),v&&(v.style.display="none"),ze(z)){let ce={pendingAuthenticationToken:z.pending_authentication_token,email:N(z.email||h)};i?.show(ce);return}xe&&(xe.style.display="block"),Hr&&(Hr.textContent=h),We&&(Qt(We,30),We.onclick=async()=>{if(We.style.pointerEvents!=="none")try{let ce=await Je();await r.resendVerificationEmail(h,H,ce,{workosCapable:!0}),Qt(We,30)}catch(ce){v&&(v.style.display="block"),T&&(T.textContent=Ce(ce,"Unable to resend verification. Please try again."))}finally{M()?.reset()}}),Fr&&(Fr.onclick=()=>{xe&&(xe.style.display="none"),$r(),Be()})}catch(z){S.classList.remove("loading"),S.value=L,M()?.reset();let ce=Mr(z);ce?Zt(l,ce):!tr(z)&&v&&(v.style.display="block",T&&(T.textContent=Ce(z,"Unable to create the account. Please try again.")))}};Ur(l,d,c.querySelector('[type="submit"]')),l.addEventListener("input",()=>Fe(l)),c.addEventListener("submit",async h=>{h.stopPropagation(),h.preventDefault();let m=N(u.value);u.value=m;let y=l?.value||"",S=d?.value||"";if(!m||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m)){console.error("\u274C Email invalid"),v&&(v.style.display="block",T&&(T.textContent="Please enter a valid email address"));return}v&&(v.style.display="none"),T&&(T.textContent=""),Fe(l);let A=c.querySelector('[type="submit"]'),U=A?.value||"";localStorage.setItem("signin_provider","email");try{V==="email_input"?await bi(m,A):V==="login"?await ki(m,y,A,U):V==="signup"&&await Si(m,y,S,A,U)}catch(z){console.error("\u274C Signup error:",z),A&&(A.classList.remove("loading"),A.value=U),v&&(v.style.display="block")}})});})();
|