@tanay-wispr/webflow-package 3.6.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ "use strict";(()=>{var Hs=Object.create;var Ie=Object.defineProperty;var Js=Object.getOwnPropertyDescriptor;var zs=Object.getOwnPropertyNames;var Gs=Object.getPrototypeOf,Ws=Object.prototype.hasOwnProperty;var Ks=(r,e)=>()=>(r&&(e=r(r=0)),e);var P=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Vs=(r,e)=>{for(var t in e)Ie(r,t,{get:e[t],enumerable:!0})},Ut=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of zs(e))!Ws.call(r,i)&&i!==t&&Ie(r,i,{get:()=>e[i],enumerable:!(s=Js(e,i))||s.enumerable});return r};var Dt=(r,e,t)=>(t=r!=null?Hs(Gs(r)):{},Ut(e||!r||!r.__esModule?Ie(t,"default",{value:r,enumerable:!0}):t,r)),Qs=r=>Ut(Ie({},"__esModule",{value:!0}),r);var q={};Vs(q,{Headers:()=>ct,Request:()=>Zs,Response:()=>er,default:()=>at,fetch:()=>Xs});var Ys,X,Xs,at,ct,Zs,er,D=Ks(()=>{"use strict";Ys=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")},X=Ys(),Xs=X.fetch,at=X.fetch.bind(X),ct=X.Headers,Zs=X.Request,er=X.Response});var Ht=P(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});var lt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};ht.default=lt});var dt=P(ue=>{"use strict";var Jt=ue&&ue.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ue,"__esModule",{value:!0});var sr=Jt((D(),Qs(q))),rr=Jt(Ht()),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=sr.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,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let k=await n.text();k===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=k:l=JSON.parse(k))}let v=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),m=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");v&&m&&m.length>1&&(u=parseInt(m[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(h={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,u=null,d=406,f="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let v=await n.text();try{h=JSON.parse(v),Array.isArray(h)&&n.status===404&&(l=[],h=null,d=200,f="OK")}catch{n.status===404&&v===""?(d=204,f="No Content"):h={message:v}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new rr.default(h)}return{error:h,data:l,count:u,status:d,statusText:f}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};ue.default=ut});var pt=P(de=>{"use strict";var ir=de&&de.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(de,"__esModule",{value:!0});var nr=ir(dt()),ft=class extends nr.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=ft});var qe=P(fe=>{"use strict";var or=fe&&fe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(fe,"__esModule",{value:!0});var ar=or(pt()),gt=class extends ar.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=gt});var mt=P(ge=>{"use strict";var cr=ge&&ge.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ge,"__esModule",{value:!0});var pe=cr(qe()),_t=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 pe.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 pe.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 pe.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 pe.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 pe.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ge.default=_t});var zt=P(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.version=void 0;Me.version="0.0.0-automated"});var Gt=P(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.DEFAULT_HEADERS=void 0;var lr=zt();Be.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${lr.version}`}});var Kt=P(_e=>{"use strict";var Wt=_e&&_e.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(_e,"__esModule",{value:!0});var hr=Wt(mt()),ur=Wt(qe()),dr=Gt(),vt=class r{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},dr.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new hr.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||i?(o=s?"HEAD":"GET",Object.entries(t).filter(([l,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 ur.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};_e.default=vt});var es=P(b=>{"use strict";var me=b&&b.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(b,"__esModule",{value:!0});b.PostgrestBuilder=b.PostgrestTransformBuilder=b.PostgrestFilterBuilder=b.PostgrestQueryBuilder=b.PostgrestClient=void 0;var Vt=me(Kt());b.PostgrestClient=Vt.default;var Qt=me(mt());b.PostgrestQueryBuilder=Qt.default;var Yt=me(qe());b.PostgrestFilterBuilder=Yt.default;var Xt=me(pt());b.PostgrestTransformBuilder=Xt.default;var Zt=me(dt());b.PostgrestBuilder=Zt.default;b.default={PostgrestClient:Vt.default,PostgrestQueryBuilder:Qt.default,PostgrestFilterBuilder:Yt.default,PostgrestTransformBuilder:Xt.default,PostgrestBuilder:Zt.default}});var ls=P((Ii,cs)=>{"use strict";cs.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Le="https://staging.aria-web.wispr.ai",nt=class{static async signupUser(e){try{let t=await fetch(`${Le}/signup`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Signup failed with status ${t.status}`);console.log("User signed up successfully")}catch(t){console.error("Error during signup:",t)}}static async addRawUserEmail(e){try{let t=await fetch(`${Le}/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}`)}catch(t){console.error("Error during raw user signup:",t)}}static async addToWaitlist(e){try{let t=await fetch(`${Le}/add_to_waitlist`,{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 applyReferralCode(e){try{let t=await fetch(`${Le}/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}}};function Nt(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}var ot=nt;var Ft=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var qt=()=>{let r=window.location.hash.substring(1),e=new URLSearchParams(r);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var Mt=()=>{let{access_token:r,refresh_token:e}=qt(),t=r,s=e;if(!t||!s){let i=Ft();t=i.access_token,s=i.refresh_token}return{accessToken:t,refreshToken:s}};var Bt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(D(),q)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var le=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},Ue=class extends le{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},De=class extends le{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Ne=class extends le{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Fe;(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"})(Fe||(Fe={}));var tr=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())})},he=class{constructor(e,{headers:t={},customFetch:s,region:i=Fe.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Bt(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return tr(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(_=>{throw new Ue(_)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new De(l);if(!l.ok)throw new Ne(l);let d=((s=l.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield l.json():d==="application/octet-stream"?f=yield l.blob():d==="text/event-stream"?f=l:d==="multipart/form-data"?f=yield l.formData():f=yield l.text(),{data:f,error:null}}catch(i){return{data:null,error:i}}})}};var ts=Dt(es(),1),{PostgrestClient:ss,PostgrestQueryBuilder:gi,PostgrestFilterBuilder:_i,PostgrestTransformBuilder:mi,PostgrestBuilder:vi}=ts.default;var rs="2.10.2";var is={"X-Client-Info":`realtime-js/${rs}`},ns="1.0.0",Je=1e4,os=1e3,M;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(M||(M={}));var S;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(S||(S={}));var E;(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"})(E||(E={}));var He;(function(r){r.websocket="websocket"})(He||(He={}));var N;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(N||(N={}));var ve=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 B=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 y;(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"})(y||(y={}));var wt=(r,e,t={})=>{var s;let i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=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)?as(n,o):yt(o)},as=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return mr(e,t)}switch(r){case y.bool:return pr(e);case y.float4:case y.float8:case y.int2:case y.int4:case y.int8:case y.numeric:case y.oid:return gr(e);case y.json:case y.jsonb:return _r(e);case y.timestamp:return vr(e);case y.abstime:case y.date:case y.daterange:case y.int4range:case y.int8range:case y.money:case y.reltime:case y.text:case y.time:case y.timestamptz:case y.timetz:case y.tsrange:case y.tstzrange:return yt(e);default:return yt(e)}},yt=r=>r,pr=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},gr=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},_r=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},mr=(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=>as(e,a))}return r},vr=r=>typeof r=="string"?r.replace(" ","T"):r,ze=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var H=class{constructor(e,t,s={},i=Je){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 bt;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(bt||(bt={}));var Z=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(m=>m.presence_ref),f=u.map(m=>m.presence_ref),_=l.filter(m=>f.indexOf(m.presence_ref)<0),v=u.filter(m=>d.indexOf(m.presence_ref)<0);_.length>0&&(a[h]=_),v.length>0&&(c[h]=v)}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(f=>f.presence_ref),d=l.filter(f=>u.indexOf(f.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 St;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(St||(St={}));var Et;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Et||(Et={}));var ee=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=S.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 H(this,E.join,this.params,this.timeout),this.rejoinTimer=new B(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=S.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=S.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=S.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=S.errored,this.rejoinTimer.scheduleTimeout())}),this._on(E.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new Z(this),this.broadcastEndpointURL=ze(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,f=(u=d?.length)!==null&&u!==void 0?u:0,_=[];for(let v=0;v<f;v++){let m=d[v],{filter:{event:k,schema:I,table:R,filter:A}}=m,O=l&&l[v];if(O&&O.event===k&&O.schema===I&&O.table===R&&O.filter===A)_.push(Object.assign(Object.assign({},m),{id:O.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,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=S.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(E.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let i=new H(this,E.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 H(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}=E;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(f=>{var _,v,m;return((_=f.filter)===null||_===void 0?void 0:_.event)==="*"||((m=(v=f.filter)===null||v===void 0?void 0:v.event)===null||m===void 0?void 0:m.toLocaleLowerCase())===o}).map(f=>f.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var _,v,m,k,I,R;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let A=f.id,O=(_=f.filter)===null||_===void 0?void 0:_.event;return A&&((v=t.ids)===null||v===void 0?void 0:v.includes(A))&&(O==="*"||O?.toLocaleLowerCase()===((m=t.data)===null||m===void 0?void 0:m.type.toLocaleLowerCase()))}else{let A=(I=(k=f?.filter)===null||k===void 0?void 0:k.event)===null||I===void 0?void 0:I.toLocaleLowerCase();return A==="*"||A===((R=t?.event)===null||R===void 0?void 0:R.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let _=d.data,{schema:v,table:m,commit_timestamp:k,type:I,errors:R}=_;d=Object.assign(Object.assign({},{schema:v,table:m,commit_timestamp:k,eventType:I,new:{},old:{},errors:R}),this._getPayloadRecords(_))}f.callback(d,s)})}_isClosed(){return this.state===S.closed}_isJoined(){return this.state===S.joined}_isJoining(){return this.state===S.joining}_isLeaving(){return this.state===S.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(E.close,{},e)}_onError(e){this._on(E.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=S.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=wt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=wt(e.columns,e.old_record)),t}};var wr=()=>{},br=typeof WebSocket<"u",te=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=is,this.params={},this.timeout=Je,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=wr,this.conn=null,this.sendBuffer=[],this.serializer=new ve,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(D(),q)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${He.websocket}`,this.httpEndpoint=ze(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 B(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(br){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Tt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Dt(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 M.connecting:return N.Connecting;case M.open:return N.Open;case M.closing:return N.Closing;default:return N.Closed}}isConnected(){return this.connectionState()===N.Open}channel(e,t={config:{}}){let s=new ee(`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(E.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:ns}))}_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(E.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(os,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Tt=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=M.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var se=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function w(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Ge=class extends se{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},ye=class extends se{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var kr=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=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(D(),q)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},hs=()=>kr(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(D(),q))).Response:Response});var re=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),Sr=(r,e)=>re(void 0,void 0,void 0,function*(){let t=yield hs();r instanceof t?r.json().then(s=>{e(new Ge(xt(s),r.status||500))}).catch(s=>{e(new ye(xt(s),s))}):e(new ye(xt(r),r))}),Er=(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 Ke(r,e,t,s,i,n){return re(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,Er(e,s,i,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Sr(c,a))})})}function we(r,e,t,s){return re(this,void 0,void 0,function*(){return Ke(r,"GET",e,t,s)})}function j(r,e,t,s,i){return re(this,void 0,void 0,function*(){return Ke(r,"POST",e,s,i,t)})}function us(r,e,t,s,i){return re(this,void 0,void 0,function*(){return Ke(r,"PUT",e,s,i,t)})}function Ve(r,e,t,s,i){return re(this,void 0,void 0,function*(){return Ke(r,"DELETE",e,s,i,t)})}var T=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())})},Tr={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ds={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},be=class{constructor(e,t={},s,i){this.url=e,this.headers=t,this.bucketId=s,this.fetch=We(i)}uploadOrUpdate(e,t,s,i){return T(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(w(n))return{data:null,error:n};throw n}})}upload(e,t,s){return T(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return T(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(w(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return T(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 j(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 se("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(w(s))return{data:null,error:s};throw s}})}update(e,t,s){return T(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return T(this,void 0,void 0,function*(){try{return{data:yield j(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(w(i))return{data:null,error:i};throw i}})}copy(e,t,s){return T(this,void 0,void 0,function*(){try{return{data:{path:(yield j(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(w(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return T(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield j(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(w(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return T(this,void 0,void 0,function*(){try{let i=yield j(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(w(i))return{data:null,error:i};throw i}})}download(e,t){return T(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 we(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(w(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 T(this,void 0,void 0,function*(){try{return{data:yield Ve(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}})}list(e,t,s){return T(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Tr),t),{prefix:e||""});return{data:yield j(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if(w(i))return{data:null,error:i};throw i}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var fs="2.6.0";var ps={"X-Client-Info":`storage-js/${fs}`};var ie=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())})},ke=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},ps),t),this.fetch=We(s)}listBuckets(){return ie(this,void 0,void 0,function*(){try{return{data:yield we(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(w(e))return{data:null,error:e};throw e}})}getBucket(e){return ie(this,void 0,void 0,function*(){try{return{data:yield we(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return ie(this,void 0,void 0,function*(){try{return{data:yield j(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(w(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return ie(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(w(s))return{data:null,error:s};throw s}})}emptyBucket(e){return ie(this,void 0,void 0,function*(){try{return{data:yield j(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}})}deleteBucket(e){return ie(this,void 0,void 0,function*(){try{return{data:yield Ve(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}})}};var Se=class extends ke{constructor(e,t={},s){super(e,t,s)}from(e){return new be(this.url,this.headers,e,this.fetch)}};var gs="2.44.4";var Ee="";typeof Deno<"u"?Ee="deno":typeof document<"u"?Ee="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ee="react-native":Ee="node";var xr={"X-Client-Info":`supabase-js-${Ee}/${gs}`},_s={headers:xr},ms={schema:"public"},vs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ys={};D();var Ar=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())})},Or=r=>{let e;return r?e=r:typeof fetch>"u"?e=at:e=fetch,(...t)=>e(...t)},Rr=()=>typeof Headers>"u"?ct:Headers,ws=(r,e,t)=>{let s=Or(t),i=Rr();return(n,o)=>Ar(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 bs(r){return r.replace(/\/$/,"")}function ks(r,e){let{db:t,auth:s,realtime:i,global:n}=r,{db:o,auth:a,realtime:c,global: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 Qe="2.64.4";var Ss="http://localhost:9999",Es="supabase.auth.token";var Ts={"X-Client-Info":`gotrue-js/${Qe}`},At=10;var Te="X-Supabase-Api-Version",Ot={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function xs(r){return Math.round(Date.now()/1e3)+r}function As(){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 x=()=>typeof document<"u",J={tested:!1,writable:!1},F=()=>{if(!x())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(J.tested)return J.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),J.tested=!0,J.writable=!0}catch{J.tested=!0,J.writable=!1}return J.writable};function Ye(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 Xe=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(D(),q)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Os=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",Rt=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},Ae=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Ze=async(r,e)=>{await r.removeItem(e)};function Pr(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 xe=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};xe.promiseConstructor=Promise;function Pt(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(Pr(s))}async function Rs(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function Ps(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 jr(r){return("0"+r.toString(16)).substr(-2)}function Cr(){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,jr).join("")}async function $r(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 Ir(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Lr(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 $r(r);return Ir(t)}async function z(r,e,t=!1){let s=Cr(),i=s;t&&(i+="/PASSWORD_RECOVERY"),await Rt(r,`${e}-code-verifier`,i);let n=await Lr(s);return[n,s===n?"plain":"s256"]}var Ur=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function js(r){let e=r.headers.get(Te);if(!e||!e.match(Ur))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Oe=class extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}};function p(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var et=class extends Oe{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function Cs(r){return p(r)&&r.name==="AuthApiError"}var ne=class extends Oe{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},L=class extends Oe{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}},C=class extends L{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},oe=class extends L{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},G=class extends L{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},W=class extends L{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}}},Re=class extends L{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}}},ae=class extends L{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function tt(r){return p(r)&&r.name==="AuthRetryableFetchError"}var Pe=class extends L{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var Dr=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},K=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Nr=[502,503,504];async function $s(r){var e;if(!Os(r))throw new ae(K(r),0);if(Nr.includes(r.status))throw new ae(K(r),r.status);let t;try{t=await r.json()}catch(n){throw new ne(K(n),n)}let s,i=js(r);if(i&&i.getTime()>=Ot["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 Pe(K(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 Pe(K(t),r.status,t.weak_password.reasons);throw new et(K(t),r.status||500,s)}var Fr=(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 g(r,e,t,s){var i;let n=Object.assign({},s?.headers);n[Te]||(n[Te]=Ot["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 qr(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 qr(r,e,t,s,i,n){let o=Fr(e,s,i,n),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new ae(K(c),0)}if(a.ok||await $s(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await $s(c)}}function U(r){var e;let t=null;Mr(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=xs(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function jt(r){let e=U(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 $(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function Is(r){return{data:r,error:null}}function Ls(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=Dr(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 Us(r){return r}function Mr(r){return r.access_token&&r.refresh_token&&r.expires_in}var Br=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},V=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=Xe(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await g(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(p(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await g(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:$})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=Br(e,["options"]),i=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(i.new_email=s?.newEmail,delete i.newEmail),await g(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Ls,redirectTo:t?.redirectTo})}catch(t){if(p(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await g(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:$})}catch(t){if(p(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 g(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:Us});if(l.error)throw l.error;let u=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(_=>{let v=parseInt(_.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(_.split(";")[1].split("=")[1]);h[`${m}Page`]=v}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(p(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:$})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:$})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:$})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(p(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}};var Ds={getItem:r=>F()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{F()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{F()&&globalThis.localStorage.removeItem(r)}};function Ct(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function Ns(){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 Q={debug:!!(globalThis&&F()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},je=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},st=class extends je{};async function $t(r,e,t){Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Q.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){Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new st(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Q.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()}})}Ns();var Hr={url:Ss,storageKey:Es,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ts,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Ce=30*1e3,Fs=3;async function qs(r,e,t){return await t()}var Y=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&&x()&&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({},Hr),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 V({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Xe(i.fetch),this.lock=i.lock||qs,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:x()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=$t:this.lock=qs,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:F()?this.storage=Ds:(this.memoryStorage={},this.storage=Ct(this.memoryStorage)):(this.memoryStorage={},this.storage=Ct(this.memoryStorage)),x()&&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} (${Qe}) ${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=x()?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 p(e)?{error:e}:{error:new ne("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{let n=await g(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:U}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,i;try{let n;if("email"in e){let{email:l,password:u,options:d}=e,f=null,_=null;this.flowType==="pkce"&&([f,_]=await z(this.storage,this.storageKey)),n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:_},xform:U})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:u,data:(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:U})}else throw new G("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:jt})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:jt})}else throw new G("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 oe}:(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(p(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 Ae(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(t??"").split("/"),{data:n,error:o}=await g(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:U});return await Ze(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 oe}:(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 g(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:U}),{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 oe}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,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 z(this.storage,this.storageKey));let{error:u}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(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 g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:l}}throw new G("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,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 g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:U});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(p(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,s,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await z(this.storage,this.storageKey)),await g(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(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:Is})}catch(n){if(p(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new C;let{error:i}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(p(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:n}=e,{error:o}=await g(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 g(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 G("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let 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 Ae(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 g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:$}):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 C}:await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:$})})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{let{data:i,error:n}=s;if(n)throw n;if(!i.session)throw new C;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await z(this.storage,this.storageKey));let{data:h,error:l}=await g(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:$});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(p(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return Pt(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 C;let t=Date.now()/1e3,s=t,i=!0,n=null,o=Pt(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(p(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var 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 C;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!x())throw new W("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new W("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Re("Not a valid PKCE flow url.");let t=Ye(window.location.href);if(e){if(!t.code)throw new Re("No code detected.");let{data:I,error:R}=await this._exchangeCodeForSession(t.code);if(R)throw R;let A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:I.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new W(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 W("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;c&&(d=parseInt(c));let f=d-l;f*1e3<=Ce&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let _=d-u;l-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,d,l):l-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",_,d,l);let{data:v,error:m}=await this._getUser(n);if(m)throw m;let k={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:k,redirectType:t.type},error:null}}catch(t){if(p(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Ye(window.location.href);return!!(x()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Ye(window.location.href),t=await Ae(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&&!(Cs(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Ze(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=As(),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 z(this.storage,this.storageKey,!0));try{return await g(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(p(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(p(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 f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await g(this.fetch,"GET",f,{headers:this.headers,jwt:(l=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return x()&&!(!((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(p(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 g(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(p(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let s=Date.now();return await Ps(async i=>(i>0&&await Rs(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await g(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:U})),(i,n)=>{let o=200*Math.pow(2,i);return n&&tt(n)&&Date.now()+o-s<Ce})}catch(s){if(this._debug(t,"error",s),p(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),x()&&!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 Ae(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+At;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${At}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),tt(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 C;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new xe;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new C;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),p(n)){let o={session:null,error:n};return tt(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 Rt(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Ze(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&x()&&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(),Ce);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)/Ce);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Ce}ms, refresh threshold is ${Fs} ticks`),i<=Fs&&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 je)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!x()||!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 z(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 g(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(p(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 g(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(p(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(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(p(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(p(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}}))}};Y.nextInstanceID=0;var Jr=Y,It=Jr;var rt=class extends It{constructor(e){super(e)}};var zr=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())})},$e=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=bs(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:ms,realtime:ys,auth:Object.assign(Object.assign({},vs),{storageKey:c}),global:_s},l=ks(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=ws(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new ss(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new he(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Se(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 zr(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 te(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 Ms=(r,e,t)=>new $e(r,e,t);var ce={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var it=class{constructor(){this.sessionData=null;this.supabase=Ms(ce.supaBaseUrl,ce.supaBaseKey)}async signInWithGoogle(){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:ce.redirectUri}}),console.log("Signed in with Google")}catch(e){throw console.error("Error signing in with Google:",e),e}}async signInWithApple(){try{await this.supabase.auth.signInWithOAuth({provider:"apple",options:{redirectTo:ce.redirectUri}}),console.log("Signed in with Apple")}catch(e){throw console.error("Error signing in with Apple:",e),e}}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 this.signOut(),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){try{let{error:t}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:ce.redirectUri}});if(t)throw t}catch(t){throw console.error("Error sending magic link:",t),t}}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 Bs=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var Lt=(r,e)=>{window.posthog.capture(r,e)};window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let r=new it,{accessToken:e,refreshToken:t}=Mt(),s=document.querySelector("#hello-text"),i=document.querySelector("#logout-button");i.hidden=!0;let n=Bs(),{dclid:o,referral:a}=n,c=localStorage.getItem("email")||"";if(e&&t)try{r.setCookies(e,t),await r.checkAndSetSession();let u=r.sessionData?.user.email,d=r.sessionData?.user.user_metadata.full_name||" ",[f,_]=Nt(d),v={access_token:e,first_name:f,last_name:_,dub_click_id:o||void 0,referral:a||void 0};localStorage.setItem("email",u),s.textContent=`Hi ${f}!`,i.hidden=!1,await ot.signupUser(v)}catch(u){window.location.href="/get-started",console.error("Error during session setup:",u)}else c?(s.textContent=`Hi ${c}!`,i.hidden=!1):window.location.href="/get-started";document.querySelectorAll("[active-download]").forEach(function(u){u.onclick=()=>(Lt("app_download",{device_type:u.getAttribute("active-download")}),!0)}),document.querySelectorAll("[waitlist]").forEach(function(u){u.onclick=()=>{Lt("app_waitlist",{device_type:u.getAttribute("waitlist")});let d={email:c,device_type:u.getAttribute("waitlist")||"unknown"};return ot.addToWaitlist(d),u.innerText="You're on the waitlist!",!0}}),i.addEventListener("click",async()=>{try{await r.signOut(),localStorage.removeItem("email"),window.location.href="/get-started"}catch(u){console.error("Error during sign-out:",u)}})});})();
package/dist/signup.js CHANGED
@@ -1 +1 @@
1
- "use strict";(()=>{var Zr=Object.create;var Ne=Object.defineProperty;var es=Object.getOwnPropertyDescriptor;var ts=Object.getOwnPropertyNames;var rs=Object.getPrototypeOf,ss=Object.prototype.hasOwnProperty;var is=(s,e)=>()=>(s&&(e=s(s=0)),e);var j=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),ns=(s,e)=>{for(var t in e)Ne(s,t,{get:e[t],enumerable:!0})},Bt=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ts(e))!ss.call(s,i)&&i!==t&&Ne(s,i,{get:()=>e[i],enumerable:!(r=es(e,i))||r.enumerable});return s};var Mt=(s,e,t)=>(t=s!=null?Zr(rs(s)):{},Bt(e||!s||!s.__esModule?Ne(t,"default",{value:s,enumerable:!0}):t,s)),os=s=>Bt(Ne({},"__esModule",{value:!0}),s);var H={};ns(H,{Headers:()=>ft,Request:()=>cs,Response:()=>hs,default:()=>dt,fetch:()=>ls});var as,te,ls,dt,ft,cs,hs,F=is(()=>{"use strict";as=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")},te=as(),ls=te.fetch,dt=te.fetch.bind(te),ft=te.Headers,cs=te.Request,hs=te.Response});var Yt=j(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});var pt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};gt.default=pt});var _t=j(ge=>{"use strict";var Zt=ge&&ge.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ge,"__esModule",{value:!0});var ds=Zt((F(),os(H))),fs=Zt(Yt()),mt=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=ds.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let h=null,c=null,u=null,d=n.status,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let S=await n.text();S===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=S:c=JSON.parse(S))}let y=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),m=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");y&&m&&m.length>1&&(u=parseInt(m[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(h={code:"PGRST116",details:`Results contain ${c.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},c=null,u=null,d=406,f="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{let y=await n.text();try{h=JSON.parse(y),Array.isArray(h)&&n.status===404&&(c=[],h=null,d=200,f="OK")}catch{n.status===404&&y===""?(d=204,f="No Content"):h={message:y}}if(h&&this.isMaybeSingle&&(!((l=h?.details)===null||l===void 0)&&l.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new fs.default(h)}return{error:h,data:c,count:u,status:d,statusText:f}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,l;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:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};ge.default=mt});var vt=j(me=>{"use strict";var ps=me&&me.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(me,"__esModule",{value:!0});var gs=ps(_t()),yt=class extends gs.default{select(e){let t=!1,r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:i=r}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let l=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; options=${l};`,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}};me.default=yt});var Ge=j(_e=>{"use strict";var ms=_e&&_e.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(_e,"__esModule",{value:!0});var _s=ms(vt()),wt=class extends _s.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};_e.default=wt});var kt=j(ve=>{"use strict";var ys=ve&&ve.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ve,"__esModule",{value:!0});var ye=ys(Ge()),bt=class{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new ye.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new ye.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let l=e.reduce((h,c)=>h.concat(Object.keys(c)),[]);if(l.length>0){let h=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",h.join(","))}}return new ye.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new ye.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new ye.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ve.default=bt});var er=j(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.version=void 0;Je.version="0.0.0-automated"});var tr=j(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.DEFAULT_HEADERS=void 0;var vs=er();ze.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${vs.version}`}});var sr=j(we=>{"use strict";var rr=we&&we.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(we,"__esModule",{value:!0});var ws=rr(kt()),bs=rr(Ge()),ks=tr(),St=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},ks.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new ws.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new s(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),l;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([c,u])=>u!==void 0).map(([c,u])=>[c,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([c,u])=>{a.searchParams.append(c,u)})):(o="POST",l=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new bs.default({method:o,url:a,headers:h,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};we.default=St});var cr=j(E=>{"use strict";var be=E&&E.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(E,"__esModule",{value:!0});E.PostgrestBuilder=E.PostgrestTransformBuilder=E.PostgrestFilterBuilder=E.PostgrestQueryBuilder=E.PostgrestClient=void 0;var ir=be(sr());E.PostgrestClient=ir.default;var nr=be(kt());E.PostgrestQueryBuilder=nr.default;var or=be(Ge());E.PostgrestFilterBuilder=or.default;var ar=be(vt());E.PostgrestTransformBuilder=ar.default;var lr=be(_t());E.PostgrestBuilder=lr.default;E.default={PostgrestClient:ir.default,PostgrestQueryBuilder:nr.default,PostgrestFilterBuilder:or.default,PostgrestTransformBuilder:ar.default,PostgrestBuilder:lr.default}});var yr=j((sn,_r)=>{"use strict";_r.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Fe="https://api.flowvoice.ai",ht=class{static async signupUser(e){try{let t=await fetch(`${Fe}/signup`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Signup failed with status ${t.status}`);console.log("User signed up successfully")}catch(t){console.error("Error during signup:",t)}}static async addRawUserEmail(e){try{let t=await fetch(`${Fe}/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}`)}catch(t){console.error("Error during raw user signup:",t)}}static async updateUser(e){try{let t=await fetch(`${Fe}/signup_update`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`UpdateUser failed with status ${t.status}`);return(await t.json()).waitlist_number}catch(t){return console.error("Error during updating user:",t),-1}}static async applyReferralCode(e){try{let t=await fetch(`${Fe}/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}}};function qt(s){let[e,...t]=s.split(" "),r=t.join(" ");return[e,r]}var Ht=ht;var Gt=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var Jt=()=>{let s=window.location.hash.substring(1),e=new URLSearchParams(s);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var zt=()=>{let{access_token:s,refresh_token:e}=Jt(),t=s,r=e;if(!t||!r){let i=Gt();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var v="data",b={googleLoginButton:`[${v}="google-login"]`,getStartedLoader:`[${v}="get-started-loader"]`,logOutButton:`[${v}="logout-button"]`,email:`[${v}="email"]`,emailField:`[${v}="email-field"]`,magicLink:`[${v}="magic-link"]`,successBlock:`[${v}="success-block"]`,magicLinkEmail:`[${v}="magic-link-email"]`,emailFormWrapper:`[${v}="email-form-wrapper"]`,platformBlock:`[${v}="platform-block"]`,socialBlock:`[${v}="social-block"]`,downloadBlock:`[${v}="download-block"]`,priorityBlock:`[${v}="priority-block"]`,thankyouBlock:`[${v}="thankyou-block"]`,referralBlock:`[${v}="referral-block"]`,referralAppliedBlock:`[${v}="referral-applied-block"]`,platformBlockButton:`[${v}="platform-block-button"]`,socialBlockButton:`[${v}="social-block-button"]`,downloadBlockButton:`[${v}="download-block-button"]`,referralBlockButton:`[${v}="referral-block-button"]`,platformCard:`[${v}="platform-card"]`,referralCodeField:`[${v}="referral-code-field"]`,referralCodeApplied:`[${v}="referral-code-applied"]`,fullNameField:`[${v}="full-name-field"]`,signUpForm:`[${v}="signup-form"]`,reEnterEmail:`[${v}="re-enter-email"]`,selectedPlatformClass:"selected",macOsApplePlatformId:"mac-apple",macOsIntelPlatformId:"mac-intel",iosPlatformId:"ios",windowsPlatformId:"windows",androidPlatformId:"android",socialsRadioGroup:"socials",validatedClass:"validated",waitlistNumber:"waitlist-number",onboardingForm:"#email-form"},ue={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/get-started`},Wt="/sign-up",Kt="/get-started";var q=(s,e)=>{s?e?s.style.setProperty("display","flex","important"):s.style.setProperty("display","none","important"):console.warn("Element not found")};function de(s,e,t={}){let r=document.getElementById(s);r&&r.addEventListener("click",function(){window.analytics.track(e,t)})}var ut=s=>{let e=document.querySelector(b.getStartedLoader);e&&(e.style.display=s?"block":"none")};var Vt=async(s,e,t,r,i,n,o)=>{try{ut(!0),await i.signWithMagicLink(s);let a=i.sessionData?.user.id;a&&window.analytics.identify(a,{email:s,name:e,firstName:t,lastName:r});let l=document.querySelector(b.magicLinkEmail);l.innerText=s,q(o,!1),q(n,!0),ut(!1),de("sign-up-open-gmail","signup_open_app",{app_name:"gmail"}),de("sign-up-open-superhuman","signup_open_app",{app_name:"superhuman"}),de("sign-up-open-outlook","signup_open_app",{app_name:"outlook"}),de("sign-up-reenter-email","signup_reenter_email")}catch(a){console.error("Error during sign-in:",a)}};var Qt=()=>{window.location.href=Kt};var Xt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(F(),H)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var fe=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Be=class extends fe{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Me=class extends fe{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},qe=class extends fe{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},He;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(He||(He={}));var us=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})},pe=class{constructor(e,{headers:t={},customFetch:r,region:i=He.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Xt(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return us(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);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 c=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:h}).catch(_=>{throw new Be(_)}),u=c.headers.get("x-relay-error");if(u&&u==="true")throw new Me(c);if(!c.ok)throw new qe(c);let d=((r=c.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield c.json():d==="application/octet-stream"?f=yield c.blob():d==="text/event-stream"?f=c:d==="multipart/form-data"?f=yield c.formData():f=yield c.text(),{data:f,error:null}}catch(i){return{data:null,error:i}}})}};var hr=Mt(cr(),1),{PostgrestClient:ur,PostgrestQueryBuilder:Ni,PostgrestFilterBuilder:Fi,PostgrestTransformBuilder:Bi,PostgrestBuilder:Mi}=hr.default;var dr="2.10.2";var fr={"X-Client-Info":`realtime-js/${dr}`},pr="1.0.0",Ke=1e4,gr=1e3,G;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(G||(G={}));var T;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(T||(T={}));var O;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(O||(O={}));var We;(function(s){s.websocket="websocket"})(We||(We={}));var B;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(B||(B={}));var ke=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+i));o=o+i;let l=r.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:h}}};var J=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var w;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(w||(w={}));var Tt=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=Ss(o,s,e,i),n),{})},Ss=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?mr(n,o):Et(o)},mr=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return Os(e,t)}switch(s){case w.bool:return Es(e);case w.float4:case w.float8:case w.int2:case w.int4:case w.int8:case w.numeric:case w.oid:return Ts(e);case w.json:case w.jsonb:return xs(e);case w.timestamp:return As(e);case w.abstime:case w.date:case w.daterange:case w.int4range:case w.int8range:case w.money:case w.reltime:case w.text:case w.time:case w.timestamptz:case w.timetz:case w.tsrange:case w.tstzrange:return Et(e);default:return Et(e)}},Et=s=>s,Es=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Ts=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},xs=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},Os=(s,e)=>{if(typeof s!="string")return s;let t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n,o=s.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>mr(e,a))}return s},As=s=>typeof s=="string"?s.replace(" ","T"):s,Ve=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var z=class{constructor(e,t,r={},i=Ke){this.channel=e,this.event=t,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var xt;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(xt||(xt={}));var re=class s{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=s.syncState(this.state,i,n,o),this.pendingDiffs.forEach(l=>{this.state=s.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=s.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(h,c)=>{o[h]||(l[h]=c)}),this.map(o,(h,c)=>{let u=n[h];if(u){let d=c.map(m=>m.presence_ref),f=u.map(m=>m.presence_ref),_=c.filter(m=>f.indexOf(m.presence_ref)<0),y=u.filter(m=>d.indexOf(m.presence_ref)<0);_.length>0&&(a[h]=_),y.length>0&&(l[h]=y)}else a[h]=c}),this.syncDiff(n,{joins:a,leaves:l},r,i)}static syncDiff(e,t,r,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(a,l)=>{var h;let c=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(l),c.length>0){let u=e[a].map(f=>f.presence_ref),d=c.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}r(a,c,l)}),this.map(o,(a,l)=>{let h=e[a];if(!h)return;let c=l.map(u=>u.presence_ref);h=h.filter(u=>c.indexOf(u.presence_ref)<0),e[a]=h,i(a,h,l),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return"metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var Ot;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Ot||(Ot={}));var At;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(At||(At={}));var Pt;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Pt||(Pt={}));var se=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=T.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 z(this,O.join,this.params,this.timeout),this.rejoinTimer=new J(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=T.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=T.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=T.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=T.errored,this.rejoinTimer.scheduleTimeout())}),this._on(O.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new re(this),this.broadcastEndpointURL=Ve(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(c=>e&&e("CHANNEL_ERROR",c)),this._onClose(()=>e&&e("CLOSED"));let l={},h={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(c=>c.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:h},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:c})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),c===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,f=(u=d?.length)!==null&&u!==void 0?u:0,_=[];for(let y=0;y<f;y++){let m=d[y],{filter:{event:S,schema:A,table:x,filter:C}}=m,$=c&&c[y];if($&&$.event===S&&$.schema===A&&$.table===x&&$.filter===C)_.push(Object.assign(Object.assign({},m),{id:$.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e("SUBSCRIBED");return}}).receive("error",c=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(c).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.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=T.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(O.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new z(this,O.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new z(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:h,join:c}=O;if(r&&[a,l,h,c].indexOf(o)>=0&&r!==this._joinRef())return;let d=this._onMessage(o,t,r);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(f=>{var _,y,m;return((_=f.filter)===null||_===void 0?void 0:_.event)==="*"||((m=(y=f.filter)===null||y===void 0?void 0:y.event)===null||m===void 0?void 0:m.toLocaleLowerCase())===o}).map(f=>f.callback(d,r)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var _,y,m,S,A,x;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let C=f.id,$=(_=f.filter)===null||_===void 0?void 0:_.event;return C&&((y=t.ids)===null||y===void 0?void 0:y.includes(C))&&($==="*"||$?.toLocaleLowerCase()===((m=t.data)===null||m===void 0?void 0:m.type.toLocaleLowerCase()))}else{let C=(A=(S=f?.filter)===null||S===void 0?void 0:S.event)===null||A===void 0?void 0:A.toLocaleLowerCase();return C==="*"||C===((x=t?.event)===null||x===void 0?void 0:x.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let _=d.data,{schema:y,table:m,commit_timestamp:S,type:A,errors:x}=_;d=Object.assign(Object.assign({},{schema:y,table:m,commit_timestamp:S,eventType:A,new:{},old:{},errors:x}),this._getPayloadRecords(_))}f.callback(d,r)})}_isClosed(){return this.state===T.closed}_isJoined(){return this.state===T.joined}_isJoining(){return this.state===T.joining}_isLeaving(){return this.state===T.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&s.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(O.close,{},e)}_onError(e){this._on(O.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=T.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Tt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Tt(e.columns,e.old_record)),t}};var Rs=()=>{},Cs=typeof WebSocket<"u",ie=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=fr,this.params={},this.timeout=Ke,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Rs,this.conn=null,this.sendBuffer=[],this.serializer=new ke,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(F(),H)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${We.websocket}`,this.httpEndpoint=Ve(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(r=t?.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new J(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(Cs){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Rt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Mt(yr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case G.connecting:return B.Connecting;case G.open:return B.Open;case G.closing:return B.Closing;default:return B.Closed}}isConnected(){return this.connectionState()===B.Open}channel(e,t={config:{}}){let r=new se(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${r} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(O.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:pr}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(O.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(gr,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Rt=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=G.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var ne=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function k(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var Qe=class extends ne{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Se=class extends ne{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var $s=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})},Xe=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(F(),H)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},vr=()=>$s(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(F(),H))).Response:Response});var oe=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})},Ct=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),js=(s,e)=>oe(void 0,void 0,void 0,function*(){let t=yield vr();s instanceof t?s.json().then(r=>{e(new Qe(Ct(r),s.status||500))}).catch(r=>{e(new Se(Ct(r),r))}):e(new Se(Ct(s),s))}),Ls=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function Ye(s,e,t,r,i,n){return oe(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,Ls(e,r,i,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>js(l,a))})})}function Ee(s,e,t,r){return oe(this,void 0,void 0,function*(){return Ye(s,"GET",e,t,r)})}function L(s,e,t,r,i){return oe(this,void 0,void 0,function*(){return Ye(s,"POST",e,r,i,t)})}function wr(s,e,t,r,i){return oe(this,void 0,void 0,function*(){return Ye(s,"PUT",e,r,i,t)})}function Ze(s,e,t,r,i){return oe(this,void 0,void 0,function*(){return Ye(s,"DELETE",e,r,i,t)})}var P=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})},Is={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},br={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Te=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=Xe(i)}uploadOrUpdate(e,t,r,i){return P(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},br),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl)):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let l=this._removeEmptyFolders(t),h=this._getFinalPath(l),c=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield c.json();return c.ok?{data:{path:l,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(k(n))return{data:null,error:n};throw n}})}upload(e,t,r){return P(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return P(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 l,h=Object.assign({upsert:br.upsert},i),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",h.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",h.cacheControl)):(l=r,c["cache-control"]=`max-age=${h.cacheControl}`,c["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:c}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(l){if(k(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return P(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield L(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new ne("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}update(e,t,r){return P(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return P(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(k(i))return{data:null,error:i};throw i}})}copy(e,t,r){return P(this,void 0,void 0,function*(){try{return{data:{path:(yield L(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(k(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return P(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield L(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(k(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return P(this,void 0,void 0,function*(){try{let i=yield L(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(k(i))return{data:null,error:i};throw i}})}download(e,t){return P(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 Ee(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(k(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&i.push(l);let h=i.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${h}`)}}}remove(e){return P(this,void 0,void 0,function*(){try{return{data:yield Ze(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}list(e,t,r){return P(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Is),t),{prefix:e||""});return{data:yield L(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(k(i))return{data:null,error:i};throw i}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var kr="2.6.0";var Sr={"X-Client-Info":`storage-js/${kr}`};var ae=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})},xe=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Sr),t),this.fetch=Xe(r)}listBuckets(){return ae(this,void 0,void 0,function*(){try{return{data:yield Ee(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(k(e))return{data:null,error:e};throw e}})}getBucket(e){return ae(this,void 0,void 0,function*(){try{return{data:yield Ee(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return ae(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return ae(this,void 0,void 0,function*(){try{return{data:yield wr(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}emptyBucket(e){return ae(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}deleteBucket(e){return ae(this,void 0,void 0,function*(){try{return{data:yield Ze(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}};var Oe=class extends xe{constructor(e,t={},r){super(e,t,r)}from(e){return new Te(this.url,this.headers,e,this.fetch)}};var Er="2.44.4";var Ae="";typeof Deno<"u"?Ae="deno":typeof document<"u"?Ae="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ae="react-native":Ae="node";var Us={"X-Client-Info":`supabase-js-${Ae}/${Er}`},Tr={headers:Us},xr={schema:"public"},Or={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ar={};F();var Ds=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})},Ns=s=>{let e;return s?e=s:typeof fetch>"u"?e=dt:e=fetch,(...t)=>e(...t)},Fs=()=>typeof Headers>"u"?ft:Headers,Pr=(s,e,t)=>{let r=Ns(t),i=Fs();return(n,o)=>Ds(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:s,h=new i(o?.headers);return h.has("apikey")||h.set("apikey",s),h.has("Authorization")||h.set("Authorization",`Bearer ${l}`),r(n,Object.assign(Object.assign({},o),{headers:h}))})};function Rr(s){return s.replace(/\/$/,"")}function Cr(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:l,global:h}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},l),i),global:Object.assign(Object.assign({},h),n)}}var et="2.64.4";var $r="http://localhost:9999",jr="supabase.auth.token";var Lr={"X-Client-Info":`gotrue-js/${et}`},$t=10;var Pe="X-Supabase-Api-Version",jt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Ir(s){return Math.round(Date.now()/1e3)+s}function Ur(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}var R=()=>typeof document<"u",W={tested:!1,writable:!1},M=()=>{if(!R())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(W.tested)return W.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),W.tested=!0,W.writable=!0}catch{W.tested=!0,W.writable=!1}return W.writable};function tt(s){let e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}var rt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(F(),H)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Dr=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",Lt=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Ce=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},st=async(s,e)=>{await s.removeItem(e)};function Bs(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,l,h,c=0;for(s=s.replace("-","+").replace("_","/");c<s.length;)o=e.indexOf(s.charAt(c++)),a=e.indexOf(s.charAt(c++)),l=e.indexOf(s.charAt(c++)),h=e.indexOf(s.charAt(c++)),r=o<<2|a>>4,i=(a&15)<<4|l>>2,n=(l&3)<<6|h,t=t+String.fromCharCode(r),l!=64&&i!=0&&(t=t+String.fromCharCode(i)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Re=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Re.promiseConstructor=Promise;function It(s){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=s.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let r=t[1];return JSON.parse(Bs(r))}async function Nr(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Fr(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await s(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function Ms(s){return("0"+s.toString(16)).substr(-2)}function qs(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,Ms).join("")}async function Hs(s){let t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function Gs(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Js(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;let t=await Hs(s);return Gs(t)}async function K(s,e,t=!1){let r=qs(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await Lt(s,`${e}-code-verifier`,i);let n=await Js(r);return[n,r===n?"plain":"s256"]}var zs=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Br(s){let e=s.headers.get(Pe);if(!e||!e.match(zs))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var $e=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function p(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var it=class extends $e{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function Mr(s){return p(s)&&s.name==="AuthApiError"}var le=class extends $e{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},D=class extends $e{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},I=class extends D{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},ce=class extends D{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},V=class extends D{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Q=class extends D{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}}},je=class extends D{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}}},he=class extends D{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function nt(s){return p(s)&&s.name==="AuthRetryableFetchError"}var Le=class extends D{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Ws=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},X=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Ks=[502,503,504];async function qr(s){var e;if(!Dr(s))throw new he(X(s),0);if(Ks.includes(s.status))throw new he(X(s),s.status);let t;try{t=await s.json()}catch(n){throw new le(X(n),n)}let r,i=Br(s);if(i&&i.getTime()>=jt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Le(X(t),s.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new Le(X(t),s.status,t.weak_password.reasons);throw new it(X(t),s.status||500,r)}var Vs=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function g(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Pe]||(n[Pe]=jt["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(i=r?.query)!==null&&i!==void 0?i:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Qs(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(l):{data:Object.assign({},l),error:null}}async function Qs(s,e,t,r,i,n){let o=Vs(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(l){throw console.error(l),new he(X(l),0)}if(a.ok||await qr(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await qr(l)}}function N(s){var e;let t=null;Xs(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Ir(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function Ut(s){let e=N(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function U(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function Hr(s){return{data:s,error:null}}function Gr(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Ws(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Jr(s){return s}function Xs(s){return s.access_token&&s.refresh_token&&s.expires_in}var Ys=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},Y=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=rt(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await g(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(p(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await g(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:U})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Ys(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await g(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Gr,redirectTo:t?.redirectTo})}catch(t){if(p(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await g(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:U})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,l;try{let h={nextPage:null,lastPage:0,total:0},c=await g(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:Jr});if(c.error)throw c.error;let u=await c.json(),d=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(_=>{let y=parseInt(_.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(_.split(";")[1].split("=")[1]);h[`${m}Page`]=y}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(p(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:U})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:U})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:U})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(p(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}};var zr={getItem:s=>M()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{M()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{M()&&globalThis.localStorage.removeItem(s)}};function Dt(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function Wr(){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 Z={debug:!!(globalThis&&M()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Ie=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},ot=class extends Ie{};async function Nt(s,e,t){Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),Z.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new ot(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(Z.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()}})}Wr();var Zs={url:$r,storageKey:jr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Lr,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Ue=30*1e3,Kr=3;async function Vr(s,e,t){return await t()}var ee=class s{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=s.nextInstanceID,s.nextInstanceID+=1,this.instanceID>0&&R()&&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({},Zs),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 Y({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=rt(i.fetch),this.lock=i.lock||Vr,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:R()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Nt:this.lock=Vr,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:M()?this.storage=zr:(this.memoryStorage={},this.storage=Dt(this.memoryStorage)):(this.memoryStorage={},this.storage=Dt(this.memoryStorage)),R()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${et}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=R()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),r?.message==="Identity is already linked"||r?.message==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return p(e)?{error:e}:{error:new le("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:N}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:c,password:u,options:d}=e,f=null,_=null;this.flowType==="pkce"&&([f,_]=await K(this.storage,this.storageKey)),n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:c,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:_},xform:N})}else if("phone"in e){let{phone:c,password:u,options:d}=e;n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:u,data:(r=d?.data)!==null&&r!==void 0?r:{},channel:(i=d?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:N})}else throw new V("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 l=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ut})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ut})}else throw new V("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new ce}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Ce(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await g(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:N});return await st(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:r,token:i,access_token:n,nonce:o}=e,a=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:N}),{data:l,error:h}=a;return h?{data:{user:null,session:null},error:h}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new ce}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:h})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:l}=e,h=null,c=null;this.flowType==="pkce"&&([h,c]=await K(this.storage,this.storageKey));let{error:u}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(r=l?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:h,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:l}=e,{data:h,error:c}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l?.data)!==null&&i!==void 0?i:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:c}}throw new V("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:N});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,h=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(i){if(p(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await K(this.storage,this.storageKey)),await g(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:Hr})}catch(n){if(p(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new I;let{error:i}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(p(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:i,options:n}=e,{error:o}=await g(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:i,options:n}=e,{data:o,error:a}=await g(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new V("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Ce(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,h,c)=>(!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(l,h,c))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:U}):await this._useSession(async t=>{var r,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new I}:await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:U})})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new I;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await K(this.storage,this.storageKey));let{data:h,error:c}=await g(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:U});if(c)throw c;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return It(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 I;let t=Date.now()/1e3,r=t,i=!0,n=null,o=It(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(p(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new I;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!R())throw new Q("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Q("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new je("Not a valid PKCE flow url.");let t=tt(window.location.href);if(e){if(!t.code)throw new je("No code detected.");let{data:A,error:x}=await this._exchangeCodeForSession(t.code);if(x)throw x;let C=new URL(window.location.href);return C.searchParams.delete("code"),window.history.replaceState(window.history.state,"",C.toString()),{data:{session:A.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Q(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:h}=t;if(!n||!a||!o||!h)throw new Q("No session defined in URL");let c=Math.round(Date.now()/1e3),u=parseInt(a),d=c+u;l&&(d=parseInt(l));let f=d-c;f*1e3<=Ue&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let _=d-u;c-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,d,c):c-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",_,d,c);let{data:y,error:m}=await this._getUser(n);if(m)throw m;let S={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:S,redirectType:t.type},error:null}}catch(t){if(p(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=tt(window.location.href);return!!(R()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=tt(window.location.href),t=await Ce(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{error:n};let o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Mr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await st(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Ur(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await K(this.storage,this.storageKey,!0));try{return await g(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(p(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,l,h,c;let{data:u,error:d}=n;if(d)throw d;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await g(this.fetch,"GET",f,{headers:this.headers,jwt:(c=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&c!==void 0?c:void 0})});if(i)throw i;return R()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(p(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await g(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await Fr(async i=>(i>0&&await Nr(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await g(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:N})),(i,n)=>{let o=200*Math.pow(2,i);return n&&nt(n)&&Date.now()+o-r<Ue})}catch(r){if(this._debug(t,"error",r),p(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),R()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await Ce(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<i+$t;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${$t}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),nt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new I;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Re;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new I;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),p(n)){let o={session:null,error:n};return nt(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){n.push(l)}});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 Lt(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await st(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&R()&&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(),Ue);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((r.expires_at*1e3-e)/Ue);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Ue}ms, refresh threshold is ${Kr} ticks`),i<=Kr&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Ie)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!R()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await K(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:l}=await g(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return l?{data:null,error:l}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r=e?.factors||[],i=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let l=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(l="aal2");let c=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:c},error:null}}))}};ee.nextInstanceID=0;var ei=ee,Ft=ei;var at=class extends Ft{constructor(e){super(e)}};var ti=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})},De=class{constructor(e,t,r){var i,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=Rr(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 l=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:xr,realtime:Ar,auth:Object.assign(Object.assign({},Or),{storageKey:l}),global:Tr},c=Cr(r??{},h);this.storageKey=(i=c.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=Pr(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new ur(`${a}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new pe(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Oe(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return ti(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:n,flowType:o,debug:a},l,h){var c;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new at({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(c="Authorization"in this.headers)!==null&&c!==void 0?c:!1})}_initRealtimeClient(e){return new ie(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var Qr=(s,e,t)=>new De(s,e,t);var Xr=()=>{window.location.href=Wt};var lt=class{constructor(){this.sessionData=null;this.supabase=Qr(ue.supaBaseUrl,ue.supaBaseKey)}async signInWithGoogle(){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:ue.redirectUri}}),console.log("Signed in with Google")}catch(e){throw console.error("Error signing in with Google:",e),e}}async setSession(e,t){try{let{data:r,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw this.signOut(),console.error("Error setting session:",r),r}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,r){let i=new Date;i.setTime(i.getTime()+r*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{await this.setSession(t,r)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,i]=t.split("=");return e[r]=i,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1),Xr()}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e){try{let{error:t}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:ue.redirectUri}});if(t)throw t}catch(t){throw console.error("Error sending magic link:",t),t}}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 ct=class{constructor(){this.fullNameField=document.querySelector(b.fullNameField),this.emailField=document.querySelector(b.emailField),this.magicLinkButton=document.querySelector(b.magicLink),this.magicLinkButton.disabled=!0,this.fullNameField.addEventListener("input",()=>this.validate()),this.emailField.addEventListener("input",()=>this.validate())}validate(){let e=this.fullNameField.value,t=this.emailField.value;return!e||!t?(this.magicLinkButton.classList.remove(b.validatedClass),this.magicLinkButton.disabled=!0,!1):(this.magicLinkButton.disabled=!1,this.magicLinkButton.classList.add(b.validatedClass),!0)}resetEmailField(){this.emailField.value=""}};var Yr=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var ri=()=>{let e=new URLSearchParams(window.location.search).get("referral");if(e){let t=new Date;t.setTime(t.getTime()+30*24*60*60*1e3),document.cookie=`referral=${e};expires=${t.toUTCString()};path=/;domain=.flowvoice.ai;`}};window.Webflow||(window.Webflow=[]);window.Webflow.push(()=>{let{accessToken:s,refreshToken:e}=zt(),t=document.querySelector(b.getStartedLoader);if(s&&e){Qt();return}ri();let r=document.querySelector(b.successBlock),i=document.querySelector(b.emailFormWrapper),n=document.querySelector(b.googleLoginButton),o=document.querySelector(b.signUpForm),a=document.querySelector(b.reEnterEmail);try{q(t,!1)}catch{console.warn("Loader is hidden")}let l=new lt;n.addEventListener("click",async()=>{try{window.analytics.track("signup_google"),await l.signInWithGoogle()}catch(c){console.error("Error during sign-in:",c)}});let h=new ct;o.addEventListener("submit",async c=>{if(c.stopPropagation(),c.preventDefault(),!h.validate())return;window.analytics.track("signup_email");let f=document.querySelector(b.fullNameField).value;localStorage.setItem("fullName",f);let y=document.querySelector(b.emailField).value,[m,S]=qt(f),A={email:y,first_name:m,last_name:S},x=Yr();x.dclid&&(A.dubClickID=x.dclid),await Ht.addRawUserEmail(A),await Vt(y,f,m,S,l,r,i)}),a.addEventListener("click",()=>{h.resetEmailField(),q(i,!0),q(r,!1)})});})();
1
+ "use strict";(()=>{var Br=Object.create;var Ie=Object.defineProperty;var Hr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var zr=Object.getPrototypeOf,Gr=Object.prototype.hasOwnProperty;var Wr=(s,e)=>()=>(s&&(e=s(s=0)),e);var P=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Kr=(s,e)=>{for(var t in e)Ie(s,t,{get:e[t],enumerable:!0})},Lt=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Jr(e))!Gr.call(s,i)&&i!==t&&Ie(s,i,{get:()=>e[i],enumerable:!(r=Hr(e,i))||r.enumerable});return s};var Ut=(s,e,t)=>(t=s!=null?Br(zr(s)):{},Lt(e||!s||!s.__esModule?Ie(t,"default",{value:s,enumerable:!0}):t,s)),Vr=s=>Lt(Ie({},"__esModule",{value:!0}),s);var q={};Kr(q,{Headers:()=>ct,Request:()=>Yr,Response:()=>Zr,default:()=>at,fetch:()=>Xr});var Qr,Y,Xr,at,ct,Yr,Zr,D=Wr(()=>{"use strict";Qr=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")},Y=Qr(),Xr=Y.fetch,at=Y.fetch.bind(Y),ct=Y.Headers,Yr=Y.Request,Zr=Y.Response});var Bt=P(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});var lt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};ht.default=lt});var dt=P(ue=>{"use strict";var Ht=ue&&ue.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ue,"__esModule",{value:!0});var ts=Ht((D(),Vr(q))),rs=Ht(Bt()),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=ts.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let h=null,l=null,u=null,d=n.status,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let k=await n.text();k===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=k:l=JSON.parse(k))}let v=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),m=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");v&&m&&m.length>1&&(u=parseInt(m[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(h={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,u=null,d=406,f="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let v=await n.text();try{h=JSON.parse(v),Array.isArray(h)&&n.status===404&&(l=[],h=null,d=200,f="OK")}catch{n.status===404&&v===""?(d=204,f="No Content"):h={message:v}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new rs.default(h)}return{error:h,data:l,count:u,status:d,statusText:f}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};ue.default=ut});var pt=P(de=>{"use strict";var ss=de&&de.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(de,"__esModule",{value:!0});var is=ss(dt()),ft=class extends is.default{select(e){let t=!1,r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:i=r}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};de.default=ft});var qe=P(fe=>{"use strict";var ns=fe&&fe.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(fe,"__esModule",{value:!0});var os=ns(pt()),gt=class extends os.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};fe.default=gt});var mt=P(ge=>{"use strict";var as=ge&&ge.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ge,"__esModule",{value:!0});var pe=as(qe()),_t=class{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new pe.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new pe.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((h,l)=>h.concat(Object.keys(l)),[]);if(c.length>0){let h=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",h.join(","))}}return new pe.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new pe.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new pe.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ge.default=_t});var Jt=P(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.version=void 0;Me.version="0.0.0-automated"});var zt=P(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.DEFAULT_HEADERS=void 0;var cs=Jt();Be.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${cs.version}`}});var Wt=P(_e=>{"use strict";var Gt=_e&&_e.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(_e,"__esModule",{value:!0});var ls=Gt(mt()),hs=Gt(qe()),us=zt(),vt=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},us.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new ls.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new s(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([l,u])=>u!==void 0).map(([l,u])=>[l,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([l,u])=>{a.searchParams.append(l,u)})):(o="POST",c=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new hs.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};_e.default=vt});var Zt=P(b=>{"use strict";var me=b&&b.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(b,"__esModule",{value:!0});b.PostgrestBuilder=b.PostgrestTransformBuilder=b.PostgrestFilterBuilder=b.PostgrestQueryBuilder=b.PostgrestClient=void 0;var Kt=me(Wt());b.PostgrestClient=Kt.default;var Vt=me(mt());b.PostgrestQueryBuilder=Vt.default;var Qt=me(qe());b.PostgrestFilterBuilder=Qt.default;var Xt=me(pt());b.PostgrestTransformBuilder=Xt.default;var Yt=me(dt());b.PostgrestBuilder=Yt.default;b.default={PostgrestClient:Kt.default,PostgrestQueryBuilder:Vt.default,PostgrestFilterBuilder:Qt.default,PostgrestTransformBuilder:Xt.default,PostgrestBuilder:Yt.default}});var cr=P((Li,ar)=>{"use strict";ar.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Le="https://staging.aria-web.wispr.ai",ot=class{static async signupUser(e){try{let t=await fetch(`${Le}/signup`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Signup failed with status ${t.status}`);console.log("User signed up successfully")}catch(t){console.error("Error during signup:",t)}}static async addRawUserEmail(e){try{let t=await fetch(`${Le}/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}`)}catch(t){console.error("Error during raw user signup:",t)}}static async addToWaitlist(e){try{let t=await fetch(`${Le}/add_to_waitlist`,{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 applyReferralCode(e){try{let t=await fetch(`${Le}/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}}};var Dt=ot;var Nt=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var Ft=()=>{let s=window.location.hash.substring(1),e=new URLSearchParams(s);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var qt=()=>{let{access_token:s,refresh_token:e}=Ft(),t=s,r=e;if(!t||!r){let i=Nt();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var Mt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(D(),q)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var le=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Ue=class extends le{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},De=class extends le{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Ne=class extends le{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Fe;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(Fe||(Fe={}));var es=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},he=class{constructor(e,{headers:t={},customFetch:r,region:i=Fe.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Mt(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return es(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(_=>{throw new Ue(_)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new De(l);if(!l.ok)throw new Ne(l);let d=((r=l.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield l.json():d==="application/octet-stream"?f=yield l.blob():d==="text/event-stream"?f=l:d==="multipart/form-data"?f=yield l.formData():f=yield l.text(),{data:f,error:null}}catch(i){return{data:null,error:i}}})}};var er=Ut(Zt(),1),{PostgrestClient:tr,PostgrestQueryBuilder:_i,PostgrestFilterBuilder:mi,PostgrestTransformBuilder:vi,PostgrestBuilder:yi}=er.default;var rr="2.10.2";var sr={"X-Client-Info":`realtime-js/${rr}`},ir="1.0.0",Je=1e4,nr=1e3,M;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(M||(M={}));var S;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(S||(S={}));var E;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(E||(E={}));var He;(function(s){s.websocket="websocket"})(He||(He={}));var N;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(N||(N={}));var ve=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+i));o=o+i;let c=r.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:h}}};var B=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 y;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(y||(y={}));var wt=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=ds(o,s,e,i),n),{})},ds=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?or(n,o):yt(o)},or=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return _s(e,t)}switch(s){case y.bool:return fs(e);case y.float4:case y.float8:case y.int2:case y.int4:case y.int8:case y.numeric:case y.oid:return ps(e);case y.json:case y.jsonb:return gs(e);case y.timestamp:return ms(e);case y.abstime:case y.date:case y.daterange:case y.int4range:case y.int8range:case y.money:case y.reltime:case y.text:case y.time:case y.timestamptz:case y.timetz:case y.tsrange:case y.tstzrange:return yt(e);default:return yt(e)}},yt=s=>s,fs=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},ps=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},gs=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},_s=(s,e)=>{if(typeof s!="string")return s;let t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n,o=s.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>or(e,a))}return s},ms=s=>typeof s=="string"?s.replace(" ","T"):s,ze=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var H=class{constructor(e,t,r={},i=Je){this.channel=e,this.event=t,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var bt;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(bt||(bt={}));var Z=class s{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=s.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=s.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=s.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(h,l)=>{o[h]||(c[h]=l)}),this.map(o,(h,l)=>{let u=n[h];if(u){let d=l.map(m=>m.presence_ref),f=u.map(m=>m.presence_ref),_=l.filter(m=>f.indexOf(m.presence_ref)<0),v=u.filter(m=>d.indexOf(m.presence_ref)<0);_.length>0&&(a[h]=_),v.length>0&&(c[h]=v)}else a[h]=l}),this.syncDiff(n,{joins:a,leaves:c},r,i)}static syncDiff(e,t,r,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var h;let l=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(c),l.length>0){let u=e[a].map(f=>f.presence_ref),d=l.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}r(a,l,c)}),this.map(o,(a,c)=>{let h=e[a];if(!h)return;let l=c.map(u=>u.presence_ref);h=h.filter(u=>l.indexOf(u.presence_ref)<0),e[a]=h,i(a,h,c),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return"metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var kt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(kt||(kt={}));var St;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(St||(St={}));var Et;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(Et||(Et={}));var ee=class s{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=S.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 H(this,E.join,this.params,this.timeout),this.rejoinTimer=new B(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=S.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=S.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=S.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=S.errored,this.rejoinTimer.scheduleTimeout())}),this._on(E.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new Z(this),this.broadcastEndpointURL=ze(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},h={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:h},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,f=(u=d?.length)!==null&&u!==void 0?u:0,_=[];for(let v=0;v<f;v++){let m=d[v],{filter:{event:k,schema:I,table:R,filter:A}}=m,O=l&&l[v];if(O&&O.event===k&&O.schema===I&&O.table===R&&O.filter===A)_.push(Object.assign(Object.assign({},m),{id:O.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),h.receive("ok",()=>n("ok")),h.receive("error",()=>n("error")),h.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=S.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(E.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new H(this,E.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new H(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:h,join:l}=E;if(r&&[a,c,h,l].indexOf(o)>=0&&r!==this._joinRef())return;let d=this._onMessage(o,t,r);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(f=>{var _,v,m;return((_=f.filter)===null||_===void 0?void 0:_.event)==="*"||((m=(v=f.filter)===null||v===void 0?void 0:v.event)===null||m===void 0?void 0:m.toLocaleLowerCase())===o}).map(f=>f.callback(d,r)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var _,v,m,k,I,R;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let A=f.id,O=(_=f.filter)===null||_===void 0?void 0:_.event;return A&&((v=t.ids)===null||v===void 0?void 0:v.includes(A))&&(O==="*"||O?.toLocaleLowerCase()===((m=t.data)===null||m===void 0?void 0:m.type.toLocaleLowerCase()))}else{let A=(I=(k=f?.filter)===null||k===void 0?void 0:k.event)===null||I===void 0?void 0:I.toLocaleLowerCase();return A==="*"||A===((R=t?.event)===null||R===void 0?void 0:R.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let _=d.data,{schema:v,table:m,commit_timestamp:k,type:I,errors:R}=_;d=Object.assign(Object.assign({},{schema:v,table:m,commit_timestamp:k,eventType:I,new:{},old:{},errors:R}),this._getPayloadRecords(_))}f.callback(d,r)})}_isClosed(){return this.state===S.closed}_isJoined(){return this.state===S.joined}_isJoining(){return this.state===S.joining}_isLeaving(){return this.state===S.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&s.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(E.close,{},e)}_onError(e){this._on(E.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=S.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=wt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=wt(e.columns,e.old_record)),t}};var ys=()=>{},ws=typeof WebSocket<"u",te=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=sr,this.params={},this.timeout=Je,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=ys,this.conn=null,this.sendBuffer=[],this.serializer=new ve,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(D(),q)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${He.websocket}`,this.httpEndpoint=ze(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(r=t?.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new B(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(ws){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Tt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Ut(cr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case M.connecting:return N.Connecting;case M.open:return N.Open;case M.closing:return N.Closing;default:return N.Closed}}isConnected(){return this.connectionState()===N.Open}channel(e,t={config:{}}){let r=new ee(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${r} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(E.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:ir}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(E.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(nr,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Tt=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=M.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var re=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function w(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}var Ge=class extends re{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},ye=class extends re{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var bs=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},We=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(D(),q)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},lr=()=>bs(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(D(),q))).Response:Response});var se=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},xt=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),ks=(s,e)=>se(void 0,void 0,void 0,function*(){let t=yield lr();s instanceof t?s.json().then(r=>{e(new Ge(xt(r),s.status||500))}).catch(r=>{e(new ye(xt(r),r))}):e(new ye(xt(s),s))}),Ss=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function Ke(s,e,t,r,i,n){return se(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,Ss(e,r,i,n)).then(c=>{if(!c.ok)throw c;return r?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>ks(c,a))})})}function we(s,e,t,r){return se(this,void 0,void 0,function*(){return Ke(s,"GET",e,t,r)})}function j(s,e,t,r,i){return se(this,void 0,void 0,function*(){return Ke(s,"POST",e,r,i,t)})}function hr(s,e,t,r,i){return se(this,void 0,void 0,function*(){return Ke(s,"PUT",e,r,i,t)})}function Ve(s,e,t,r,i){return se(this,void 0,void 0,function*(){return Ke(s,"DELETE",e,r,i,t)})}var T=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},Es={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ur={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},be=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=We(i)}uploadOrUpdate(e,t,r,i){return T(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},ur),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl)):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),h=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield l.json();return l.ok?{data:{path:c,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(w(n))return{data:null,error:n};throw n}})}upload(e,t,r){return T(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return T(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:ur.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",h.cacheControl)):(c=r,l["cache-control"]=`max-age=${h.cacheControl}`,l["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(w(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return T(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield j(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new re("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(w(r))return{data:null,error:r};throw r}})}update(e,t,r){return T(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return T(this,void 0,void 0,function*(){try{return{data:yield j(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(w(i))return{data:null,error:i};throw i}})}copy(e,t,r){return T(this,void 0,void 0,function*(){try{return{data:{path:(yield j(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(w(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return T(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield j(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(w(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return T(this,void 0,void 0,function*(){try{let i=yield j(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(w(i))return{data:null,error:i};throw i}})}download(e,t){return T(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 we(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(w(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let h=i.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${h}`)}}}remove(e){return T(this,void 0,void 0,function*(){try{return{data:yield Ve(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}})}list(e,t,r){return T(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Es),t),{prefix:e||""});return{data:yield j(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(w(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 dr="2.6.0";var fr={"X-Client-Info":`storage-js/${dr}`};var ie=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},ke=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},fr),t),this.fetch=We(r)}listBuckets(){return ie(this,void 0,void 0,function*(){try{return{data:yield we(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(w(e))return{data:null,error:e};throw e}})}getBucket(e){return ie(this,void 0,void 0,function*(){try{return{data:yield we(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return ie(this,void 0,void 0,function*(){try{return{data:yield j(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(w(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return ie(this,void 0,void 0,function*(){try{return{data:yield hr(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(w(r))return{data:null,error:r};throw r}})}emptyBucket(e){return ie(this,void 0,void 0,function*(){try{return{data:yield j(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}})}deleteBucket(e){return ie(this,void 0,void 0,function*(){try{return{data:yield Ve(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(w(t))return{data:null,error:t};throw t}})}};var Se=class extends ke{constructor(e,t={},r){super(e,t,r)}from(e){return new be(this.url,this.headers,e,this.fetch)}};var pr="2.44.4";var Ee="";typeof Deno<"u"?Ee="deno":typeof document<"u"?Ee="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ee="react-native":Ee="node";var Ts={"X-Client-Info":`supabase-js-${Ee}/${pr}`},gr={headers:Ts},_r={schema:"public"},mr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},vr={};D();var xs=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},As=s=>{let e;return s?e=s:typeof fetch>"u"?e=at:e=fetch,(...t)=>e(...t)},Os=()=>typeof Headers>"u"?ct:Headers,yr=(s,e,t)=>{let r=As(t),i=Os();return(n,o)=>xs(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:s,h=new i(o?.headers);return h.has("apikey")||h.set("apikey",s),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),r(n,Object.assign(Object.assign({},o),{headers:h}))})};function wr(s){return s.replace(/\/$/,"")}function br(s,e){let{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:c,global:h}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},h),n)}}var Qe="2.64.4";var kr="http://localhost:9999",Sr="supabase.auth.token";var Er={"X-Client-Info":`gotrue-js/${Qe}`},At=10;var Te="X-Supabase-Api-Version",Ot={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Tr(s){return Math.round(Date.now()/1e3)+s}function xr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}var x=()=>typeof document<"u",J={tested:!1,writable:!1},F=()=>{if(!x())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(J.tested)return J.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),J.tested=!0,J.writable=!0}catch{J.tested=!0,J.writable=!1}return J.writable};function Xe(s){let e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}var Ye=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(D(),q)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Ar=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",Rt=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Ae=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Ze=async(s,e)=>{await s.removeItem(e)};function Rs(s){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,i,n,o,a,c,h,l=0;for(s=s.replace("-","+").replace("_","/");l<s.length;)o=e.indexOf(s.charAt(l++)),a=e.indexOf(s.charAt(l++)),c=e.indexOf(s.charAt(l++)),h=e.indexOf(s.charAt(l++)),r=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|h,t=t+String.fromCharCode(r),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var xe=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};xe.promiseConstructor=Promise;function Pt(s){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=s.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let r=t[1];return JSON.parse(Rs(r))}async function Or(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Rr(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await s(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function Ps(s){return("0"+s.toString(16)).substr(-2)}function js(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,Ps).join("")}async function Cs(s){let t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function $s(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Is(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;let t=await Cs(s);return $s(t)}async function z(s,e,t=!1){let r=js(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await Rt(s,`${e}-code-verifier`,i);let n=await Is(r);return[n,r===n?"plain":"s256"]}var Ls=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Pr(s){let e=s.headers.get(Te);if(!e||!e.match(Ls))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Oe=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function p(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}var et=class extends Oe{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function jr(s){return p(s)&&s.name==="AuthApiError"}var ne=class extends Oe{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},L=class extends Oe{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},C=class extends L{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},oe=class extends L{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},G=class extends L{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},W=class extends L{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}}},Re=class extends L{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}}},ae=class extends L{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function tt(s){return p(s)&&s.name==="AuthRetryableFetchError"}var Pe=class extends L{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Us=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},K=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Ds=[502,503,504];async function Cr(s){var e;if(!Ar(s))throw new ae(K(s),0);if(Ds.includes(s.status))throw new ae(K(s),s.status);let t;try{t=await s.json()}catch(n){throw new ne(K(n),n)}let r,i=Pr(s);if(i&&i.getTime()>=Ot["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Pe(K(t),s.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new Pe(K(t),s.status,t.weak_password.reasons);throw new et(K(t),s.status||500,r)}var Ns=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function g(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[Te]||(n[Te]=Ot["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(i=r?.query)!==null&&i!==void 0?i:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Fs(s,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function Fs(s,e,t,r,i,n){let o=Ns(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(c){throw console.error(c),new ae(K(c),0)}if(a.ok||await Cr(a),r?.noResolveJson)return a;try{return await a.json()}catch(c){await Cr(c)}}function U(s){var e;let t=null;qs(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Tr(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function jt(s){let e=U(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function $(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function $r(s){return{data:s,error:null}}function Ir(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Us(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function Lr(s){return s}function qs(s){return s.access_token&&s.refresh_token&&s.expires_in}var Ms=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},V=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Ye(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await g(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(p(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await g(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:$})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Ms(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r?.newEmail,delete i.newEmail),await g(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Ir,redirectTo:t?.redirectTo})}catch(t){if(p(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await g(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:$})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,c;try{let h={nextPage:null,lastPage:0,total:0},l=await g(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:Lr});if(l.error)throw l.error;let u=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(_=>{let v=parseInt(_.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(_.split(";")[1].split("=")[1]);h[`${m}Page`]=v}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(p(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:$})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:$})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:$})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(p(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}};var Ur={getItem:s=>F()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{F()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{F()&&globalThis.localStorage.removeItem(s)}};function Ct(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function Dr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var Q={debug:!!(globalThis&&F()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},je=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},rt=class extends je{};async function $t(s,e,t){Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),Q.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new rt(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(Q.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}Dr();var Bs={url:kr,storageKey:Sr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Er,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Ce=30*1e3,Nr=3;async function Fr(s,e,t){return await t()}var X=class s{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=s.nextInstanceID,s.nextInstanceID+=1,this.instanceID>0&&x()&&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({},Bs),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 V({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Ye(i.fetch),this.lock=i.lock||Fr,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:x()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=$t:this.lock=Fr,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:F()?this.storage=Ur:(this.memoryStorage={},this.storage=Ct(this.memoryStorage)):(this.memoryStorage={},this.storage=Ct(this.memoryStorage)),x()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Qe}) ${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=x()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),r?.message==="Identity is already linked"||r?.message==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});let{session:i,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",n),await this._saveSession(i),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return p(e)?{error:e}:{error:new ne("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:U}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){let{email:l,password:u,options:d}=e,f=null,_=null;this.flowType==="pkce"&&([f,_]=await z(this.storage,this.storageKey)),n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:_},xform:U})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:u,data:(r=d?.data)!==null&&r!==void 0?r:{},channel:(i=d?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:U})}else throw new G("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:jt})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:jt})}else throw new G("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new oe}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Ae(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/"),{data:n,error:o}=await g(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:U});return await Ze(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 oe}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:r,token:i,access_token:n,nonce:o}=e,a=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:U}),{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 oe}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){let{email:a,options:c}=e,h=null,l=null;this.flowType==="pkce"&&([h,l]=await z(this.storage,this.storageKey));let{error:u}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(r=c?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:h,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:c}=e,{data:h,error:l}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:l}}throw new G("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:U});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(p(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await z(this.storage,this.storageKey)),await g(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:$r})}catch(n){if(p(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new C;let{error:i}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(p(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:i,options:n}=e,{error:o}=await g(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:i,options:n}=e,{data:o,error:a}=await g(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new G("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Ae(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,h,l)=>(!o&&h==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,h,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:$}):await this._useSession(async t=>{var r,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new C}:await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:$})})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new C;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await z(this.storage,this.storageKey));let{data:h,error:l}=await g(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:$});if(l)throw l;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return Pt(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 C;let t=Date.now()/1e3,r=t,i=!0,n=null,o=Pt(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(p(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new C;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!x())throw new W("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new W("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Re("Not a valid PKCE flow url.");let t=Xe(window.location.href);if(e){if(!t.code)throw new Re("No code detected.");let{data:I,error:R}=await this._exchangeCodeForSession(t.code);if(R)throw R;let A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:I.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new W(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:h}=t;if(!n||!a||!o||!h)throw new W("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;c&&(d=parseInt(c));let f=d-l;f*1e3<=Ce&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let _=d-u;l-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,d,l):l-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",_,d,l);let{data:v,error:m}=await this._getUser(n);if(m)throw m;let k={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:k,redirectType:t.type},error:null}}catch(t){if(p(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=Xe(window.location.href);return!!(x()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=Xe(window.location.href),t=await Ae(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{error:n};let o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(jr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Ze(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=xr(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await z(this.storage,this.storageKey,!0));try{return await g(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(p(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,c,h,l;let{data:u,error:d}=n;if(d)throw d;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await g(this.fetch,"GET",f,{headers:this.headers,jwt:(l=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return x()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(p(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)throw o;return await g(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await Rr(async i=>(i>0&&await Or(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await g(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:U})),(i,n)=>{let o=200*Math.pow(2,i);return n&&tt(n)&&Date.now()+o-r<Ce})}catch(r){if(this._debug(t,"error",r),p(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),x()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await Ae(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let i=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<i+At;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${At}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),tt(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new C;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new xe;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new C;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),p(n)){let o={session:null,error:n};return tt(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Rt(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Ze(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&x()&&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(),Ce);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((r.expires_at*1e3-e)/Ce);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Ce}ms, refresh threshold is ${Nr} ticks`),i<=Nr&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof je)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!x()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await z(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await g(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r=e?.factors||[],i=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let c=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};X.nextInstanceID=0;var Hs=X,It=Hs;var st=class extends It{constructor(e){super(e)}};var Js=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(r.next(l))}catch(u){o(u)}}function c(l){try{h(r.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((r=r.apply(s,e||[])).next())})},$e=class{constructor(e,t,r){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=wr(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:_r,realtime:vr,auth:Object.assign(Object.assign({},mr),{storageKey:c}),global:gr},l=br(r??{},h);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=yr(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new tr(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new he(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Se(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Js(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:n,flowType:o,debug:a},c,h){var l;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new st({url:this.authUrl,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new te(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var qr=(s,e,t)=>new $e(s,e,t);var ce={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var it=class{constructor(){this.sessionData=null;this.supabase=qr(ce.supaBaseUrl,ce.supaBaseKey)}async signInWithGoogle(){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:ce.redirectUri}}),console.log("Signed in with Google")}catch(e){throw console.error("Error signing in with Google:",e),e}}async signInWithApple(){try{await this.supabase.auth.signInWithOAuth({provider:"apple",options:{redirectTo:ce.redirectUri}}),console.log("Signed in with Apple")}catch(e){throw console.error("Error signing in with Apple:",e),e}}async setSession(e,t){try{let{data:r,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw this.signOut(),console.error("Error setting session:",r),r}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,r){let i=new Date;i.setTime(i.getTime()+r*24*60*60*1e3);let n=`expires=${i.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{await this.setSession(t,r)}catch(i){throw i}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,i]=t.split("=");return e[r]=i,e},{})}async signOut(){try{let{error:e}=await this.supabase.auth.signOut();if(e)throw e;console.log("Signed out successfully"),this.sessionData=null,this.setCookie("access_token","",-1),this.setCookie("refresh_token","",-1)}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e){try{let{error:t}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:ce.redirectUri}});if(t)throw t}catch(t){throw console.error("Error sending magic link:",t),t}}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 Mr=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var nt=(s,e)=>{window.posthog.capture(s,e)};var zs=async()=>{let s=await navigator.userAgentData.getHighEntropyValues(["architecture","platform"]);return s.platform==="macOS"?s.architecture==="arm"?"mac_m1":"mac_intel":s.platform},Gs=()=>{let e=new URLSearchParams(window.location.search).get("referral");if(e){let t=new Date;t.setTime(t.getTime()+30*24*60*60*1e3),document.cookie=`referral=${e};expires=${t.toUTCString()};path=/;domain=.flowvoice.ai;`}};window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=new it,{accessToken:e,refreshToken:t}=qt();Gs();let r=await zs(),i=document.querySelector("#email-form"),n=document.querySelector("#email-input"),o=document.querySelector("#google-login"),a=document.querySelector("#apple-login"),c=Mr(),{dclid:h,referral:l}=c,u=localStorage.getItem("email");if(e&&t)try{s.setCookies(e,t),await s.checkAndSetSession();let d=s.sessionData?.user.email;localStorage.setItem("email",d),window.location.href="/downloads"}catch(d){console.error("Error during session setup:",d)}else u&&(window.location.href="/downloads");o.addEventListener("click",async()=>{try{nt("email_submission_success",{signin_provider:"google",device_type:r,dclid:h,referral:l}),await s.signInWithGoogle()}catch(d){console.error("Error during sign-in:",d)}}),a.addEventListener("click",async()=>{try{nt("email_submission_success",{signin_provider:"apple",device_type:r,dclid:h,referral:l}),await s.signInWithApple()}catch(d){console.error("Error during sign-in:",d)}}),i.addEventListener("submit",async d=>{d.stopPropagation(),d.preventDefault();let f=n.value;if(!f||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f)){console.error("Email invalid");return}let v={email:f,first_name:"",last_name:"",dub_click_id:h||void 0,referral:l||void 0};nt("email_submission_success",{signin_provider:"email",device_type:r,dclid:h,referral:l}),localStorage.setItem("email",f),await Dt.addRawUserEmail(v),window.location.href="/downloads"})});})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanay-wispr/webflow-package",
3
- "version": "3.6.1",
3
+ "version": "4.0.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -1 +0,0 @@
1
- "use strict";(()=>{var Vr=Object.create;var Ne=Object.defineProperty;var Wr=Object.getOwnPropertyDescriptor;var Qr=Object.getOwnPropertyNames;var Yr=Object.getPrototypeOf,Xr=Object.prototype.hasOwnProperty;var Zr=(i,e)=>()=>(i&&(e=i(i=0)),e);var j=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),es=(i,e)=>{for(var t in e)Ne(i,t,{get:e[t],enumerable:!0})},qt=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Qr(e))!Xr.call(i,s)&&s!==t&&Ne(i,s,{get:()=>e[s],enumerable:!(r=Wr(e,s))||r.enumerable});return i};var Ht=(i,e,t)=>(t=i!=null?Vr(Yr(i)):{},qt(e||!i||!i.__esModule?Ne(t,"default",{value:i,enumerable:!0}):t,i)),ts=i=>qt(Ne({},"__esModule",{value:!0}),i);var H={};es(H,{Headers:()=>mt,Request:()=>is,Response:()=>ns,default:()=>pt,fetch:()=>ss});var rs,re,ss,pt,mt,is,ns,F=Zr(()=>{"use strict";rs=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")},re=rs(),ss=re.fetch,pt=re.fetch.bind(re),mt=re.Headers,is=re.Request,ns=re.Response});var Wt=j(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});var gt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};_t.default=gt});var vt=j(ge=>{"use strict";var Qt=ge&&ge.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ge,"__esModule",{value:!0});var as=Qt((F(),ts(H))),ls=Qt(Wt()),yt=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=as.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let r=this.fetch,s=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let h=null,c=null,u=null,d=n.status,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let T=await n.text();T===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=T:c=JSON.parse(T))}let v=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),y=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");v&&y&&y.length>1&&(u=parseInt(y[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(h={code:"PGRST116",details:`Results contain ${c.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},c=null,u=null,d=406,f="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{let v=await n.text();try{h=JSON.parse(v),Array.isArray(h)&&n.status===404&&(c=[],h=null,d=200,f="OK")}catch{n.status===404&&v===""?(d=204,f="No Content"):h={message:v}}if(h&&this.isMaybeSingle&&(!((l=h?.details)===null||l===void 0)&&l.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new ls.default(h)}return{error:h,data:c,count:u,status:d,statusText:f}});return this.shouldThrowOnError||(s=s.catch(n=>{var o,a,l;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:`${(l=n?.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}};ge.default=yt});var bt=j(_e=>{"use strict";var cs=_e&&_e.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(_e,"__esModule",{value:!0});var hs=cs(vt()),wt=class extends hs.default{select(e){let t=!1,r=(e??"*").split("").map(s=>/\s/.test(s)&&!t?"":(s==='"'&&(t=!t),s)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){let n=typeof s>"u"?"offset":`${s}.offset`,o=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:o="text"}={}){var a;let l=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"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=${l};`,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}};_e.default=wt});var Ge=j(ye=>{"use strict";var us=ye&&ye.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ye,"__esModule",{value:!0});var ds=us(bt()),kt=class extends ds.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(s=>typeof s=="string"&&new RegExp("[,()]").test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};ye.default=kt});var Et=j(we=>{"use strict";var fs=we&&we.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(we,"__esModule",{value:!0});var ve=fs(Ge()),St=class{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=t,this.schema=r,this.fetch=s}select(e,{head:t=!1,count:r}={}){let s=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new ve.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let s="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){let a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new ve.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),s&&a.push(`count=${s}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let l=e.reduce((h,c)=>h.concat(Object.keys(c)),[]);if(l.length>0){let h=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",h.join(","))}}return new ve.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r="PATCH",s=[];return this.headers.Prefer&&s.push(this.headers.Prefer),t&&s.push(`count=${t}`),this.headers.Prefer=s.join(","),new ve.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new ve.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};we.default=St});var Yt=j(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.version=void 0;Ke.version="0.0.0-automated"});var Xt=j(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.DEFAULT_HEADERS=void 0;var ps=Yt();Ve.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${ps.version}`}});var er=j(be=>{"use strict";var Zt=be&&be.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(be,"__esModule",{value:!0});var ms=Zt(Et()),gs=Zt(Ge()),_s=Xt(),Tt=class i{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=Object.assign(Object.assign({},_s.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=s}from(e){let t=new URL(`${this.url}/${e}`);return new ms.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new i(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:s=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),l;r||s?(o=r?"HEAD":"GET",Object.entries(t).filter(([c,u])=>u!==void 0).map(([c,u])=>[c,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([c,u])=>{a.searchParams.append(c,u)})):(o="POST",l=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new gs.default({method:o,url:a,headers:h,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};be.default=Tt});var or=j(E=>{"use strict";var ke=E&&E.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(E,"__esModule",{value:!0});E.PostgrestBuilder=E.PostgrestTransformBuilder=E.PostgrestFilterBuilder=E.PostgrestQueryBuilder=E.PostgrestClient=void 0;var tr=ke(er());E.PostgrestClient=tr.default;var rr=ke(Et());E.PostgrestQueryBuilder=rr.default;var sr=ke(Ge());E.PostgrestFilterBuilder=sr.default;var ir=ke(bt());E.PostgrestTransformBuilder=ir.default;var nr=ke(vt());E.PostgrestBuilder=nr.default;E.default={PostgrestClient:tr.default,PostgrestQueryBuilder:rr.default,PostgrestFilterBuilder:sr.default,PostgrestTransformBuilder:ir.default,PostgrestBuilder:nr.default}});var mr=j((qi,pr)=>{"use strict";pr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Fe="https://api.flowvoice.ai",ft=class{static async signupUser(e){try{let t=await fetch(`${Fe}/signup`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Signup failed with status ${t.status}`);console.log("User signed up successfully")}catch(t){console.error("Error during signup:",t)}}static async addRawUserEmail(e){try{let t=await fetch(`${Fe}/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}`)}catch(t){console.error("Error during raw user signup:",t)}}static async updateUser(e){try{let t=await fetch(`${Fe}/signup_update`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`UpdateUser failed with status ${t.status}`);return(await t.json()).waitlist_number}catch(t){return console.error("Error during updating user:",t),-1}}static async applyReferralCode(e){try{let t=await fetch(`${Fe}/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}}};function Jt(i){let[e,...t]=i.split(" "),r=t.join(" ");return[e,r]}var te=ft;var zt=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,r]=e.split("=");return i[t]=r,i},{});var Gt=()=>{let i=window.location.hash.substring(1),e=new URLSearchParams(i);return{access_token:e.get("access_token"),refresh_token:e.get("refresh_token")}};var Kt=()=>{let{access_token:i,refresh_token:e}=Gt(),t=i,r=e;if(!t||!r){let s=zt();t=s.access_token,r=s.refresh_token}return{accessToken:t,refreshToken:r}};var w="data",g={googleLoginButton:`[${w}="google-login"]`,getStartedLoader:`[${w}="get-started-loader"]`,logOutButton:`[${w}="logout-button"]`,email:`[${w}="email"]`,emailField:`[${w}="email-field"]`,magicLink:`[${w}="magic-link"]`,successBlock:`[${w}="success-block"]`,magicLinkEmail:`[${w}="magic-link-email"]`,emailFormWrapper:`[${w}="email-form-wrapper"]`,platformBlock:`[${w}="platform-block"]`,socialBlock:`[${w}="social-block"]`,downloadBlock:`[${w}="download-block"]`,priorityBlock:`[${w}="priority-block"]`,thankyouBlock:`[${w}="thankyou-block"]`,referralBlock:`[${w}="referral-block"]`,referralAppliedBlock:`[${w}="referral-applied-block"]`,platformBlockButton:`[${w}="platform-block-button"]`,socialBlockButton:`[${w}="social-block-button"]`,downloadBlockButton:`[${w}="download-block-button"]`,referralBlockButton:`[${w}="referral-block-button"]`,platformCard:`[${w}="platform-card"]`,referralCodeField:`[${w}="referral-code-field"]`,referralCodeApplied:`[${w}="referral-code-applied"]`,fullNameField:`[${w}="full-name-field"]`,signUpForm:`[${w}="signup-form"]`,reEnterEmail:`[${w}="re-enter-email"]`,selectedPlatformClass:"selected",macOsApplePlatformId:"mac-apple",macOsIntelPlatformId:"mac-intel",iosPlatformId:"ios",windowsPlatformId:"windows",androidPlatformId:"android",socialsRadioGroup:"socials",validatedClass:"validated",waitlistNumber:"waitlist-number",onboardingForm:"#email-form"},de={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/get-started`},Me="/sign-up";var fe=()=>{window.location.href=Me};var Vt=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(F(),H)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var pe=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},qe=class extends pe{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},He=class extends pe{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Je=class extends pe{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},ze;(function(i){i.Any="any",i.ApNortheast1="ap-northeast-1",i.ApNortheast2="ap-northeast-2",i.ApSouth1="ap-south-1",i.ApSoutheast1="ap-southeast-1",i.ApSoutheast2="ap-southeast-2",i.CaCentral1="ca-central-1",i.EuCentral1="eu-central-1",i.EuWest1="eu-west-1",i.EuWest2="eu-west-2",i.EuWest3="eu-west-3",i.SaEast1="sa-east-1",i.UsEast1="us-east-1",i.UsWest1="us-west-1",i.UsWest2="us-west-2"})(ze||(ze={}));var os=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):s(c.value).then(a,l)}h((r=r.apply(i,e||[])).next())})},me=class{constructor(e,{headers:t={},customFetch:r,region:s=ze.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=Vt(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return os(this,void 0,void 0,function*(){try{let{headers:s,method:n,body:o}=t,a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let h;o&&(s&&!Object.prototype.hasOwnProperty.call(s,"Content-Type")||!s)&&(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 c=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),s),body:h}).catch(_=>{throw new qe(_)}),u=c.headers.get("x-relay-error");if(u&&u==="true")throw new He(c);if(!c.ok)throw new Je(c);let d=((r=c.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield c.json():d==="application/octet-stream"?f=yield c.blob():d==="text/event-stream"?f=c:d==="multipart/form-data"?f=yield c.formData():f=yield c.text(),{data:f,error:null}}catch(s){return{data:null,error:s}}})}};var ar=Ht(or(),1),{PostgrestClient:lr,PostgrestQueryBuilder:Si,PostgrestFilterBuilder:Ei,PostgrestTransformBuilder:Ti,PostgrestBuilder:xi}=ar.default;var cr="2.10.2";var hr={"X-Client-Info":`realtime-js/${cr}`},ur="1.0.0",Qe=1e4,dr=1e3,J;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(J||(J={}));var x;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})(x||(x={}));var A;(function(i){i.close="phx_close",i.error="phx_error",i.join="phx_join",i.reply="phx_reply",i.leave="phx_leave",i.access_token="access_token"})(A||(A={}));var We;(function(i){i.websocket="websocket"})(We||(We={}));var M;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(M||(M={}));var Se=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let s=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=r.decode(e.slice(o,o+s));o=o+s;let l=r.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:h}}};var z=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 b;(function(i){i.abstime="abstime",i.bool="bool",i.date="date",i.daterange="daterange",i.float4="float4",i.float8="float8",i.int2="int2",i.int4="int4",i.int4range="int4range",i.int8="int8",i.int8range="int8range",i.json="json",i.jsonb="jsonb",i.money="money",i.numeric="numeric",i.oid="oid",i.reltime="reltime",i.text="text",i.time="time",i.timestamp="timestamp",i.timestamptz="timestamptz",i.timetz="timetz",i.tsrange="tsrange",i.tstzrange="tstzrange"})(b||(b={}));var At=(i,e,t={})=>{var r;let s=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=ys(o,i,e,s),n),{})},ys=(i,e,t,r)=>{let s=e.find(a=>a.name===i),n=s?.type,o=t[i];return n&&!r.includes(n)?fr(n,o):xt(o)},fr=(i,e)=>{if(i.charAt(0)==="_"){let t=i.slice(1,i.length);return ks(e,t)}switch(i){case b.bool:return vs(e);case b.float4:case b.float8:case b.int2:case b.int4:case b.int8:case b.numeric:case b.oid:return ws(e);case b.json:case b.jsonb:return bs(e);case b.timestamp:return Ss(e);case b.abstime:case b.date:case b.daterange:case b.int4range:case b.int8range:case b.money:case b.reltime:case b.text:case b.time:case b.timestamptz:case b.timetz:case b.tsrange:case b.tstzrange:return xt(e);default:return xt(e)}},xt=i=>i,vs=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},ws=i=>{if(typeof i=="string"){let e=parseFloat(i);if(!Number.isNaN(e))return e}return i},bs=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},ks=(i,e)=>{if(typeof i!="string")return i;let t=i.length-1,r=i[t];if(i[0]==="{"&&r==="}"){let n,o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>fr(e,a))}return i},Ss=i=>typeof i=="string"?i.replace(" ","T"):i,Ye=i=>{let e=i;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var G=class{constructor(e,t,r={},s=Qe){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};var Ot;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(Ot||(Ot={}));var se=class i{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},s=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=i.syncState(this.state,s,n,o),this.pendingDiffs.forEach(l=>{this.state=i.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},s=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=i.syncDiff(this.state,s,n,o),a())}),this.onJoin((s,n,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:n,newPresences:o})}),this.onLeave((s,n,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){let n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(h,c)=>{o[h]||(l[h]=c)}),this.map(o,(h,c)=>{let u=n[h];if(u){let d=c.map(y=>y.presence_ref),f=u.map(y=>y.presence_ref),_=c.filter(y=>f.indexOf(y.presence_ref)<0),v=u.filter(y=>d.indexOf(y.presence_ref)<0);_.length>0&&(a[h]=_),v.length>0&&(l[h]=v)}else a[h]=c}),this.syncDiff(n,{joins:a,leaves:l},r,s)}static syncDiff(e,t,r,s){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(n,(a,l)=>{var h;let c=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(l),c.length>0){let u=e[a].map(f=>f.presence_ref),d=c.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}r(a,c,l)}),this.map(o,(a,l)=>{let h=e[a];if(!h)return;let c=l.map(u=>u.presence_ref);h=h.filter(u=>c.indexOf(u.presence_ref)<0),e[a]=h,s(a,h,l),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let s=e[r];return"metas"in s?t[r]=s.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=s,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 Ct;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(Ct||(Ct={}));var Pt;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes"})(Pt||(Pt={}));var Rt;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(Rt||(Rt={}));var ie=class i{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=x.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 G(this,A.join,this.params,this.timeout),this.rejoinTimer=new z(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=x.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=x.closed,this.socket._remove(this)}),this._onError(s=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,s),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this._on(A.reply,{},(s,n)=>{this._trigger(this._replyEventName(n),s)}),this.presence=new se(this),this.broadcastEndpointURL=Ye(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var r,s;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(c=>e&&e("CHANNEL_ERROR",c)),this._onClose(()=>e&&e("CLOSED"));let l={},h={broadcast:n,presence:o,postgres_changes:(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(c=>c.filter))!==null&&s!==void 0?s:[],private:a};this.socket.accessToken&&(l.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:h},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:c})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),c===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,f=(u=d?.length)!==null&&u!==void 0?u:0,_=[];for(let v=0;v<f;v++){let y=d[v],{filter:{event:T,schema:B,table:$,filter:P}}=y,R=c&&c[v];if(R&&R.event===T&&R.schema===B&&R.table===$&&R.filter===P)_.push(Object.assign(Object.assign({},y),{id:R.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e("SUBSCRIBED");return}}).receive("error",c=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(c).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,s;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 l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((s=l.body)===null||s===void 0?void 0:s.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.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=x.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(A.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let s=new G(this,A.leave,{},e);s.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),s.send(),this._canPush()||s.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new G(this,e,t,r);return this._canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:h,join:c}=A;if(r&&[a,l,h,c].indexOf(o)>=0&&r!==this._joinRef())return;let d=this._onMessage(o,t,r);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(f=>{var _,v,y;return((_=f.filter)===null||_===void 0?void 0:_.event)==="*"||((y=(v=f.filter)===null||v===void 0?void 0:v.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===o}).map(f=>f.callback(d,r)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var _,v,y,T,B,$;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let P=f.id,R=(_=f.filter)===null||_===void 0?void 0:_.event;return P&&((v=t.ids)===null||v===void 0?void 0:v.includes(P))&&(R==="*"||R?.toLocaleLowerCase()===((y=t.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))}else{let P=(B=(T=f?.filter)===null||T===void 0?void 0:T.event)===null||B===void 0?void 0:B.toLocaleLowerCase();return P==="*"||P===(($=t?.event)===null||$===void 0?void 0:$.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let _=d.data,{schema:v,table:y,commit_timestamp:T,type:B,errors:$}=_;d=Object.assign(Object.assign({},{schema:v,table:y,commit_timestamp:T,eventType:B,new:{},old:{},errors:$}),this._getPayloadRecords(_))}f.callback(d,r)})}_isClosed(){return this.state===x.closed}_isJoined(){return this.state===x.joined}_isJoining(){return this.state===x.joining}_isLeaving(){return this.state===x.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let s=e.toLocaleLowerCase(),n={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(n):this.bindings[s]=[n],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(s=>{var n;return!(((n=s.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&i.isEqual(s.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(A.close,{},e)}_onError(e){this._on(A.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=x.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=At(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=At(e.columns,e.old_record)),t}};var Ts=()=>{},xs=typeof WebSocket<"u",ne=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=hr,this.params={},this.timeout=Qe,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Ts,this.conn=null,this.sendBuffer=[],this.serializer=new Se,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(F(),H)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${We.websocket}`,this.httpEndpoint=Ye(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 s=(r=t?.params)===null||r===void 0?void 0:r.apikey;s&&(this.accessToken=s,this.apiKey=s),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 z(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(xs){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new $t(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Ht(mr())).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case J.connecting:return M.Connecting;case J.open:return M.Open;case J.closing:return M.Closing;default:return M.Closed}}isConnected(){return this.connectionState()===M.Open}channel(e,t={config:{}}){let r=new ie(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:s,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${r} (${n})`,s),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(A.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:ur}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:s,payload:n,ref:o}=t;(o&&o===this.pendingHeartbeatRef||s===n?.type)&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${s} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(s,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(A.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${r}${s}`}_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(dr,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},$t=class{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=J.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}};var oe=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function k(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}var Xe=class extends oe{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Ee=class extends oe{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var As=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):s(c.value).then(a,l)}h((r=r.apply(i,e||[])).next())})},Ze=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(F(),H)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},gr=()=>As(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(F(),H))).Response:Response});var ae=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):s(c.value).then(a,l)}h((r=r.apply(i,e||[])).next())})},jt=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Os=(i,e)=>ae(void 0,void 0,void 0,function*(){let t=yield gr();i instanceof t?i.json().then(r=>{e(new Xe(jt(r),i.status||500))}).catch(r=>{e(new Ee(jt(r),r))}):e(new Ee(jt(i),i))}),Cs=(i,e,t,r)=>{let s={method:i,headers:e?.headers||{}};return i==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};function et(i,e,t,r,s,n){return ae(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,Cs(e,r,s,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Os(l,a))})})}function Te(i,e,t,r){return ae(this,void 0,void 0,function*(){return et(i,"GET",e,t,r)})}function L(i,e,t,r,s){return ae(this,void 0,void 0,function*(){return et(i,"POST",e,r,s,t)})}function _r(i,e,t,r,s){return ae(this,void 0,void 0,function*(){return et(i,"PUT",e,r,s,t)})}function tt(i,e,t,r,s){return ae(this,void 0,void 0,function*(){return et(i,"DELETE",e,r,s,t)})}var O=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):s(c.value).then(a,l)}h((r=r.apply(i,e||[])).next())})},Ps={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},yr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},xe=class{constructor(e,t={},r,s){this.url=e,this.headers=t,this.bucketId=r,this.fetch=Ze(s)}uploadOrUpdate(e,t,r,s){return O(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},yr),s),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl)):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let l=this._removeEmptyFolders(t),h=this._getFinalPath(l),c=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield c.json();return c.ok?{data:{path:l,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(k(n))return{data:null,error:n};throw n}})}upload(e,t,r){return O(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,s){return O(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 l,h=Object.assign({upsert:yr.upsert},s),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",h.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",h.cacheControl)):(l=r,c["cache-control"]=`max-age=${h.cacheControl}`,c["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:c}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(l){if(k(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return O(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),s=Object.assign({},this.headers);t?.upsert&&(s["x-upsert"]="true");let n=yield L(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:s}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new oe("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}update(e,t,r){return O(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return O(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}copy(e,t,r){return O(this,void 0,void 0,function*(){try{return{data:{path:(yield L(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,r){return O(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),n=yield L(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},r?.transform?{transform:r.transform}:{}),{headers:this.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,r){return O(this,void 0,void 0,function*(){try{let s=yield L(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{data:s.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}download(e,t){return O(this,void 0,void 0,function*(){let s=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 Te(this.fetch,`${this.url}/${s}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(k(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let r=this._getFinalPath(e),s=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&s.push(n);let a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&s.push(l);let h=s.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${h}`)}}}remove(e){return O(this,void 0,void 0,function*(){try{return{data:yield tt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}list(e,t,r){return O(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},Ps),t),{prefix:e||""});return{data:yield L(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}_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 vr="2.6.0";var wr={"X-Client-Info":`storage-js/${vr}`};var le=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):s(c.value).then(a,l)}h((r=r.apply(i,e||[])).next())})},Ae=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},wr),t),this.fetch=Ze(r)}listBuckets(){return le(this,void 0,void 0,function*(){try{return{data:yield Te(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(k(e))return{data:null,error:e};throw e}})}getBucket(e){return le(this,void 0,void 0,function*(){try{return{data:yield Te(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return le(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return le(this,void 0,void 0,function*(){try{return{data:yield _r(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}})}emptyBucket(e){return le(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}deleteBucket(e){return le(this,void 0,void 0,function*(){try{return{data:yield tt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}};var Oe=class extends Ae{constructor(e,t={},r){super(e,t,r)}from(e){return new xe(this.url,this.headers,e,this.fetch)}};var br="2.44.4";var Ce="";typeof Deno<"u"?Ce="deno":typeof document<"u"?Ce="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ce="react-native":Ce="node";var Rs={"X-Client-Info":`supabase-js-${Ce}/${br}`},kr={headers:Rs},Sr={schema:"public"},Er={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Tr={};F();var $s=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):s(c.value).then(a,l)}h((r=r.apply(i,e||[])).next())})},js=i=>{let e;return i?e=i:typeof fetch>"u"?e=pt:e=fetch,(...t)=>e(...t)},Ls=()=>typeof Headers>"u"?mt:Headers,xr=(i,e,t)=>{let r=js(t),s=Ls();return(n,o)=>$s(void 0,void 0,void 0,function*(){var a;let l=(a=yield e())!==null&&a!==void 0?a:i,h=new s(o?.headers);return h.has("apikey")||h.set("apikey",i),h.has("Authorization")||h.set("Authorization",`Bearer ${l}`),r(n,Object.assign(Object.assign({},o),{headers:h}))})};function Ar(i){return i.replace(/\/$/,"")}function Or(i,e){let{db:t,auth:r,realtime:s,global:n}=i,{db:o,auth:a,realtime:l,global:h}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},l),s),global:Object.assign(Object.assign({},h),n)}}var rt="2.64.4";var Cr="http://localhost:9999",Pr="supabase.auth.token";var Rr={"X-Client-Info":`gotrue-js/${rt}`},Lt=10;var Pe="X-Supabase-Api-Version",It={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function $r(i){return Math.round(Date.now()/1e3)+i}function jr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){let e=Math.random()*16|0;return(i=="x"?e:e&3|8).toString(16)})}var C=()=>typeof document<"u",K={tested:!1,writable:!1},q=()=>{if(!C())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(K.tested)return K.writable;let i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),K.tested=!0,K.writable=!0}catch{K.tested=!0,K.writable=!1}return K.writable};function st(i){let e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,n)=>{e[n]=s})}catch{}return t.searchParams.forEach((r,s)=>{e[s]=r}),e}var it=i=>{let e;return i?e=i:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(F(),H)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Lr=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",Ut=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},$e=async(i,e)=>{let t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},nt=async(i,e)=>{await i.removeItem(e)};function Is(i){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",r,s,n,o,a,l,h,c=0;for(i=i.replace("-","+").replace("_","/");c<i.length;)o=e.indexOf(i.charAt(c++)),a=e.indexOf(i.charAt(c++)),l=e.indexOf(i.charAt(c++)),h=e.indexOf(i.charAt(c++)),r=o<<2|a>>4,s=(a&15)<<4|l>>2,n=(l&3)<<6|h,t=t+String.fromCharCode(r),l!=64&&s!=0&&(t=t+String.fromCharCode(s)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Re=class i{constructor(){this.promise=new i.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Re.promiseConstructor=Promise;function Bt(i){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=i.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let r=t[1];return JSON.parse(Is(r))}async function Ir(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function Ur(i,e){return new Promise((r,s)=>{(async()=>{for(let n=0;n<1/0;n++)try{let o=await i(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){s(o);return}}})()})}function Us(i){return("0"+i.toString(16)).substr(-2)}function Bs(){let e=new Uint32Array(56);if(typeof crypto>"u"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length,s="";for(let n=0;n<56;n++)s+=t.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,Us).join("")}async function Ds(i){let t=new TextEncoder().encode(i),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(n=>String.fromCharCode(n)).join("")}function Ns(i){return btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Fs(i){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."),i;let t=await Ds(i);return Ns(t)}async function V(i,e,t=!1){let r=Bs(),s=r;t&&(s+="/PASSWORD_RECOVERY"),await Ut(i,`${e}-code-verifier`,s);let n=await Fs(r);return[n,r===n?"plain":"s256"]}var Ms=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Br(i){let e=i.headers.get(Pe);if(!e||!e.match(Ms))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var je=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function p(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}var ot=class extends je{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function Dr(i){return p(i)&&i.name==="AuthApiError"}var ce=class extends je{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},D=class extends je{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}},I=class extends D{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},he=class extends D{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},W=class extends D{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Q=class extends D{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}}},Le=class extends D{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},ue=class extends D{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function at(i){return p(i)&&i.name==="AuthRetryableFetchError"}var Ie=class extends D{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var qs=function(i,e){var t={};for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&e.indexOf(r)<0&&(t[r]=i[r]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(i);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(i,r[s])&&(t[r[s]]=i[r[s]]);return t},Y=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Hs=[502,503,504];async function Nr(i){var e;if(!Lr(i))throw new ue(Y(i),0);if(Hs.includes(i.status))throw new ue(Y(i),i.status);let t;try{t=await i.json()}catch(n){throw new ce(Y(n),n)}let r,s=Br(i);if(s&&s.getTime()>=It["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new Ie(Y(t),i.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 Ie(Y(t),i.status,t.weak_password.reasons);throw new ot(Y(t),i.status||500,r)}var Js=(i,e,t,r)=>{let s={method:i,headers:e?.headers||{}};return i==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};async function m(i,e,t,r){var s;let n=Object.assign({},r?.headers);n[Pe]||(n[Pe]=It["2024-01-01"].name),r?.jwt&&(n.Authorization=`Bearer ${r.jwt}`);let o=(s=r?.query)!==null&&s!==void 0?s:{};r?.redirectTo&&(o.redirect_to=r.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await zs(i,e,t+a,{headers:n,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(l):{data:Object.assign({},l),error:null}}async function zs(i,e,t,r,s,n){let o=Js(e,r,s,n),a;try{a=await i(t,Object.assign({},o))}catch(l){throw console.error(l),new ue(Y(l),0)}if(a.ok||await Nr(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await Nr(l)}}function N(i){var e;let t=null;Gs(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=$r(i.expires_in)));let r=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:r},error:null}}function Dt(i){let e=N(i);return!e.error&&i.weak_password&&typeof i.weak_password=="object"&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.message&&typeof i.weak_password.message=="string"&&i.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=i.weak_password),e}function U(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function Fr(i){return{data:i,error:null}}function Mr(i){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:n}=i,o=qs(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function qr(i){return i}function Gs(i){return i.access_token&&i.refresh_token&&i.expires_in}var Ks=function(i,e){var t={};for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&e.indexOf(r)<0&&(t[r]=i[r]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(i);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(i,r[s])&&(t[r[s]]=i[r[s]]);return t},X=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=it(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await m(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(p(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await m(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:U})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=Ks(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await m(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Mr,redirectTo:t?.redirectTo})}catch(t){if(p(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await m(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:U})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,n,o,a,l;try{let h={nextPage:null,lastPage:0,total:0},c=await m(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&n!==void 0?n:""},xform:qr});if(c.error)throw c.error;let u=await c.json(),d=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(_=>{let v=parseInt(_.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(_.split(";")[1].split("=")[1]);h[`${y}Page`]=v}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(p(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await m(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:U})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await m(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:U})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await m(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:U})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{let{data:t,error:r}=await m(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(p(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await m(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}};var Hr={getItem:i=>q()?globalThis.localStorage.getItem(i):null,setItem:(i,e)=>{q()&&globalThis.localStorage.setItem(i,e)},removeItem:i=>{q()&&globalThis.localStorage.removeItem(i)}};function Nt(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}function Jr(){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 Z={debug:!!(globalThis&&q()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Ue=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},lt=class extends Ue{};async function Ft(i,e,t){Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),Z.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",i)},e),await globalThis.navigator.locks.request(i,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async s=>{if(s){Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,s.name);try{return await t()}finally{Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,s.name)}}else{if(e===0)throw Z.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new lt(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(Z.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()}})}Jr();var Vs={url:Cr,storageKey:Pr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Rr,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Be=30*1e3,zr=3;async function Gr(i,e,t){return await t()}var ee=class i{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=i.nextInstanceID,i.nextInstanceID+=1,this.instanceID>0&&C()&&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 s=Object.assign(Object.assign({},Vs),e);if(this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.persistSession=s.persistSession,this.storageKey=s.storageKey,this.autoRefreshToken=s.autoRefreshToken,this.admin=new X({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=it(s.fetch),this.lock=s.lock||Gr,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:C()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Ft:this.lock=Gr,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?s.storage?this.storage=s.storage:q()?this.storage=Hr:(this.memoryStorage={},this.storage=Nt(this.memoryStorage)):(this.memoryStorage={},this.storage=Nt(this.memoryStorage)),C()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${rt}) ${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=C()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),r?.message==="Identity is already linked"||r?.message==="Identity is already linked to another user"?{error:r}:(await this._removeSession(),{error:r});let{session:s,redirectType:n}=t;return this._debug("#_initialize()","detected session in URL",s,"redirect type",n),await this._saveSession(s),setTimeout(async()=>{n==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",s):await this._notifyAllSubscribers("SIGNED_IN",s)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return p(e)?{error:e}:{error:new ce("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:N}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let l=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,s;try{let n;if("email"in e){let{email:c,password:u,options:d}=e,f=null,_=null;this.flowType==="pkce"&&([f,_]=await V(this.storage,this.storageKey)),n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:c,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:_},xform:N})}else if("phone"in e){let{phone:c,password:u,options:d}=e;n=await m(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:u,data:(r=d?.data)!==null&&r!==void 0?r:{},channel:(s=d?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:N})}else throw new W("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 l=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await m(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:Dt})}else if("phone"in e){let{phone:n,password:o,options:a}=e;t=await m(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:Dt})}else throw new W("You must provide either an email or phone number and a password");let{data:r,error:s}=t;return s?{data:{user:null,session:null},error:s}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new he}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,s,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.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 $e(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(t??"").split("/"),{data:n,error:o}=await m(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:N});return await nt(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 he}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:s??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:n,nonce:o}=e,a=await m(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:N}),{data:l,error:h}=a;return h?{data:{user:null,session:null},error:h}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new he}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:h})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,s,n,o;try{if("email"in e){let{email:a,options:l}=e,h=null,c=null;this.flowType==="pkce"&&([h,c]=await V(this.storage,this.storageKey));let{error:u}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(r=l?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:h,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:l}=e,{data:h,error:c}=await m(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l?.data)!==null&&s!==void 0?s:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:c}}throw new W("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let s,n;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await m(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:N});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,h=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(s){if(p(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithSSO(e){var t,r,s;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await V(this.storage,this.storageKey)),await m(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((s=e?.options)===null||s===void 0)&&s.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:Fr})}catch(n){if(p(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new I;let{error:s}=await m(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(p(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:s,options:n}=e,{error:o}=await m(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:s,options:n}=e,{data:o,error:a}=await m(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new W("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await $e(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,h,c)=>(!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(l,h,c))})}return{data:{session:e},error:null}}let{session:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:s},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 m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:U}):await this._useSession(async t=>{var r,s,n;let{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new I}:await m(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0,xform:U})})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:s,error:n}=r;if(n)throw n;if(!s.session)throw new I;let o=s.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await V(this.storage,this.storageKey));let{data:h,error:c}=await m(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:U});if(c)throw c;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return Bt(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new I;let t=Date.now()/1e3,r=t,s=!0,n=null,o=Bt(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){let{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(p(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!e?.refresh_token)throw new I;let{session:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!C())throw new Q("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Q("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Le("Not a valid PKCE flow url.");let t=st(window.location.href);if(e){if(!t.code)throw new Le("No code detected.");let{data:B,error:$}=await this._exchangeCodeForSession(t.code);if($)throw $;let P=new URL(window.location.href);return P.searchParams.delete("code"),window.history.replaceState(window.history.state,"",P.toString()),{data:{session:B.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Q(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:s,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:h}=t;if(!n||!a||!o||!h)throw new Q("No session defined in URL");let c=Math.round(Date.now()/1e3),u=parseInt(a),d=c+u;l&&(d=parseInt(l));let f=d-c;f*1e3<=Be&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let _=d-u;c-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,d,c):c-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",_,d,c);let{data:v,error:y}=await this._getUser(n);if(y)throw y;let T={provider_token:r,provider_refresh_token:s,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:T,redirectType:t.type},error:null}}catch(t){if(p(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=st(window.location.href);return!!(C()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=st(window.location.href),t=await $e(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:s,error:n}=t;if(n)return{error:n};let o=(r=s.session)===null||r===void 0?void 0:r.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Dr(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await nt(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=jr(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;this.flowType==="pkce"&&([r,s]=await V(this.storage,this.storageKey,!0));try{return await m(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(p(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:s}=await this._useSession(async n=>{var o,a,l,h,c;let{data:u,error:d}=n;if(d)throw d;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await m(this.fetch,"GET",f,{headers:this.headers,jwt:(c=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&c!==void 0?c:void 0})});if(s)throw s;return C()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r?.url),{data:{provider:e.provider,url:r?.url},error:null}}catch(r){if(p(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:n,error:o}=t;if(o)throw o;return await m(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await Ur(async s=>(s>0&&await Ir(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await m(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:N})),(s,n)=>{let o=200*Math.pow(2,s);return n&&at(n)&&Date.now()+o-r<Be})}catch(r){if(this._debug(t,"error",r),p(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),C()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await $e(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}let s=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<s+Lt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Lt}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.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",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new I;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new Re;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new I;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(s,"error",n),p(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(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){n.push(l)}});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(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Ut(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await nt(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&C()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Be);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-e)/Be);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Be}ms, refresh threshold is ${zr} ticks`),s<=zr&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Ue)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!C()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await V(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);s.push(n.toString())}return r?.skipBrowserRedirect&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;return n?{data:null,error:n}:await m(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:l}=await m(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=n?.session)===null||r===void 0?void 0:r.access_token});return l?{data:null,error:l}:(!((s=a?.totp)===null||s===void 0)&&s.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:n}=t;return n?{data:null,error:n}:await m(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r=e?.factors||[],s=r.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:r,totp:s},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:s},error:n}=e;if(n)return{data:null,error:n};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(s.access_token),a=null;o.aal&&(a=o.aal);let l=a;((r=(t=s.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(l="aal2");let c=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:c},error:null}}))}};ee.nextInstanceID=0;var Ws=ee,Mt=Ws;var ct=class extends Mt{constructor(e){super(e)}};var Qs=function(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(u){o(u)}}function l(c){try{h(r.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):s(c.value).then(a,l)}h((r=r.apply(i,e||[])).next())})},De=class{constructor(e,t,r){var s,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=Ar(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 l=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:Sr,realtime:Tr,auth:Object.assign(Object.assign({},Er),{storageKey:l}),global:kr},c=Or(r??{},h);this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=xr(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new lr(`${a}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new me(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Oe(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Qs(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,storageKey:n,flowType:o,debug:a},l,h){var c;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ct({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(c="Authorization"in this.headers)!==null&&c!==void 0?c:!1})}_initRealtimeClient(e){return new ne(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var Kr=(i,e,t)=>new De(i,e,t);var ht=class{constructor(){this.sessionData=null;this.supabase=Kr(de.supaBaseUrl,de.supaBaseKey)}async signInWithGoogle(){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:de.redirectUri}}),console.log("Signed in with Google")}catch(e){throw console.error("Error signing in with Google:",e),e}}async setSession(e,t){try{let{data:r,error:s}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(s)throw s;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw this.signOut(),console.error("Error setting session:",r),r}}setCookies(e,t){this.setCookie("access_token",e,30),this.setCookie("refresh_token",t,30)}setCookie(e,t,r){let s=new Date;s.setTime(s.getTime()+r*24*60*60*1e3);let n=`expires=${s.toUTCString()}`;document.cookie=`${e}=${t};${n};path=/`}async checkAndSetSession(){let e=this.getCookies(),t=e.access_token,r=e.refresh_token;if(t&&r)try{await this.setSession(t,r)}catch(s){throw s}else console.log("No tokens found in cookies")}getCookies(){return document.cookie.split("; ").reduce((e,t)=>{let[r,s]=t.split("=");return e[r]=s,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),fe()}catch(e){throw console.error("Error signing out:",e),e}}async signWithMagicLink(e){try{let{error:t}=await this.supabase.auth.signInWithOtp({email:e,options:{shouldCreateUser:!0,emailRedirectTo:de.redirectUri}});if(t)throw t}catch(t){throw console.error("Error sending magic link:",t),t}}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 S=(i,e)=>{i?e?i.style.setProperty("display","flex","important"):i.style.setProperty("display","none","important"):console.warn("Element not found")};var ut=()=>document.cookie.split("; ").reduce((i,e)=>{let[t,r]=e.split("=");return i[t]=r,i},{});var dt=class{constructor(e){this.isPlatformSelected=!1;this.isSocialSelected=!1;this.isReferralCodeFieldValidated=!1;this.selectedPlatformData=[{id:g.macOsApplePlatformId,selected:!1},{id:g.macOsIntelPlatformId,selected:!1},{id:g.iosPlatformId,selected:!1},{id:g.windowsPlatformId,selected:!1},{id:g.androidPlatformId,selected:!1}];if(this.supabaseInstance=e,this.onboardingForm=document.querySelector(g.onboardingForm),this.platformBlock=document.querySelector(g.platformBlock),this.socialBlock=document.querySelector(g.socialBlock),this.downloadBlock=document.querySelector(g.downloadBlock),this.priorityBlock=document.querySelector(g.priorityBlock),this.thankyouBlock=document.querySelector(g.thankyouBlock),this.referralBlock=document.querySelector(g.referralBlock),this.getStartedLoader=document.querySelector(g.getStartedLoader),this.referralAppliedBlock=document.querySelector(g.referralAppliedBlock),this.platformBlockButton=document.querySelector(g.platformBlockButton),this.socialBlockButton=document.querySelector(g.socialBlockButton),this.downloadBlockButton=document.querySelector(g.downloadBlockButton),this.referralBlockButton=document.querySelector(g.referralBlockButton),this.platformCards=Array.from(document.querySelectorAll(g.platformCard)),this.referralCodeField=document.querySelector(g.referralCodeField),this.referralCodeAppliedElement=document.querySelector(g.referralCodeApplied),!this.platformBlock||!this.socialBlock||!this.downloadBlock||!this.priorityBlock||!this.thankyouBlock||!this.referralBlock||!this.referralAppliedBlock||!this.platformBlockButton||!this.socialBlockButton||!this.downloadBlockButton||!this.referralBlockButton||!this.platformCards||!this.referralCodeField||!this.referralCodeAppliedElement)throw new Error("Element not found");this.init()}init(){this.platformCards.forEach(o=>{o.addEventListener("click",a=>this.handlePlatformCardClick(a))}),this.platformBlockButton.addEventListener("click",()=>this.handlePlatformBlockButtonClick()),this.socialBlockButton.addEventListener("click",()=>this.handleSocialBlockButtonClick()),this.downloadBlockButton.addEventListener("click",()=>this.handleDownloadBlockButtonClick()),this.referralBlockButton.addEventListener("click",()=>this.handleReferralBlockButtonClick()),this.valideReferralCodeField(),this.onboardingForm.addEventListener("submit",async o=>{o.stopPropagation(),o.preventDefault(),this.isReferralCodeFieldValidated&&this.handleReferralBlockButtonClick()});let e=this.supabaseInstance.sessionData?.user.id,t=this.supabaseInstance.sessionData?.user.email,r=this.supabaseInstance.sessionData?.user.user_metadata.full_name,s=r.split(" ")[0],n=r.indexOf(" ")>-1?r.slice(r.indexOf(" ")+1):"";e&&t&&window.analytics.identify(e,{email:t,name:r,firstName:s,lastName:n}),window.analytics.page("Signup","Platform Selection")}handlePlatformCardClick(e){let t=e.currentTarget;t.classList.toggle(g.selectedPlatformClass);let r=t.id;this.selectedPlatformData.forEach(n=>{n.id===r&&(n.selected=!n.selected)});let s=this.selectedPlatformData.some(n=>n.selected);window.analytics.track("signup_platform_selected",{platform:r,selected:s}),s?(this.platformBlockButton.classList.add(g.validatedClass),this.isPlatformSelected=!0):(this.platformBlockButton.classList.remove(g.validatedClass),this.isPlatformSelected=!1)}async handlePlatformBlockButtonClick(){if(!this.isPlatformSelected)return;let e=await this.supabaseInstance.getSession();if(!e){console.error("User not found");return}let t=this.selectedPlatformData.filter(s=>s.selected).map(s=>s.id),r={access_token:e.access_token,platforms:t,source:""};te.updateUser(r),window.analytics.track("signup_platform_complete"),S(this.platformBlock,!1),S(this.socialBlock,!0),window.analytics.page("Signup","Social Source")}async handleSocialBlockButtonClick(){let e=this.selectedPlatformData.filter(r=>r.selected).map(r=>r.id),t=document.querySelector(`input[name=${g.socialsRadioGroup}]:checked`);if(t)this.isSocialSelected=!0,this.socialBlockButton.classList.add(g.validatedClass);else{this.isSocialSelected=!1,this.socialBlockButton.classList.remove(g.validatedClass);return}try{S(this.getStartedLoader,!0);let r=t.value;window.analytics.track("signup_source_complete",{source:r});let s=await this.supabaseInstance.getSession();if(!s){console.error("User not found");return}let n={access_token:s.access_token,source:r,platforms:e},o=await te.updateUser(n);if(S(this.socialBlock,!1),S(this.getStartedLoader,!1),this.selectedPlatformData[0].selected)S(this.downloadBlock,!0),window.analytics.page("Signup","Download");else{S(this.priorityBlock,!0),window.analytics.page("Signup","Waitlist");let h=document.querySelector(`#${g.waitlistNumber}`);h.innerText=`You are #${o} on the priority list \u{1F389}`}let l=ut().referral;l?(this.referralCodeAppliedElement.innerText=l.toUpperCase(),await this.applyReferralCode(l)):this.selectedPlatformData[0].selected||S(this.referralBlock,!0)}catch(r){S(this.getStartedLoader,!1),console.error("Error saving source for user",r)}}handleDownloadBlockButtonClick(){window.analytics.track("signup_downloaded",{platform:"mac-apple"}),S(this.downloadBlock,!1),S(this.referralBlock,!1),S(this.referralAppliedBlock,!1),S(this.thankyouBlock,!0)}async applyReferralCode(e){let t=await this.supabaseInstance.getSession();if(!t){console.error("User not found");return}let r={access_token:t.access_token,referrer_code:e};try{window.analytics.track("apply_referral",{referral_code:e}),await te.applyReferralCode(r),S(this.referralBlock,!1),S(this.referralAppliedBlock,!0)}catch(s){console.error("Error applying referral code",s)}}async handleReferralBlockButtonClick(){if(!this.isReferralCodeFieldValidated)return;let e=this.referralCodeField.value.toUpperCase();this.referralCodeAppliedElement.innerText=e,await this.applyReferralCode(e)}valideReferralCodeField(){this.referralCodeField.addEventListener("input",()=>{if(this.referralCodeField.value){this.referralBlockButton.classList.add(g.validatedClass),this.isReferralCodeFieldValidated=!0;return}this.referralBlockButton.classList.remove(g.validatedClass),this.isReferralCodeFieldValidated=!1})}};window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let i=document.querySelector(g.getStartedLoader),e=document.querySelector(g.logOutButton),{accessToken:t,refreshToken:r}=Kt(),s=new ht;(!t||!r)&&fe();let n=ut();if(t&&r){try{s.setCookies(t,r),await s.checkAndSetSession()}catch(d){return console.error("Error during session setup:",d),fe()}let o=document.querySelector(g.email),a=s.sessionData?.user.email;o.innerText=a;let l=s.sessionData?.user.user_metadata.full_name||localStorage.getItem("fullName")||" ",[h,c]=Jt(l),u={access_token:s.sessionData?.access_token,first_name:h,last_name:c};n.dclid&&(u.dubClickID=n.dclid),await te.signupUser(u),S(i,!1)}else{let o=n.access_token,a=n.refresh_token;if(o&&a)try{await s.signOut(),console.log("User successfully logged in using tokens from cookies")}catch(l){console.error("Error logging in using tokens from cookies:",l)}}e.addEventListener("click",async()=>{try{await s.signOut(),console.log("User successfully logged out"),window.location.href=Me}catch(o){console.error("Error during logout:",o)}}),new dt(s)});})();
package/dist/home.js DELETED
@@ -1 +0,0 @@
1
- "use strict";(()=>{var r=o=>{let i="@dub/analytics",n="0.0.15";function s(){return"https://www.dubcdn.com/analytics/script.js"}function c(){return typeof window<"u"}if(!c())return;let e=s();if(document.head.querySelector(`script[src*="${e}"]`))return;let t=document.createElement("script");t.src=e,t.defer=!0,t.setAttribute("data-sdkn",i),t.setAttribute("data-sdkv",n),o.cookieOptions&&Object.keys(o.cookieOptions).length>0&&t.setAttribute("data-cookie-options",JSON.stringify(o.cookieOptions)),o.attributionModel&&t.setAttribute("data-attribution-model",o.attributionModel),t.onerror=()=>{console.log(`[Dub Web Analytics] failed to load script from ${e}.`)},document.head.appendChild(t)};window.Webflow||(window.Webflow=[]);window.Webflow.push(()=>{r({cookieOptions:{domain:".flowvoice.ai",expiresInDays:30}})});})();