@tanay-wispr/webflow-package 6.6.5 → 6.6.7

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.
Files changed (2) hide show
  1. package/dist/login.js +1 -1
  2. package/package.json +1 -1
package/dist/login.js CHANGED
@@ -1 +1 @@
1
- "use strict";(()=>{var _r=Object.create;var at=Object.defineProperty;var yr=Object.getOwnPropertyDescriptor;var vr=Object.getOwnPropertyNames;var wr=Object.getPrototypeOf,br=Object.prototype.hasOwnProperty;var kr=(r,e)=>()=>(r&&(e=r(r=0)),e);var W=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Sr=(r,e)=>{for(var t in e)at(r,t,{get:e[t],enumerable:!0})},cs=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of vr(e))!br.call(r,i)&&i!==t&&at(r,i,{get:()=>e[i],enumerable:!(s=yr(e,i))||s.enumerable});return r};var ls=(r,e,t)=>(t=r!=null?_r(wr(r)):{},cs(e||!r||!r.__esModule?at(t,"default",{value:r,enumerable:!0}):t,r)),Er=r=>cs(at({},"__esModule",{value:!0}),r);var ce={};Sr(ce,{Headers:()=>Lt,Request:()=>Ar,Response:()=>Pr,default:()=>It,fetch:()=>xr});var Tr,we,xr,It,Lt,Ar,Pr,re=kr(()=>{"use strict";Tr=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=Tr(),xr=we.fetch,It=we.fetch.bind(we),Lt=we.Headers,Ar=we.Request,Pr=we.Response});var fs=W(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});var $t=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};jt.default=$t});var Dt=W(Ue=>{"use strict";var ps=Ue&&Ue.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ue,"__esModule",{value:!0});var Rr=ps((re(),Er(ce))),Cr=ps(fs()),Ut=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=Rr.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 h=null,l=null,u=null,d=n.status,p=n.statusText;if(n.ok){if(this.method!=="HEAD"){let m=await n.text();m===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=m:l=JSON.parse(m))}let y=(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("/");y&&f&&f.length>1&&(u=parseInt(f[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(h={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,u=null,d=406,p="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let y=await n.text();try{h=JSON.parse(y),Array.isArray(h)&&n.status===404&&(l=[],h=null,d=200,p="OK")}catch{n.status===404&&y===""?(d=204,p="No Content"):h={message:y}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,p="OK"),h&&this.shouldThrowOnError)throw new Cr.default(h)}return{error:h,data:l,count:u,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=Ut});var Mt=W(De=>{"use strict";var Ir=De&&De.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(De,"__esModule",{value:!0});var Lr=Ir(Dt()),Nt=class extends Lr.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("|"),h=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};De.default=Nt});var dt=W(Ne=>{"use strict";var $r=Ne&&Ne.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ne,"__esModule",{value:!0});var jr=$r(Mt()),qt=class extends jr.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=qt});var Ht=W(qe=>{"use strict";var Ur=qe&&qe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(qe,"__esModule",{value:!0});var Me=Ur(dt()),Ft=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((h,l)=>h.concat(Object.keys(l)),[]);if(c.length>0){let h=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",h.join(","))}}return new 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=Ft});var gs=W(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.version=void 0;ft.version="0.0.0-automated"});var ms=W(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.DEFAULT_HEADERS=void 0;var Dr=gs();pt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Dr.version}`}});var ys=W(Fe=>{"use strict";var _s=Fe&&Fe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fe,"__esModule",{value:!0});var Nr=_s(Ht()),Mr=_s(dt()),qr=ms(),Bt=class r{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},qr.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new Nr.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,u])=>u!==void 0).map(([l,u])=>[l,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([l,u])=>{a.searchParams.append(l,u)})):(o="POST",c=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new Mr.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};Fe.default=Bt});var Es=W(U=>{"use strict";var He=U&&U.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(U,"__esModule",{value:!0});U.PostgrestBuilder=U.PostgrestTransformBuilder=U.PostgrestFilterBuilder=U.PostgrestQueryBuilder=U.PostgrestClient=void 0;var vs=He(ys());U.PostgrestClient=vs.default;var ws=He(Ht());U.PostgrestQueryBuilder=ws.default;var bs=He(dt());U.PostgrestFilterBuilder=bs.default;var ks=He(Mt());U.PostgrestTransformBuilder=ks.default;var Ss=He(Dt());U.PostgrestBuilder=Ss.default;U.default={PostgrestClient:vs.default,PostgrestQueryBuilder:ws.default,PostgrestFilterBuilder:bs.default,PostgrestTransformBuilder:ks.default,PostgrestBuilder:Ss.default}});var Ls=W((nn,Is)=>{"use strict";Is.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var j="https://api.wisprflow.ai",Ct=class{static async signupUser(e){try{let t=`${j}/signup`,i=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=i&&i.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${j}/signup_raw_email`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Adding raw user failed with status ${t.status}`);return console.log("Added raw user successfully"),await t.json()}catch(t){throw console.error("Error during raw user signup:",t),t}}static async addToWaitlist(e){try{let t=await fetch(`${j}/add_to_waitlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying waitlist failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async applyReferralCode(e){try{let t=await fetch(`${j}/api/v1/referral/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying referral code failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async associateAppSumoLicense(e){try{let t=await fetch(`${j}/app_sumo/associate_license_key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}static async checkUserStatus(e){return await(await fetch(`${j}/user_status?email=${encodeURIComponent(e)}`)).json()}static async requestPasswordReset(e,t){let s=await fetch(`${j}/email/request-reset-password-captcha`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email: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(`${j}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${j}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s){let i=`${j}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(i+=`&currency=${s}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${j}/api/v1/referral/download-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:e,recipient_email:t})})}static async getAndroidWaitlistStats(e){return await fetch(`${j}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${j}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${j}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,s){let i=new FormData;return i.append("screenshot",e),await fetch(`${j}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:s})}};function hs(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}function us(r){return r==="azure"?"Microsoft":r==="workos"?"SSO":r.charAt(0).toUpperCase()+r.slice(1)}var Le=Ct;var ds=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}},ct=class extends $e{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},lt=class extends $e{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},ht=class extends $e{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},ut;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(ut||(ut={}));var Or=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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},je=class{constructor(e,{headers:t={},customFetch:s,region:i=ut.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=ds(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Or(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let h;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData<"u"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:h}).catch(b=>{throw new ct(b)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new lt(l);if(!l.ok)throw new ht(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 Ts=ls(Es(),1),{PostgrestClient:xs,PostgrestQueryBuilder:Mi,PostgrestFilterBuilder:qi,PostgrestTransformBuilder:Fi,PostgrestBuilder:Hi}=Ts.default;var As="2.10.2";var Ps={"X-Client-Info":`realtime-js/${As}`},Os="1.0.0",mt=1e4,Rs=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 q;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(q||(q={}));var H;(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"})(H||(H={}));var gt;(function(r){r.websocket="websocket"})(gt||(gt={}));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 h=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:h}}};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 E;(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"})(E||(E={}));var Gt=(r,e,t={})=>{var s;let i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Fr(o,r,e,i),n),{})},Fr=(r,e,t,s)=>{let i=e.find(a=>a.name===r),n=i?.type,o=t[r];return n&&!s.includes(n)?Cs(n,o):zt(o)},Cs=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return Gr(e,t)}switch(r){case E.bool:return Hr(e);case E.float4:case E.float8:case E.int2:case E.int4:case E.int8:case E.numeric:case E.oid:return Br(e);case E.json:case E.jsonb:return zr(e);case E.timestamp:return Jr(e);case E.abstime:case E.date:case E.daterange:case E.int4range:case E.int8range:case E.money:case E.reltime:case E.text:case E.time:case E.timestamptz:case E.timetz:case E.tsrange:case E.tstzrange:return zt(e);default:return zt(e)}},zt=r=>r,Hr=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},Br=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},zr=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},Gr=(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=>Cs(e,a))}return r},Jr=r=>typeof r=="string"?r.replace(" ","T"):r,_t=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var ue=class{constructor(e,t,s={},i=mt){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 Jt;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(Jt||(Jt={}));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,(h,l)=>{o[h]||(c[h]=l)}),this.map(o,(h,l)=>{let u=n[h];if(u){let d=l.map(f=>f.presence_ref),p=u.map(f=>f.presence_ref),b=l.filter(f=>p.indexOf(f.presence_ref)<0),y=u.filter(f=>d.indexOf(f.presence_ref)<0);b.length>0&&(a[h]=b),y.length>0&&(c[h]=y)}else a[h]=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 h;let l=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(c),l.length>0){let u=e[a].map(p=>p.presence_ref),d=l.filter(p=>u.indexOf(p.presence_ref)<0);e[a].unshift(...d)}s(a,l,c)}),this.map(o,(a,c)=>{let h=e[a];if(!h)return;let l=c.map(u=>u.presence_ref);h=h.filter(u=>l.indexOf(u.presence_ref)<0),e[a]=h,i(a,h,c),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(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 Wt;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(Wt||(Wt={}));var Kt;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(Kt||(Kt={}));var Vt;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Vt||(Vt={}));var ke=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=q.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new ue(this,H.join,this.params,this.timeout),this.rejoinTimer=new he(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=q.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=q.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=q.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=q.errored,this.rejoinTimer.scheduleTimeout())}),this._on(H.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new be(this),this.broadcastEndpointURL=_t(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={},h={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:h},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,p=(u=d?.length)!==null&&u!==void 0?u:0,b=[];for(let y=0;y<p;y++){let f=d[y],{filter:{event:m,schema:D,table:A,filter:P}}=f,x=l&&l[y];if(x&&x.event===m&&x.schema===D&&x.table===A&&x.filter===P)b.push(Object.assign(Object.assign({},f),{id:x.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=b,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),h.receive("ok",()=>n("ok")),h.receive("error",()=>n("error")),h.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=q.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(H.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let i=new ue(this,H.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 ue(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:h,join:l}=H;if(s&&[a,c,h,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 b,y,f;return((b=p.filter)===null||b===void 0?void 0:b.event)==="*"||((f=(y=p.filter)===null||y===void 0?void 0:y.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 b,y,f,m,D,A;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){let P=p.id,x=(b=p.filter)===null||b===void 0?void 0:b.event;return P&&((y=t.ids)===null||y===void 0?void 0:y.includes(P))&&(x==="*"||x?.toLocaleLowerCase()===((f=t.data)===null||f===void 0?void 0:f.type.toLocaleLowerCase()))}else{let P=(D=(m=p?.filter)===null||m===void 0?void 0:m.event)===null||D===void 0?void 0:D.toLocaleLowerCase();return P==="*"||P===((A=t?.event)===null||A===void 0?void 0:A.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===o}).map(p=>{if(typeof d=="object"&&"ids"in d){let b=d.data,{schema:y,table:f,commit_timestamp:m,type:D,errors:A}=b;d=Object.assign(Object.assign({},{schema:y,table:f,commit_timestamp:m,eventType:D,new:{},old:{},errors:A}),this._getPayloadRecords(b))}p.callback(d,s)})}_isClosed(){return this.state===q.closed}_isJoined(){return this.state===q.joined}_isJoining(){return this.state===q.joining}_isLeaving(){return this.state===q.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:s};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&r.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(H.close,{},e)}_onError(e){this._on(H.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=q.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Gt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Gt(e.columns,e.old_record)),t}};var Kr=()=>{},Vr=typeof WebSocket<"u",Se=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Ps,this.params={},this.timeout=mt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Kr,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}/${gt.websocket}`,this.httpEndpoint=_t(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(Vr){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Yt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>ls(Ls())).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(H.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:Os}))}_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(H.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(Rs,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Yt=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 C(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var yt=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 Yr=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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},vt=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)},$s=()=>Yr(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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Qt=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Qr=(r,e)=>Te(void 0,void 0,void 0,function*(){let t=yield $s();r instanceof t?r.json().then(s=>{e(new yt(Qt(s),r.status||500))}).catch(s=>{e(new ze(Qt(s),s))}):e(new ze(Qt(r),r))}),Xr=(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 wt(r,e,t,s,i,n){return Te(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,Xr(e,s,i,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Qr(c,a))})})}function Ge(r,e,t,s){return Te(this,void 0,void 0,function*(){return wt(r,"GET",e,t,s)})}function K(r,e,t,s,i){return Te(this,void 0,void 0,function*(){return wt(r,"POST",e,s,i,t)})}function js(r,e,t,s,i){return Te(this,void 0,void 0,function*(){return wt(r,"PUT",e,s,i,t)})}function bt(r,e,t,s,i){return Te(this,void 0,void 0,function*(){return wt(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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Zr={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Us={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=vt(i)}uploadOrUpdate(e,t,s,i){return B(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Us),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&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),h=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield l.json();return l.ok?{data:{path:c,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(C(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,h=Object.assign({upsert:Us.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",h.cacheControl)):(c=s,l["cache-control"]=`max-age=${h.cacheControl}`,l["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(C(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 K(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(C(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 K(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(C(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 K(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(C(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 K(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(C(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return B(this,void 0,void 0,function*(){try{let i=yield K(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=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(C(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(C(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 h=i.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${h}`)}}}remove(e){return B(this,void 0,void 0,function*(){try{return{data:yield bt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(C(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({},Zr),t),{prefix:e||""});return{data:yield K(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if(C(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 Ds="2.6.0";var Ns={"X-Client-Info":`storage-js/${Ds}`};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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},We=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},Ns),t),this.fetch=vt(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(C(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(C(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 K(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(C(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return xe(this,void 0,void 0,function*(){try{return{data:yield js(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(C(s))return{data:null,error:s};throw s}})}emptyBucket(e){return xe(this,void 0,void 0,function*(){try{return{data:yield K(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(C(t))return{data:null,error:t};throw t}})}deleteBucket(e){return xe(this,void 0,void 0,function*(){try{return{data:yield bt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(C(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 Ms="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 ei={"X-Client-Info":`supabase-js-${Ve}/${Ms}`},qs={headers:ei},Fs={schema:"public"},Hs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Bs={};re();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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},si=r=>{let e;return r?e=r:typeof fetch>"u"?e=It:e=fetch,(...t)=>e(...t)},ri=()=>typeof Headers>"u"?Lt:Headers,zs=(r,e,t)=>{let s=si(t),i=ri();return(n,o)=>ti(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,h=new i(o?.headers);return h.has("apikey")||h.set("apikey",r),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:h}))})};function Gs(r){return r.replace(/\/$/,"")}function Js(r,e){let{db:t,auth:s,realtime:i,global:n}=r,{db:o,auth:a,realtime:c,global:h}=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({},h),n)}}var kt="2.64.4";var Ws="http://localhost:9999",Ks="supabase.auth.token";var Vs={"X-Client-Info":`gotrue-js/${kt}`},Xt=10;var Ye="X-Supabase-Api-Version",Zt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Ys(r){return Math.round(Date.now()/1e3)+r}function Qs(){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 z=()=>typeof document<"u",de={tested:!1,writable:!1},ne=()=>{if(!z())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 St(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 Et=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)},Xs=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",es=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}},Tt=async(r,e)=>{await r.removeItem(e)};function ii(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,i,n,o,a,c,h,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++)),h=e.indexOf(r.charAt(l++)),s=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|h,t=t+String.fromCharCode(s),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),h!=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 ts(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(ii(s))}async function Zs(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function er(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 ni(r){return("0"+r.toString(16)).substr(-2)}function oi(){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,ni).join("")}async function ai(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 ci(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function li(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 ai(r);return ci(t)}async function fe(r,e,t=!1){let s=oi(),i=s;t&&(i+="/PASSWORD_RECOVERY"),await es(r,`${e}-code-verifier`,i);let n=await li(s);return[n,s===n?"plain":"s256"]}var hi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function tr(r){let e=r.headers.get(Ye);if(!e||!e.match(hi))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 _(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var xt=class extends Ze{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function sr(r){return _(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}},V=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}}},Oe=class extends ee{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function At(r){return _(r)&&r.name==="AuthRetryableFetchError"}var tt=class extends ee{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var ui=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),di=[502,503,504];async function rr(r){var e;if(!Xs(r))throw new Oe(me(r),0);if(di.includes(r.status))throw new Oe(me(r),r.status);let t;try{t=await r.json()}catch(n){throw new Ae(me(n),n)}let s,i=tr(r);if(i&&i.getTime()>=Zt["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 xt(me(t),r.status||500,s)}var fi=(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 w(r,e,t,s){var i;let n=Object.assign({},s?.headers);n[Ye]||(n[Ye]=Zt["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 pi(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 pi(r,e,t,s,i,n){let o=fi(e,s,i,n),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new Oe(me(c),0)}if(a.ok||await rr(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await rr(c)}}function te(r){var e;let t=null;gi(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=Ys(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function ss(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 Y(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function ir(r){return{data:r,error:null}}function nr(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=ui(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 or(r){return r}function gi(r){return r.access_token&&r.refresh_token&&r.expires_in}var mi=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var 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=Et(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await w(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(_(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await w(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Y})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=mi(e,["options"]),i=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(i.new_email=s?.newEmail,delete i.newEmail),await w(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:nr,redirectTo:t?.redirectTo})}catch(t){if(_(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await w(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Y})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,i,n,o,a,c;try{let h={nextPage:null,lastPage:0,total:0},l=await w(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:or});if(l.error)throw l.error;let u=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(b=>{let y=parseInt(b.split(";")[0].split("=")[1].substring(0,1)),f=JSON.parse(b.split(";")[1].split("=")[1]);h[`${f}Page`]=y}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(_(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await w(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Y})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await w(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Y})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await w(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Y})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await w(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(_(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await w(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}};var ar={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 rs(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function cr(){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}},Pt=class extends st{};async function is(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 Pt(`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()}})}cr();var _i={url:Ws,storageKey:Ks,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Vs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},rt=30*1e3,lr=3;async function hr(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&&z()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let i=Object.assign(Object.assign({},_i),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=Et(i.fetch),this.lock=i.lock||hr,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:z()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=is:this.lock=hr,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=ar:(this.memoryStorage={},this.storage=rs(this.memoryStorage)):(this.memoryStorage={},this.storage=rs(this.memoryStorage)),z()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(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} (${kt}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=z()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return _(e)?{error:e}:{error:new 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 w(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,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(_(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:u,options:d}=e,p=null,b=null;this.flowType==="pkce"&&([p,b]=await fe(this.storage,this.storageKey)),n=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:p,code_challenge_method:b},xform:te})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:u,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,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(_(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 w(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:ss})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await w(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:ss})}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(_(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 w(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:te});return await Tt(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 w(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:h}=a;return h?{data:{user:null,session:null},error:h}:!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:h})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,i,n,o;try{if("email"in e){let{email:a,options:c}=e,h=null,l=null;this.flowType==="pkce"&&([h,l]=await fe(this.storage,this.storageKey));let{error:u}=await w(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:h,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:c}=e,{data:h,error:l}=await w(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:l}}throw new pe("You must provide either an email or phone number.")}catch(a){if(_(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await w(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,h=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(_(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 w(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:ir})}catch(n){if(_(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new V;let{error:i}=await w(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(_(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:n}=e,{error:o}=await w(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 w(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(_(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,h,l)=>(!o&&h==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,h,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await w(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Y}):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 V}:await w(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:Y})})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:i,error:n}=s;if(n)throw n;if(!i.session)throw new V;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await fe(this.storage,this.storageKey));let{data:h,error:l}=await w(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:Y});if(l)throw l;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return ts(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 V;let t=Date.now()/1e3,s=t,i=!0,n=null,o=ts(e.access_token);if(o.exp&&(s=o.exp,i=s<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(_(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new V;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!z())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=St(window.location.href);if(e){if(!t.code)throw new et("No code detected.");let{data:D,error:A}=await this._exchangeCodeForSession(t.code);if(A)throw A;let P=new URL(window.location.href);return P.searchParams.delete("code"),window.history.replaceState(window.history.state,"",P.toString()),{data:{session:D.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:h}=t;if(!n||!a||!o||!h)throw new ge("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;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 ${u}s`);let b=d-u;l-b>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",b,d,l):l-b<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",b,d,l);let{data:y,error:f}=await this._getUser(n);if(f)throw f;let m={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:m,redirectType:t.type},error:null}}catch(t){if(_(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=St(window.location.href);return!!(z()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=St(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&&!(sr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Tt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Qs(),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 w(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(_(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:i}=await this._useSession(async n=>{var o,a,c,h,l;let{data:u,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 w(this.fetch,"GET",p,{headers:this.headers,jwt:(l=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return z()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(_(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)throw o;return await w(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await er(async i=>(i>0&&await Zs(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await w(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&&At(n)&&Date.now()+o-s<rt})}catch(s){if(this._debug(t,"error",s),_(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),z()&&!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+Xt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Xt}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),At(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 V;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 V;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),_(n)){let o={session:null,error:n};return At(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 es(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Tt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&z()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),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 ${lr} ticks`),i<=lr&&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()"),!z()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,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 w(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await w(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await w(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(_(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await w(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(_(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],i=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.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 yi=ve,ns=yi;var Ot=class extends ns{constructor(e){super(e)}};var vi=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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((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=Gs(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:Fs,realtime:Bs,auth:Object.assign(Object.assign({},Hs),{storageKey:c}),global:qs},l=Js(s??{},h);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=zs(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new xs(`${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 vi(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,h){var l;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ot({url:this.authUrl,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,flowType:o,debug:a,fetch:h,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 ur=(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 Re=class{constructor(){this.sessionData=null;this.supabase=ur(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 Q=null;function os(r,e=30,t){Q&&(clearInterval(Q),Q=null);let s=e;r.style.pointerEvents="none",r.textContent=`Resend (${s}s)`,Q=setInterval(()=>{s=s-1,r.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(r.style.pointerEvents="auto",Q&&(clearInterval(Q),Q=null),t&&t())},1e3)}function dr(){Q&&(clearInterval(Q),Q=null)}function fr(r,e){let t=new Re,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"),h=document.querySelector("#apple-login"),l=document.querySelector("#microsoft-login"),u=document.querySelector("[email-element]"),d=document.querySelector("[different-provider]"),p=document.querySelector("[different-provider-name]"),b=document.querySelector("[different-provider-reset]"),y=document.querySelector("[email-signup-success]"),f=document.querySelector("[email-signup-error]"),m=document.querySelector("[error-message]"),D=document.querySelector("[verification-email]"),A=document.querySelector("[email-signup-retry]"),P=document.querySelector("[email-signup-reset]"),x=document.querySelector("[scim-div]"),Ce=document.querySelector("[scim-reset]"),$=document.querySelector("[forgot-password]"),X=document.querySelector("[forgot-password-success]"),oe=document.querySelector("[forgot-password-email]"),J=document.querySelector("[unverified-email]"),nt=document.querySelector("[unverified-email-address]"),Z=document.querySelector("[resend-verification-email]"),ot=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(c&&c.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(r)}catch(v){console.error("Error during Google sign-in:",v)}}),h&&h.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await t.signInWithApple(r)}catch(v){console.error("Error during Apple sign-in:",v)}}),l&&l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(r)}catch(v){console.error("Error during Microsoft sign-in:",v)}}));let g=()=>{d&&(d.style.display="none"),y&&(y.style.display="none"),f&&(f.style.display="none"),J&&(J.style.display="none"),x&&(x.style.display="none"),$&&($.style.display="none"),X&&(X.style.display="none");let v=document.querySelector(".gs-hero_form-block");v&&(v.style.display="block"),u&&(u.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 k=document.querySelector("[captcha-embed]"),T=document.querySelector("#h-captcha-container");k&&(k.style.display="none"),T&&(T.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),s="email_input",n&&n.focus()},O=()=>{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 v=document.querySelector("[captcha-embed]"),k=document.querySelector("#h-captcha-container");v&&(v.style.display="block"),k&&(k.style.display="block"),$&&($.style.display="block",$.onclick=async()=>{let T=n?.value||"",S=$.textContent||"";try{let{hcaptcha:M}=window;if(!M)throw new Error("Verification system not loaded. Please refresh the page.");$.style.pointerEvents="none",$.textContent="Sending...";let{response:R}=await M.execute({async:!0});if(!R)throw new Error("Verification cancelled");await Le.requestPasswordReset(T,R),M.reset(),u&&(u.style.display="none"),$&&($.style.display="none"),X&&(X.style.display="block"),oe&&(oe.textContent=T)}catch(M){console.error("Error sending password reset email:",M),$.textContent=S,$.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),f&&(f.style.display="block",m&&(m.textContent=M instanceof Error?M.message:"Failed to send reset email"))}}),s="login"},N=()=>{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 v=document.querySelector("[captcha-embed]"),k=document.querySelector("#h-captcha-container");v&&(v.style.display="block"),k&&(k.style.display="block"),s="signup"},G=()=>{let v=document.querySelector(".gs-hero_form-block");v&&(v.style.display="none"),x&&(x.style.display="block"),Ce&&(Ce.onclick=()=>{x&&(x.style.display="none"),v&&(v.style.display="block"),g()})},F=v=>{let k=us(v);u&&(u.style.display="none"),d&&(d.style.display="block"),p&&(p.textContent=k),b&&(b.onclick=()=>{d&&(d.style.display="none"),g()}),s="oauth_user"},ae=v=>{u&&(u.style.display="none"),J&&(J.style.display="block"),nt&&(nt.textContent=v),Z&&(Z.onclick=async()=>{let k=Z.textContent||"";try{let T=window.hcaptcha?await window.hcaptcha.execute({async:!0}):void 0;await t.resendVerificationEmail(v,r,T),Z.textContent="Verification email resent! \u2705",Z.style.textDecoration="none"}catch(T){console.error("Error resending verification email:",T),Z.textContent=k}}),ot&&(ot.onclick=()=>{J&&(J.style.display="none"),g()}),s="unverified_email"},as=async(v,k)=>{let T=k.value;k.classList.add("loading"),k.value="";try{let S=await Le.checkUserStatus(v);k.classList.remove("loading"),k.value=T,!S.exists&&S.scim_managed?G():S.enforce_sso?F("workos"):S.exists&&S.provider&&S.provider!=="email"?F(S.provider):S.exists&&S.provider==="email"&&!S.verified?ae(v):S.exists&&S.provider==="email"?O():N()}catch(S){console.error("Error checking user status:",S),k.classList.remove("loading"),k.value=T,N()}},Rt=async(v,k,T,S)=>{if(!k||k.length<8){f&&(f.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}let M=window.hcaptcha?.getResponse()||"";if(!M){f&&(f.style.display="block",m&&(m.textContent="Please complete the verification"));return}T.classList.add("loading"),T.value="";try{let{accessToken:R,refreshToken:L,fullName:Ie}=await t.signInWithPassword(v,k,M);t.setCookies(R,L),localStorage.setItem("email",v),e?.onLoginSuccess?await e.onLoginSuccess(R,L,Ie):window.location.href=r}catch(R){if(console.error("Login error:",R),window.hcaptcha&&window.hcaptcha.reset(),T.classList.remove("loading"),T.value=S,f&&(f.style.display="block",m)){let L=R instanceof Error?R.message:"Invalid login credentials";m.textContent=L}}},mr=async(v,k,T,S,M)=>{if(!k||k.length<8){f&&(f.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}if(!T||T.trim().length<2){f&&(f.style.display="block",m&&(m.textContent="Please enter your full name"));return}let R=window.hcaptcha?.getResponse()||"";if(!R){f&&(f.style.display="block",m&&(m.textContent="Please complete the verification"));return}S.classList.add("loading"),S.value="";try{await t.signUpWithPassword(v,k,T,r,R),window.hcaptcha&&window.hcaptcha.reset(),S.classList.remove("loading"),S.value=M,u&&(u.style.display="none"),f&&(f.style.display="none"),y&&(y.style.display="block"),D&&(D.textContent=v),A&&(os(A,30),A.onclick=async()=>{if(A.style.pointerEvents!=="none")try{let L=window.hcaptcha?.getResponse()||"";await t.signUpWithPassword(v,k,T,r,L),window.hcaptcha&&window.hcaptcha.reset(),os(A,30)}catch(L){console.error("Error resending verification email:",L)}}),P&&(P.onclick=()=>{y&&(y.style.display="none"),dr(),g()})}catch(L){if(console.error("Signup error:",L),S.classList.remove("loading"),S.value=M,f&&(f.style.display="block",m)){let Ie=L instanceof Error?L.message:"Signup failed";m.textContent=Ie}}};i&&i.addEventListener("submit",async v=>{v.stopPropagation(),v.preventDefault();let k=n?.value||"",T=o?.value||"",S=a?.value||"";if(!k||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(k)){f&&(f.style.display="block",m&&(m.textContent="Please enter a valid email address"));return}f&&(f.style.display="none"),m&&(m.textContent="");let R=i.querySelector('[type="submit"]'),L=R?.value||"";localStorage.setItem("signin_provider","email");try{s==="email_input"?await as(k,R):s==="login"?await Rt(k,T,R,L):s==="signup"&&await mr(k,T,S,R,L)}catch(Ie){console.error("Auth flow error:",Ie),R&&(R.classList.remove("loading"),R.value=L),f&&(f.style.display="block")}})}var pr=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var I=(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(()=>I(r,e,t-1),200)};var gr="https://api.wisprflow.ai",wi="https://wisprflow.ai";window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let r=new Re,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("#google-login"),h=document.querySelector("#apple-login"),l=document.querySelector("#microsoft-login"),u=localStorage.getItem("last_authed_provider");u&&{google:c,apple:h,microsoft:l,sso:document.querySelector("#sso-login"),email:document.querySelector("#email-input")}[u]?.classList.add("last-used");let d=()=>{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"},p=()=>{let g=localStorage.getItem("signin_provider");g&&localStorage.setItem("last_authed_provider",g),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"},b=g=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="block"),i&&(i.textContent=g),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"},f=()=>{e&&(e.style.display="none"),n&&(n.style.display="block"),o&&(o.style.display="block"),document.body.style.visibility="visible"},m=async(g,O)=>{try{let[N,G]=hs(O||" "),F=Le.signupUser({access_token:g,first_name:N,last_name:G}),ae=new Promise((as,Rt)=>setTimeout(()=>Rt(new Error("signup timeout")),4e3));await Promise.race([F,ae])}catch(N){I("signup_sync_error",{error_message:N instanceof Error?N.message:String(N)})}},D=()=>{let g=sessionStorage.getItem("wispr_fbclid");return g?`fb.1.${Date.now()}.${g}`:null},A=async(g,O)=>{let N=sessionStorage.getItem("wispr_device_code");if(!N)throw new Error("Device code not found. Please restart authentication from desktop app.");let G=pr(),F=await fetch(`${gr}/device/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${g}`},body:JSON.stringify({device_code:N,access_token:g,refresh_token:O,fbp:G._fbp||void 0,fbc:G._fbc||D()||void 0})});if(!F.ok){let ae=await F.json().catch(()=>({}));throw F.status===403&&ae?.detail?.code==="enterprise_ip_not_allowed"?new Error("enterprise_ip_not_allowed"):new Error(ae?.detail?.message||ae.message||`Server error: ${F.status}`)}console.log("Device authentication complete:",await F.json()),sessionStorage.removeItem("wispr_device_code")},P=new URLSearchParams(window.location.search),x=P.get("device_code"),Ce=P.get("auto_signin")==="true",$=new URLSearchParams(window.location.hash.slice(1)),X=P.get("access_token")||$.get("access_token"),oe=P.get("refresh_token")||$.get("refresh_token");if(!x&&!X&&!oe&&!sessionStorage.getItem("wispr_device_code")){console.log("No device_code found - redirecting to /get-started"),I("desktop_login_no_device_code"),window.location.href="/get-started";return}if(I("desktop_login_page_view",{auto_signin:Ce}),x){sessionStorage.setItem("wispr_device_code",x),console.log("Device code stored:",x);let g=P.get("fbclid");g&&sessionStorage.setItem("wispr_fbclid",g),window.history.replaceState({},"","/login")}if(X&&oe){console.log("OAuth callback detected - handling tokens"),I("desktop_login_oauth_callback",{provider:localStorage.getItem("signin_provider")??"unknown"}),d();try{let g=X,O=oe;try{r.setCookies(X,oe),await r.checkAndSetSession(),r.sessionData&&(g=r.sessionData.access_token,O=r.sessionData.refresh_token,r.setCookies(g,O),localStorage.setItem("email",r.sessionData.user.email),r.sessionData.user.id&&localStorage.setItem("user_id",r.sessionData.user.id))}catch{}await m(g,r.sessionData?.user.user_metadata?.full_name),await A(g,O),I("desktop_login_complete_success",{method:"oauth"}),p()}catch(g){if(g instanceof Error&&g.message==="enterprise_ip_not_allowed"){I("desktop_login_complete_error",{method:"oauth",error:"enterprise_ip_not_allowed"}),y();return}let O=g instanceof Error?g.message:"Failed to complete authentication. Please try again.";I("desktop_login_complete_error",{method:"oauth",error:O}),console.error("Error completing device authentication:",g),b(O)}return}if(Ce){console.log("Auto-signin enabled - checking existing session"),d();try{let g=r.checkAndSetSession(),O=new Promise((N,G)=>setTimeout(()=>G(new Error("Session timeout")),3e3));if(await Promise.race([g,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 m(r.sessionData.access_token,r.sessionData?.user.user_metadata?.full_name),await A(r.sessionData.access_token,r.sessionData.refresh_token),I("desktop_login_auto_signin_success"),p();return}console.log("No existing session - showing login form"),I("desktop_login_auto_signin_no_session"),f()}catch(g){if(console.error("Auto-signin error:",g),g instanceof Error&&g.message==="enterprise_ip_not_allowed"){I("desktop_login_auto_signin_error",{error:"enterprise_ip_not_allowed"}),y();return}let O=g instanceof Error?g.message:"Auto-signin failed. Please try logging in manually.";I("desktop_login_auto_signin_error",{error:O}),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),f()}}else I("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"),f();let J=g=>{console.log(`Redirecting to ${g} OAuth`),I("desktop_login_oauth_click",{provider:g}),localStorage.setItem("signin_provider",g);let O=`${gr}/${g}/sign_in?source=${wi}`;window.location.href=O};c&&c.addEventListener("click",()=>{J("google")}),h&&h.addEventListener("click",()=>{J("apple")}),l&&l.addEventListener("click",()=>{J("microsoft")});let nt=async(g,O,N)=>{try{await m(g,N),await A(g,O)}catch(G){let F=G instanceof Error?G.message:"Failed to complete authentication. Please try again.";I("desktop_login_complete_error",{method:"email",error:F}),b(F);return}I("desktop_login_complete_success",{method:"email"}),p()},Z=sessionStorage.getItem("wispr_device_code"),ot=Z?`${window.location.origin}/login?device_code=${Z}`:`${window.location.origin}/login`;fr(ot,{onLoginSuccess:nt,skipOAuthButtons:!0}),console.log("Desktop login page initialized")});})();
1
+ "use strict";(()=>{var _r=Object.create;var ct=Object.defineProperty;var yr=Object.getOwnPropertyDescriptor;var vr=Object.getOwnPropertyNames;var wr=Object.getPrototypeOf,br=Object.prototype.hasOwnProperty;var kr=(r,e)=>()=>(r&&(e=r(r=0)),e);var W=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Sr=(r,e)=>{for(var t in e)ct(r,t,{get:e[t],enumerable:!0})},ls=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of vr(e))!br.call(r,i)&&i!==t&&ct(r,i,{get:()=>e[i],enumerable:!(s=yr(e,i))||s.enumerable});return r};var hs=(r,e,t)=>(t=r!=null?_r(wr(r)):{},ls(e||!r||!r.__esModule?ct(t,"default",{value:r,enumerable:!0}):t,r)),Er=r=>ls(ct({},"__esModule",{value:!0}),r);var le={};Sr(le,{Headers:()=>$t,Request:()=>Ar,Response:()=>Pr,default:()=>Lt,fetch:()=>xr});var Tr,Se,xr,Lt,$t,Ar,Pr,se=kr(()=>{"use strict";Tr=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")},Se=Tr(),xr=Se.fetch,Lt=Se.fetch.bind(Se),$t=Se.Headers,Ar=Se.Request,Pr=Se.Response});var ps=W(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});var jt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Ut.default=jt});var Nt=W(Me=>{"use strict";var gs=Me&&Me.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Me,"__esModule",{value:!0});var Rr=gs((se(),Er(le))),Cr=gs(ps()),Dt=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=Rr.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 h=null,l=null,u=null,d=n.status,p=n.statusText;if(n.ok){if(this.method!=="HEAD"){let m=await n.text();m===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=m:l=JSON.parse(m))}let y=(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("/");y&&f&&f.length>1&&(u=parseInt(f[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(h={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,u=null,d=406,p="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let y=await n.text();try{h=JSON.parse(y),Array.isArray(h)&&n.status===404&&(l=[],h=null,d=200,p="OK")}catch{n.status===404&&y===""?(d=204,p="No Content"):h={message:y}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,p="OK"),h&&this.shouldThrowOnError)throw new Cr.default(h)}return{error:h,data:l,count:u,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)}};Me.default=Dt});var qt=W(qe=>{"use strict";var Ir=qe&&qe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(qe,"__esModule",{value:!0});var Lr=Ir(Nt()),Mt=class extends Lr.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("|"),h=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};qe.default=Mt});var ft=W(Fe=>{"use strict";var $r=Fe&&Fe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Fe,"__esModule",{value:!0});var jr=$r(qt()),Ft=class extends jr.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}};Fe.default=Ft});var Bt=W(Be=>{"use strict";var Ur=Be&&Be.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Be,"__esModule",{value:!0});var He=Ur(ft()),Ht=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 He.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 He.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((h,l)=>h.concat(Object.keys(l)),[]);if(c.length>0){let h=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",h.join(","))}}return new He.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 He.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 He.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Be.default=Ht});var ms=W(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.version=void 0;pt.version="0.0.0-automated"});var _s=W(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.DEFAULT_HEADERS=void 0;var Dr=ms();gt.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Dr.version}`}});var vs=W(ze=>{"use strict";var ys=ze&&ze.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ze,"__esModule",{value:!0});var Nr=ys(Bt()),Mr=ys(ft()),qr=_s(),zt=class r{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},qr.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new Nr.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,u])=>u!==void 0).map(([l,u])=>[l,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([l,u])=>{a.searchParams.append(l,u)})):(o="POST",c=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new Mr.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};ze.default=zt});var Ts=W(D=>{"use strict";var Ge=D&&D.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(D,"__esModule",{value:!0});D.PostgrestBuilder=D.PostgrestTransformBuilder=D.PostgrestFilterBuilder=D.PostgrestQueryBuilder=D.PostgrestClient=void 0;var ws=Ge(vs());D.PostgrestClient=ws.default;var bs=Ge(Bt());D.PostgrestQueryBuilder=bs.default;var ks=Ge(ft());D.PostgrestFilterBuilder=ks.default;var Ss=Ge(qt());D.PostgrestTransformBuilder=Ss.default;var Es=Ge(Nt());D.PostgrestBuilder=Es.default;D.default={PostgrestClient:ws.default,PostgrestQueryBuilder:bs.default,PostgrestFilterBuilder:ks.default,PostgrestTransformBuilder:Ss.default,PostgrestBuilder:Es.default}});var $s=W((nn,Ls)=>{"use strict";Ls.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var U="https://api.wisprflow.ai",It=class{static async signupUser(e){try{let t=`${U}/signup`,i=document.cookie.split(";").find(a=>a.trim().startsWith("trial_promo=")),n=i&&i.trim().split("=")[1];(n==="3mo"||n==="2mo")&&(t+=`?trial_promo=${n}`);let o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!o.ok)throw new Error(`Signup failed with status ${o.status}`);return console.log("User signed up successfully"),await o.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${U}/signup_raw_email`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Adding raw user failed with status ${t.status}`);return console.log("Added raw user successfully"),await t.json()}catch(t){throw console.error("Error during raw user signup:",t),t}}static async addToWaitlist(e){try{let t=await fetch(`${U}/add_to_waitlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying waitlist failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async applyReferralCode(e){try{let t=await fetch(`${U}/api/v1/referral/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying referral code failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async associateAppSumoLicense(e){try{let t=await fetch(`${U}/app_sumo/associate_license_key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}static async checkUserStatus(e){return await(await fetch(`${U}/user_status?email=${encodeURIComponent(e)}`)).json()}static async requestPasswordReset(e,t){let s=await fetch(`${U}/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(`${U}/api/v1/payment/subscription`,{method:"GET",headers:{accept:"application/json",Authorization:e}})}static async getPricingByIp(){let e=await fetch(`${U}/api/v1/payment/pricing/by-ip`,{method:"GET",headers:{accept:"application/json"}});if(!e.ok)throw new Error(`Pricing API failed with status ${e.status}`);return await e.json()}static async createCheckoutSession(e,t,s){let i=`${U}/api/v1/payment/create-checkout-session?plan=${e}&custom_redirect=true`;return s&&(i+=`&currency=${s}`),await(await fetch(i,{method:"POST",headers:{accept:"application/json",Authorization:t}})).json()}static async sendDownloadLink(e,t){return await fetch(`${U}/api/v1/referral/download-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:e,recipient_email:t})})}static async getAndroidWaitlistStats(e){return await fetch(`${U}/api/v1/promos/android_waitlist_rank`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async ensureReferralCode(e){return await fetch(`${U}/api/v1/referral/`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${e}`}})}static async submitPhoneNumber(e,t){return await fetch(`${U}/api/v1/promos/android_waitlist/phone_number`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${t}`},body:JSON.stringify({phone_number:e})})}static async submitSocialShare(e,t,s){let i=new FormData;return i.append("screenshot",e),await fetch(`${U}/api/v1/promos/android_waitlist/verify_social_share`,{method:"POST",headers:{Authorization:`${t}`},body:i,signal:s})}};function us(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}function ds(r){return r==="azure"?"Microsoft":r==="workos"?"SSO":r.charAt(0).toUpperCase()+r.slice(1)}var Ue=It;var fs=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(se(),le)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var De=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},lt=class extends De{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},ht=class extends De{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},ut=class extends De{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},dt;(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"})(dt||(dt={}));var Or=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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Ne=class{constructor(e,{headers:t={},customFetch:s,region:i=dt.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=fs(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Or(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let h;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData<"u"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:h}).catch(b=>{throw new lt(b)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new ht(l);if(!l.ok)throw new ut(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 xs=hs(Ts(),1),{PostgrestClient:As,PostgrestQueryBuilder:Mi,PostgrestFilterBuilder:qi,PostgrestTransformBuilder:Fi,PostgrestBuilder:Hi}=xs.default;var Ps="2.10.2";var Os={"X-Client-Info":`realtime-js/${Ps}`},Rs="1.0.0",_t=1e4,Cs=1e3,he;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(he||(he={}));var q;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(q||(q={}));var H;(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"})(H||(H={}));var mt;(function(r){r.websocket="websocket"})(mt||(mt={}));var re;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(re||(re={}));var Je=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 h=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:h}}};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 E;(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"})(E||(E={}));var Jt=(r,e,t={})=>{var s;let i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Fr(o,r,e,i),n),{})},Fr=(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):Gt(o)},Is=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return Gr(e,t)}switch(r){case E.bool:return Hr(e);case E.float4:case E.float8:case E.int2:case E.int4:case E.int8:case E.numeric:case E.oid:return Br(e);case E.json:case E.jsonb:return zr(e);case E.timestamp:return Jr(e);case E.abstime:case E.date:case E.daterange:case E.int4range:case E.int8range:case E.money:case E.reltime:case E.text:case E.time:case E.timestamptz:case E.timetz:case E.tsrange:case E.tstzrange:return Gt(e);default:return Gt(e)}},Gt=r=>r,Hr=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},Br=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},zr=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},Gr=(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},Jr=r=>typeof r=="string"?r.replace(" ","T"):r,yt=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=_t){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 Wt;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(Wt||(Wt={}));var Ee=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,(h,l)=>{o[h]||(c[h]=l)}),this.map(o,(h,l)=>{let u=n[h];if(u){let d=l.map(f=>f.presence_ref),p=u.map(f=>f.presence_ref),b=l.filter(f=>p.indexOf(f.presence_ref)<0),y=u.filter(f=>d.indexOf(f.presence_ref)<0);b.length>0&&(a[h]=b),y.length>0&&(c[h]=y)}else a[h]=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 h;let l=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(c),l.length>0){let u=e[a].map(p=>p.presence_ref),d=l.filter(p=>u.indexOf(p.presence_ref)<0);e[a].unshift(...d)}s(a,l,c)}),this.map(o,(a,c)=>{let h=e[a];if(!h)return;let l=c.map(u=>u.presence_ref);h=h.filter(u=>l.indexOf(u.presence_ref)<0),e[a]=h,i(a,h,c),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(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 Kt;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(Kt||(Kt={}));var Vt;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(Vt||(Vt={}));var Yt;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Yt||(Yt={}));var Te=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=q.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new de(this,H.join,this.params,this.timeout),this.rejoinTimer=new ue(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=q.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=q.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=q.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=q.errored,this.rejoinTimer.scheduleTimeout())}),this._on(H.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new Ee(this),this.broadcastEndpointURL=yt(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={},h={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:h},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,p=(u=d?.length)!==null&&u!==void 0?u:0,b=[];for(let y=0;y<p;y++){let f=d[y],{filter:{event:m,schema:L,table:O,filter:R}}=f,x=l&&l[y];if(x&&x.event===m&&x.schema===L&&x.table===O&&x.filter===R)b.push(Object.assign(Object.assign({},f),{id:x.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=b,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),h.receive("ok",()=>n("ok")),h.receive("error",()=>n("error")),h.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=q.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(H.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let i=new de(this,H.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:h,join:l}=H;if(s&&[a,c,h,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 b,y,f;return((b=p.filter)===null||b===void 0?void 0:b.event)==="*"||((f=(y=p.filter)===null||y===void 0?void 0:y.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 b,y,f,m,L,O;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in p){let R=p.id,x=(b=p.filter)===null||b===void 0?void 0:b.event;return R&&((y=t.ids)===null||y===void 0?void 0:y.includes(R))&&(x==="*"||x?.toLocaleLowerCase()===((f=t.data)===null||f===void 0?void 0:f.type.toLocaleLowerCase()))}else{let R=(L=(m=p?.filter)===null||m===void 0?void 0:m.event)===null||L===void 0?void 0:L.toLocaleLowerCase();return R==="*"||R===((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 b=d.data,{schema:y,table:f,commit_timestamp:m,type:L,errors:O}=b;d=Object.assign(Object.assign({},{schema:y,table:f,commit_timestamp:m,eventType:L,new:{},old:{},errors:O}),this._getPayloadRecords(b))}p.callback(d,s)})}_isClosed(){return this.state===q.closed}_isJoined(){return this.state===q.joined}_isJoining(){return this.state===q.joining}_isLeaving(){return this.state===q.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:s};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===s&&r.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(H.close,{},e)}_onError(e){this._on(H.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=q.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Jt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Jt(e.columns,e.old_record)),t}};var Kr=()=>{},Vr=typeof WebSocket<"u",xe=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=_t,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Kr,this.conn=null,this.sendBuffer=[],this.serializer=new Je,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(se(),le)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${mt.websocket}`,this.httpEndpoint=yt(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(Vr){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Qt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>hs($s())).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 he.connecting:return re.Connecting;case he.open:return re.Open;case he.closing:return re.Closing;default:return re.Closed}}isConnected(){return this.connectionState()===re.Open}channel(e,t={config:{}}){let s=new Te(`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(H.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:Rs}))}_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(H.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(Cs,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Qt=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=he.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var Ae=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function C(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var vt=class extends Ae{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},We=class extends Ae{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Yr=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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},wt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(se(),le)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},js=()=>Yr(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(se(),le))).Response:Response});var Pe=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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Xt=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Qr=(r,e)=>Pe(void 0,void 0,void 0,function*(){let t=yield js();r instanceof t?r.json().then(s=>{e(new vt(Xt(s),r.status||500))}).catch(s=>{e(new We(Xt(s),s))}):e(new We(Xt(r),r))}),Xr=(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 bt(r,e,t,s,i,n){return Pe(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,Xr(e,s,i,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Qr(c,a))})})}function Ke(r,e,t,s){return Pe(this,void 0,void 0,function*(){return bt(r,"GET",e,t,s)})}function K(r,e,t,s,i){return Pe(this,void 0,void 0,function*(){return bt(r,"POST",e,s,i,t)})}function Us(r,e,t,s,i){return Pe(this,void 0,void 0,function*(){return bt(r,"PUT",e,s,i,t)})}function kt(r,e,t,s,i){return Pe(this,void 0,void 0,function*(){return bt(r,"DELETE",e,s,i,t)})}var z=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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Zr={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ds={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Ve=class{constructor(e,t={},s,i){this.url=e,this.headers=t,this.bucketId=s,this.fetch=wt(i)}uploadOrUpdate(e,t,s,i){return z(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Ds),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),h=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield l.json();return l.ok?{data:{path:c,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(C(n))return{data:null,error:n};throw n}})}upload(e,t,s){return z(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return z(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,h=Object.assign({upsert:Ds.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",h.cacheControl)):(c=s,l["cache-control"]=`max-age=${h.cacheControl}`,l["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(C(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return z(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 K(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 Ae("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(C(s))return{data:null,error:s};throw s}})}update(e,t,s){return z(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return z(this,void 0,void 0,function*(){try{return{data:yield K(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(C(i))return{data:null,error:i};throw i}})}copy(e,t,s){return z(this,void 0,void 0,function*(){try{return{data:{path:(yield K(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(C(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return z(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield K(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},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(C(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return z(this,void 0,void 0,function*(){try{let i=yield K(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=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(C(i))return{data:null,error:i};throw i}})}download(e,t){return z(this,void 0,void 0,function*(){let i=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield Ke(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(C(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 h=i.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${h}`)}}}remove(e){return z(this,void 0,void 0,function*(){try{return{data:yield kt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(C(t))return{data:null,error:t};throw t}})}list(e,t,s){return z(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Zr),t),{prefix:e||""});return{data:yield K(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if(C(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 Ns="2.6.0";var Ms={"X-Client-Info":`storage-js/${Ns}`};var Oe=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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Ye=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},Ms),t),this.fetch=wt(s)}listBuckets(){return Oe(this,void 0,void 0,function*(){try{return{data:yield Ke(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(C(e))return{data:null,error:e};throw e}})}getBucket(e){return Oe(this,void 0,void 0,function*(){try{return{data:yield Ke(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(C(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Oe(this,void 0,void 0,function*(){try{return{data:yield K(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(C(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return Oe(this,void 0,void 0,function*(){try{return{data:yield Us(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(C(s))return{data:null,error:s};throw s}})}emptyBucket(e){return Oe(this,void 0,void 0,function*(){try{return{data:yield K(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(C(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Oe(this,void 0,void 0,function*(){try{return{data:yield kt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(C(t))return{data:null,error:t};throw t}})}};var Qe=class extends Ye{constructor(e,t={},s){super(e,t,s)}from(e){return new Ve(this.url,this.headers,e,this.fetch)}};var qs="2.44.4";var Xe="";typeof Deno<"u"?Xe="deno":typeof document<"u"?Xe="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Xe="react-native":Xe="node";var ei={"X-Client-Info":`supabase-js-${Xe}/${qs}`},Fs={headers:ei},Hs={schema:"public"},Bs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},zs={};se();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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},si=r=>{let e;return r?e=r:typeof fetch>"u"?e=Lt:e=fetch,(...t)=>e(...t)},ri=()=>typeof Headers>"u"?$t:Headers,Gs=(r,e,t)=>{let s=si(t),i=ri();return(n,o)=>ti(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,h=new i(o?.headers);return h.has("apikey")||h.set("apikey",r),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:h}))})};function Js(r){return r.replace(/\/$/,"")}function Ws(r,e){let{db:t,auth:s,realtime:i,global:n}=r,{db:o,auth:a,realtime:c,global:h}=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({},h),n)}}var St="2.64.4";var Ks="http://localhost:9999",Vs="supabase.auth.token";var Ys={"X-Client-Info":`gotrue-js/${St}`},Zt=10;var Ze="X-Supabase-Api-Version",es={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Qs(r){return Math.round(Date.now()/1e3)+r}function Xs(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}var G=()=>typeof document<"u",fe={tested:!1,writable:!1},ie=()=>{if(!G())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 Et(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 Tt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(se(),le)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Zs=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",ts=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},tt=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},xt=async(r,e)=>{await r.removeItem(e)};function ii(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,i,n,o,a,c,h,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++)),h=e.indexOf(r.charAt(l++)),s=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|h,t=t+String.fromCharCode(s),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var et=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};et.promiseConstructor=Promise;function ss(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(ii(s))}async function er(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function tr(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 ni(r){return("0"+r.toString(16)).substr(-2)}function oi(){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,ni).join("")}async function ai(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 ci(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function li(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 ai(r);return ci(t)}async function pe(r,e,t=!1){let s=oi(),i=s;t&&(i+="/PASSWORD_RECOVERY"),await ts(r,`${e}-code-verifier`,i);let n=await li(s);return[n,s===n?"plain":"s256"]}var hi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function sr(r){let e=r.headers.get(Ze);if(!e||!e.match(hi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var st=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function _(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var At=class extends st{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function rr(r){return _(r)&&r.name==="AuthApiError"}var Re=class extends st{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},X=class extends st{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}},V=class extends X{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},Ce=class extends X{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},ge=class extends X{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},me=class extends X{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}}},rt=class extends X{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}}},Ie=class extends X{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Pt(r){return _(r)&&r.name==="AuthRetryableFetchError"}var it=class extends X{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var ui=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),di=[502,503,504];async function ir(r){var e;if(!Zs(r))throw new Ie(_e(r),0);if(di.includes(r.status))throw new Ie(_e(r),r.status);let t;try{t=await r.json()}catch(n){throw new Re(_e(n),n)}let s,i=sr(r);if(i&&i.getTime()>=es["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 it(_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 it(_e(t),r.status,t.weak_password.reasons);throw new At(_e(t),r.status||500,s)}var fi=(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 w(r,e,t,s){var i;let n=Object.assign({},s?.headers);n[Ze]||(n[Ze]=es["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 pi(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 pi(r,e,t,s,i,n){let o=fi(e,s,i,n),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new Ie(_e(c),0)}if(a.ok||await ir(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await ir(c)}}function Z(r){var e;let t=null;gi(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=Qs(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function rs(r){let e=Z(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 Y(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function nr(r){return{data:r,error:null}}function or(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=ui(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 ar(r){return r}function gi(r){return r.access_token&&r.refresh_token&&r.expires_in}var mi=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var 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=Tt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await w(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(_(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await w(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Y})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=mi(e,["options"]),i=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(i.new_email=s?.newEmail,delete i.newEmail),await w(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:or,redirectTo:t?.redirectTo})}catch(t){if(_(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await w(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Y})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,i,n,o,a,c;try{let h={nextPage:null,lastPage:0,total:0},l=await w(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:ar});if(l.error)throw l.error;let u=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(b=>{let y=parseInt(b.split(";")[0].split("=")[1].substring(0,1)),f=JSON.parse(b.split(";")[1].split("=")[1]);h[`${f}Page`]=y}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(_(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await w(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Y})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await w(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Y})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await w(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Y})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await w(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(_(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await w(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}};var cr={getItem:r=>ie()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{ie()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{ie()&&globalThis.localStorage.removeItem(r)}};function is(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function lr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var ve={debug:!!(globalThis&&ie()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},nt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Ot=class extends nt{};async function ns(r,e,t){ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),ve.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){ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw ve.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Ot(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(ve.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}lr();var _i={url:Ks,storageKey:Vs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ys,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},ot=30*1e3,hr=3;async function ur(r,e,t){return await t()}var we=class r{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=r.nextInstanceID,r.nextInstanceID+=1,this.instanceID>0&&G()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let i=Object.assign(Object.assign({},_i),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=Tt(i.fetch),this.lock=i.lock||ur,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:G()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=ns:this.lock=ur,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:ie()?this.storage=cr:(this.memoryStorage={},this.storage=is(this.memoryStorage)):(this.memoryStorage={},this.storage=is(this.memoryStorage)),G()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${St}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=G()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),s?.message==="Identity is already linked"||s?.message==="Identity is already linked to another user"?{error:s}:(await this._removeSession(),{error:s});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return _(e)?{error:e}:{error:new Re("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{let n=await w(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:Z}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(_(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:u,options:d}=e,p=null,b=null;this.flowType==="pkce"&&([p,b]=await pe(this.storage,this.storageKey)),n=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:p,code_challenge_method:b},xform:Z})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await w(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:u,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:Z})}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,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(_(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 w(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:rs})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await w(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:rs})}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 Ce}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await tt(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(t??"").split("/"),{data:n,error:o}=await w(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:Z});return await xt(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 Ce}:(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 w(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:Z}),{data:c,error:h}=a;return h?{data:{user:null,session:null},error:h}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new Ce}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,i,n,o;try{if("email"in e){let{email:a,options:c}=e,h=null,l=null;this.flowType==="pkce"&&([h,l]=await pe(this.storage,this.storageKey));let{error:u}=await w(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:h,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:c}=e,{data:h,error:l}=await w(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:l}}throw new ge("You must provide either an email or phone number.")}catch(a){if(_(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,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 w(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:Z});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(_(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 w(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:nr})}catch(n){if(_(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new V;let{error:i}=await w(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(_(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:n}=e,{error:o}=await w(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 w(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(_(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 tt(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,h,l)=>(!o&&h==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,h,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await w(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Y}):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 V}:await w(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:Y})})}catch(t){if(_(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:i,error:n}=s;if(n)throw n;if(!i.session)throw new V;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await pe(this.storage,this.storageKey));let{data:h,error:l}=await w(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:Y});if(l)throw l;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(_(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return ss(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 V;let t=Date.now()/1e3,s=t,i=!0,n=null,o=ss(e.access_token);if(o.exp&&(s=o.exp,i=s<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(_(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new V;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(_(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!G())throw new 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 rt("Not a valid PKCE flow url.");let t=Et(window.location.href);if(e){if(!t.code)throw new rt("No code detected.");let{data:L,error:O}=await this._exchangeCodeForSession(t.code);if(O)throw O;let R=new URL(window.location.href);return R.searchParams.delete("code"),window.history.replaceState(window.history.state,"",R.toString()),{data:{session:L.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:h}=t;if(!n||!a||!o||!h)throw new me("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;c&&(d=parseInt(c));let p=d-l;p*1e3<=ot&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${u}s`);let b=d-u;l-b>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",b,d,l):l-b<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",b,d,l);let{data:y,error:f}=await this._getUser(n);if(f)throw f;let m={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:m,redirectType:t.type},error:null}}catch(t){if(_(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Et(window.location.href);return!!(G()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Et(window.location.href),t=await tt(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&&!(rr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await xt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Xs(),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 w(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(_(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(_(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:i}=await this._useSession(async n=>{var o,a,c,h,l;let{data:u,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 w(this.fetch,"GET",p,{headers:this.headers,jwt:(l=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return G()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(_(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)throw o;return await w(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(s=n.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await tr(async i=>(i>0&&await er(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await w(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Z})),(i,n)=>{let o=200*Math.pow(2,i);return n&&Pt(n)&&Date.now()+o-s<ot})}catch(s){if(this._debug(t,"error",s),_(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),G()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let s=await tt(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+Zt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Zt}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Pt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",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 V;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new et;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new V;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),_(n)){let o={session:null,error:n};return Pt(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 ts(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await xt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&G()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),ot);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)/ot);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${ot}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 nt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!G()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){let i=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&i.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[n,o]=await 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 w(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await w(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(_(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await w(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(_(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await w(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(_(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],i=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.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}}))}};we.nextInstanceID=0;var yi=we,os=yi;var Rt=class extends os{constructor(e){super(e)}};var vi=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{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},at=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=Js(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:Hs,realtime:zs,auth:Object.assign(Object.assign({},Bs),{storageKey:c}),global:Fs},l=Ws(s??{},h);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=Gs(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new As(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Ne(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Qe(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 vi(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,h){var l;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Rt({url:this.authUrl,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new xe(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 dr=(r,e,t)=>new at(r,e,t);var ee={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var Le=class{constructor(){this.sessionData=null;this.supabase=dr(ee.supaBaseUrl,ee.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||ee.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||ee.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||ee.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||ee.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||ee.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||ee.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 Q=null;function as(r,e=30,t){Q&&(clearInterval(Q),Q=null);let s=e;r.style.pointerEvents="none",r.textContent=`Resend (${s}s)`,Q=setInterval(()=>{s=s-1,r.textContent=s>0?`Resend (${s}s)`:"Resend email",s===0&&(r.style.pointerEvents="auto",Q&&(clearInterval(Q),Q=null),t&&t())},1e3)}function fr(){Q&&(clearInterval(Q),Q=null)}function pr(r,e){let t=new Le,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"),h=document.querySelector("#apple-login"),l=document.querySelector("#microsoft-login"),u=document.querySelector("[email-element]"),d=document.querySelector("[different-provider]"),p=document.querySelector("[different-provider-name]"),b=document.querySelector("[different-provider-reset]"),y=document.querySelector("[email-signup-success]"),f=document.querySelector("[email-signup-error]"),m=document.querySelector("[error-message]"),L=document.querySelector("[verification-email]"),O=document.querySelector("[email-signup-retry]"),R=document.querySelector("[email-signup-reset]"),x=document.querySelector("[scim-div]"),ne=document.querySelector("[scim-reset]"),j=document.querySelector("[forgot-password]"),oe=document.querySelector("[forgot-password-success]"),ae=document.querySelector("[forgot-password-email]"),J=document.querySelector("[unverified-email]"),be=document.querySelector("[unverified-email-address]"),te=document.querySelector("[resend-verification-email]"),$e=document.querySelector("[unverified-email-reset]");e?.skipOAuthButtons||(c&&c.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","google"),await t.signInWithGoogle(r)}catch(v){console.error("Error during Google sign-in:",v)}}),h&&h.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","apple"),await t.signInWithApple(r)}catch(v){console.error("Error during Apple sign-in:",v)}}),l&&l.addEventListener("click",async()=>{try{localStorage.setItem("signin_provider","microsoft"),await t.signInWithMicrosoft(r)}catch(v){console.error("Error during Microsoft sign-in:",v)}}));let ke=()=>{d&&(d.style.display="none"),y&&(y.style.display="none"),f&&(f.style.display="none"),J&&(J.style.display="none"),x&&(x.style.display="none"),j&&(j.style.display="none"),oe&&(oe.style.display="none");let v=document.querySelector(".gs-hero_form-block");v&&(v.style.display="block"),u&&(u.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 k=document.querySelector("[captcha-embed]"),T=document.querySelector("#h-captcha-container");k&&(k.style.display="none"),T&&(T.style.display="none"),window.hcaptcha&&window.hcaptcha.reset(),s="email_input",n&&n.focus()},g=()=>{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 v=document.querySelector("[captcha-embed]"),k=document.querySelector("#h-captcha-container");v&&(v.style.display="block"),k&&(k.style.display="block"),j&&(j.style.display="block",j.onclick=async()=>{let T=n?.value||"",S=j.textContent||"";try{let{hcaptcha:M}=window;if(!M)throw new Error("Verification system not loaded. Please refresh the page.");j.style.pointerEvents="none",j.textContent="Sending...";let{response:P}=await M.execute({async:!0});if(!P)throw new Error("Verification cancelled");await Ue.requestPasswordReset(T,P),M.reset(),u&&(u.style.display="none"),j&&(j.style.display="none"),oe&&(oe.style.display="block"),ae&&(ae.textContent=T)}catch(M){console.error("Error sending password reset email:",M),j.textContent=S,j.style.pointerEvents="auto",window.hcaptcha&&window.hcaptcha.reset(),f&&(f.style.display="block",m&&(m.textContent=M instanceof Error?M.message:"Failed to send reset email"))}}),s="login"},A=()=>{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 v=document.querySelector("[captcha-embed]"),k=document.querySelector("#h-captcha-container");v&&(v.style.display="block"),k&&(k.style.display="block"),s="signup"},F=()=>{let v=document.querySelector(".gs-hero_form-block");v&&(v.style.display="none"),x&&(x.style.display="block"),ne&&(ne.onclick=()=>{x&&(x.style.display="none"),v&&(v.style.display="block"),ke()})},N=v=>{let k=ds(v);u&&(u.style.display="none"),d&&(d.style.display="block"),p&&(p.textContent=k),b&&(b.onclick=()=>{d&&(d.style.display="none"),ke()}),s="oauth_user"},B=v=>{u&&(u.style.display="none"),J&&(J.style.display="block"),be&&(be.textContent=v),te&&(te.onclick=async()=>{let k=te.textContent||"";try{let T=window.hcaptcha?await window.hcaptcha.execute({async:!0}):void 0;await t.resendVerificationEmail(v,r,T),te.textContent="Verification email resent! \u2705",te.style.textDecoration="none"}catch(T){console.error("Error resending verification email:",T),te.textContent=k}}),$e&&($e.onclick=()=>{J&&(J.style.display="none"),ke()}),s="unverified_email"},ce=async(v,k)=>{let T=k.value;k.classList.add("loading"),k.value="";try{let S=await Ue.checkUserStatus(v);k.classList.remove("loading"),k.value=T,!S.exists&&S.scim_managed?F():S.enforce_sso?N("workos"):S.exists&&S.provider&&S.provider!=="email"?N(S.provider):S.exists&&S.provider==="email"&&!S.verified?B(v):S.exists&&S.provider==="email"?g():A()}catch(S){console.error("Error checking user status:",S),k.classList.remove("loading"),k.value=T,A()}},cs=async(v,k,T,S)=>{if(!k||k.length<8){f&&(f.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}let M=window.hcaptcha?.getResponse()||"";if(!M){f&&(f.style.display="block",m&&(m.textContent="Please complete the verification"));return}T.classList.add("loading"),T.value="";try{let{accessToken:P,refreshToken:$,fullName:je}=await t.signInWithPassword(v,k,M);t.setCookies(P,$),localStorage.setItem("email",v),e?.onLoginSuccess?await e.onLoginSuccess(P,$,je):window.location.href=r}catch(P){if(console.error("Login error:",P),window.hcaptcha&&window.hcaptcha.reset(),T.classList.remove("loading"),T.value=S,f&&(f.style.display="block",m)){let $=P instanceof Error?P.message:"Invalid login credentials";m.textContent=$}}},Ct=async(v,k,T,S,M)=>{if(!k||k.length<8){f&&(f.style.display="block",m&&(m.textContent="Password must be at least 8 characters"));return}if(!T||T.trim().length<2){f&&(f.style.display="block",m&&(m.textContent="Please enter your full name"));return}let P=window.hcaptcha?.getResponse()||"";if(!P){f&&(f.style.display="block",m&&(m.textContent="Please complete the verification"));return}S.classList.add("loading"),S.value="";try{await t.signUpWithPassword(v,k,T,r,P),window.hcaptcha&&window.hcaptcha.reset(),S.classList.remove("loading"),S.value=M,u&&(u.style.display="none"),f&&(f.style.display="none"),y&&(y.style.display="block"),L&&(L.textContent=v),O&&(as(O,30),O.onclick=async()=>{if(O.style.pointerEvents!=="none")try{let $=window.hcaptcha?.getResponse()||"";await t.signUpWithPassword(v,k,T,r,$),window.hcaptcha&&window.hcaptcha.reset(),as(O,30)}catch($){console.error("Error resending verification email:",$)}}),R&&(R.onclick=()=>{y&&(y.style.display="none"),fr(),ke()})}catch($){if(console.error("Signup error:",$),S.classList.remove("loading"),S.value=M,f&&(f.style.display="block",m)){let je=$ instanceof Error?$.message:"Signup failed";m.textContent=je}}};i&&i.addEventListener("submit",async v=>{v.stopPropagation(),v.preventDefault();let k=n?.value||"",T=o?.value||"",S=a?.value||"";if(!k||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(k)){f&&(f.style.display="block",m&&(m.textContent="Please enter a valid email address"));return}f&&(f.style.display="none"),m&&(m.textContent="");let P=i.querySelector('[type="submit"]'),$=P?.value||"";localStorage.setItem("signin_provider","email");try{s==="email_input"?await ce(k,P):s==="login"?await cs(k,T,P,$):s==="signup"&&await Ct(k,T,S,P,$)}catch(je){console.error("Auth flow error:",je),P&&(P.classList.remove("loading"),P.value=$),f&&(f.style.display="block")}})}var gr=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var I=(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(()=>I(r,e,t-1),200)};var mr="https://api.wisprflow.ai",wi="https://wisprflow.ai";window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let r=new Le,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("#google-login"),h=document.querySelector("#apple-login"),l=document.querySelector("#microsoft-login"),u=localStorage.getItem("last_authed_provider");u&&{google:c,apple:h,microsoft:l,sso:document.querySelector("#sso-login"),email:document.querySelector("#email-input")}[u]?.classList.add("last-used");let d=()=>{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"},p=()=>{let g=localStorage.getItem("signin_provider");g&&localStorage.setItem("last_authed_provider",g),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"},b=g=>{e&&(e.style.display="none"),t&&(t.style.display="none"),s&&(s.style.display="block"),i&&(i.textContent=g),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"},f=document.querySelector("[retry-button]");f&&f.addEventListener("click",()=>m());let m=()=>{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"},L=async(g,A)=>{try{let[F,N]=us(A||" "),B=Ue.signupUser({access_token:g,first_name:F,last_name:N}),ce=new Promise((cs,Ct)=>setTimeout(()=>Ct(new Error("signup timeout")),4e3));await Promise.race([B,ce])}catch(F){I("signup_sync_error",{error_message:F instanceof Error?F.message:String(F)})}},O=()=>{let g=sessionStorage.getItem("wispr_fbclid");return g?`fb.1.${Date.now()}.${g}`:null},R=async(g,A)=>{let F=sessionStorage.getItem("wispr_device_code");if(!F)throw new Error("Device code not found. Please restart authentication from desktop app.");let N=gr(),B=await fetch(`${mr}/device/complete`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`${g}`},body:JSON.stringify({device_code:F,access_token:g,refresh_token:A,fbp:N._fbp||void 0,fbc:N._fbc||O()||void 0})});if(!B.ok){let ce=await B.json().catch(()=>({}));throw B.status===403&&ce?.detail?.code==="enterprise_ip_not_allowed"?new Error("enterprise_ip_not_allowed"):new Error(ce?.detail?.message||ce.message||`Server error: ${B.status}`)}console.log("Device authentication complete:",await B.json()),sessionStorage.removeItem("wispr_device_code")},x=new URLSearchParams(window.location.search),ne=x.get("device_code"),j=x.get("auto_signin")==="true",oe=new URLSearchParams(window.location.hash.slice(1)),ae=x.get("access_token")||oe.get("access_token"),J=x.get("refresh_token")||oe.get("refresh_token");if(!ne&&!ae&&!J&&!sessionStorage.getItem("wispr_device_code")){console.log("No device_code found - redirecting to /get-started"),I("desktop_login_no_device_code"),window.location.href="/get-started";return}if(I("desktop_login_page_view",{auto_signin:j}),ne){sessionStorage.setItem("wispr_device_code",ne),console.log("Device code stored:",ne);let g=x.get("fbclid");g&&sessionStorage.setItem("wispr_fbclid",g),window.history.replaceState({},"","/login")}if(ae&&J){console.log("OAuth callback detected - handling tokens"),I("desktop_login_oauth_callback",{provider:localStorage.getItem("signin_provider")??"unknown"}),d();try{let g=ae,A=J;try{r.setCookies(ae,J),await r.checkAndSetSession(),r.sessionData&&(g=r.sessionData.access_token,A=r.sessionData.refresh_token,r.setCookies(g,A),localStorage.setItem("email",r.sessionData.user.email),r.sessionData.user.id&&localStorage.setItem("user_id",r.sessionData.user.id))}catch{}await L(g,r.sessionData?.user.user_metadata?.full_name),await R(g,A),I("desktop_login_complete_success",{method:"oauth"}),p()}catch(g){if(g instanceof Error&&g.message==="enterprise_ip_not_allowed"){I("desktop_login_complete_error",{method:"oauth",error:"enterprise_ip_not_allowed"}),y();return}let A=g instanceof Error?g.message:"Failed to complete authentication. Please try again.";I("desktop_login_complete_error",{method:"oauth",error:A}),console.error("Error completing device authentication:",g),b(A)}return}if(j){console.log("Auto-signin enabled - checking existing session"),d();try{let g=r.checkAndSetSession(),A=new Promise((F,N)=>setTimeout(()=>N(new Error("Session timeout")),3e3));if(await Promise.race([g,A]),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 L(r.sessionData.access_token,r.sessionData?.user.user_metadata?.full_name),await R(r.sessionData.access_token,r.sessionData.refresh_token),I("desktop_login_auto_signin_success"),p();return}console.log("No existing session - showing login form"),I("desktop_login_auto_signin_no_session"),m()}catch(g){if(console.error("Auto-signin error:",g),g instanceof Error&&g.message==="enterprise_ip_not_allowed"){I("desktop_login_auto_signin_error",{error:"enterprise_ip_not_allowed"}),y();return}let A=g instanceof Error?g.message:"Auto-signin failed. Please try logging in manually.";I("desktop_login_auto_signin_error",{error:A}),r.setCookie("access_token","",-1),r.setCookie("refresh_token","",-1),m()}}else I("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"),m();let be=g=>{console.log(`Redirecting to ${g} OAuth`),I("desktop_login_oauth_click",{provider:g}),localStorage.setItem("signin_provider",g);let A=`${mr}/${g}/sign_in?source=${wi}`;window.location.href=A};c&&c.addEventListener("click",()=>{be("google")}),h&&h.addEventListener("click",()=>{be("apple")}),l&&l.addEventListener("click",()=>{be("microsoft")});let te=async(g,A,F)=>{try{await L(g,F),await R(g,A)}catch(N){if(N instanceof Error&&N.message==="enterprise_ip_not_allowed"){I("desktop_login_complete_error",{method:"email",error:"enterprise_ip_not_allowed"}),y();return}let B=N instanceof Error?N.message:"Failed to complete authentication. Please try again.";I("desktop_login_complete_error",{method:"email",error:B}),b(B);return}I("desktop_login_complete_success",{method:"email"}),p()},$e=sessionStorage.getItem("wispr_device_code"),ke=$e?`${window.location.origin}/login?device_code=${$e}`:`${window.location.origin}/login`;pr(ke,{onLoginSuccess:te,skipOAuthButtons:!0}),console.log("Desktop login page initialized")});})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanay-wispr/webflow-package",
3
- "version": "6.6.5",
3
+ "version": "6.6.7",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },