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