@tanay-wispr/webflow-package 6.7.11 → 6.7.13

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