@tanay-wispr/webflow-package 5.0.2 → 5.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/downloads.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";(()=>{var ir=Object.create;var ze=Object.defineProperty;var nr=Object.getOwnPropertyDescriptor;var or=Object.getOwnPropertyNames;var ar=Object.getPrototypeOf,lr=Object.prototype.hasOwnProperty;var cr=(r,e)=>()=>(r&&(e=r(r=0)),e);var j=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),hr=(r,e)=>{for(var t in e)ze(r,t,{get:e[t],enumerable:!0})},Gt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of or(e))!lr.call(r,i)&&i!==t&&ze(r,i,{get:()=>e[i],enumerable:!(s=nr(e,i))||s.enumerable});return r};var Kt=(r,e,t)=>(t=r!=null?ir(ar(r)):{},Gt(e||!r||!r.__esModule?ze(t,"default",{value:r,enumerable:!0}):t,r)),ur=r=>Gt(ze({},"__esModule",{value:!0}),r);var W={};hr(W,{Headers:()=>yt,Request:()=>pr,Response:()=>mr,default:()=>_t,fetch:()=>fr});var dr,ne,fr,_t,yt,pr,mr,H=cr(()=>{"use strict";dr=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")},ne=dr(),fr=ne.fetch,_t=ne.fetch.bind(ne),yt=ne.Headers,pr=ne.Request,mr=ne.Response});var es=j(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});var wt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};vt.default=wt});var kt=j(ve=>{"use strict";var ts=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ve,"__esModule",{value:!0});var _r=ts((H(),ur(W))),yr=ts(es()),bt=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=_r.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,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 w=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),_=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");w&&_&&_.length>1&&(u=parseInt(_[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 w=await n.text();try{h=JSON.parse(w),Array.isArray(h)&&n.status===404&&(c=[],h=null,d=200,f="OK")}catch{n.status===404&&w===""?(d=204,f="No Content"):h={message:w}}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 yr.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)}};ve.default=bt});var Et=j(be=>{"use strict";var wr=be&&be.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(be,"__esModule",{value:!0});var vr=wr(kt()),St=class extends vr.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 l=[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=${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}};be.default=St});var Qe=j(ke=>{"use strict";var br=ke&&ke.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ke,"__esModule",{value:!0});var kr=br(Et()),Tt=class extends kr.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}};ke.default=Tt});var At=j(Ee=>{"use strict";var Sr=Ee&&Ee.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Ee,"__esModule",{value:!0});var Se=Sr(Qe()),xt=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 Se.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,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 Se.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 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 Se.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 Se.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 Se.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Ee.default=xt});var ss=j(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.version=void 0;Xe.version="0.0.0-automated"});var rs=j(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.DEFAULT_HEADERS=void 0;var Er=ss();Ze.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Er.version}`}});var ns=j(Te=>{"use strict";var is=Te&&Te.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Te,"__esModule",{value:!0});var Tr=is(At()),xr=is(Qe()),Ar=rs(),Ot=class r{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},Ar.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new Tr.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}`),l;s||i?(o=s?"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 xr.default({method:o,url:a,headers:h,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};Te.default=Ot});var us=j(E=>{"use strict";var xe=E&&E.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(E,"__esModule",{value:!0});E.PostgrestBuilder=E.PostgrestTransformBuilder=E.PostgrestFilterBuilder=E.PostgrestQueryBuilder=E.PostgrestClient=void 0;var os=xe(ns());E.PostgrestClient=os.default;var as=xe(At());E.PostgrestQueryBuilder=as.default;var ls=xe(Qe());E.PostgrestFilterBuilder=ls.default;var cs=xe(Et());E.PostgrestTransformBuilder=cs.default;var hs=xe(kt());E.PostgrestBuilder=hs.default;E.default={PostgrestClient:os.default,PostgrestQueryBuilder:as.default,PostgrestFilterBuilder:ls.default,PostgrestTransformBuilder:cs.default,PostgrestBuilder:hs.default}});var vs=j((Zi,ws)=>{"use strict";ws.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Je="https://api.wisprflow.ai",gt=class{static async signupUser(e){try{let t=`${Je}/signup`,i=document.cookie.split(";").find(o=>o.trim().startsWith("trial_promo="));i&&i.trim().split("=")[1]==="3mo"&&(t+="?trial_promo=3mo");let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`Signup failed with status ${n.status}`);return console.log("User signed up successfully"),await n.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${Je}/signup_raw_email`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Adding raw user failed with status ${t.status}`);return console.log("Added raw user successfully"),await t.json()}catch(t){throw console.error("Error during raw user signup:",t),t}}static async addToWaitlist(e){try{let t=await fetch(`${Je}/add_to_waitlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying waitlist failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async applyReferralCode(e){try{let t=await fetch(`${Je}/api/v1/referral/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying referral code failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async associateAppSumoLicense(e){try{let t=await fetch("https://api.wisprflow.ai/app_sumo/associate_license_key",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}};function Vt(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}var We=gt;var Yt=()=>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 Xt=()=>{let{access_token:r,refresh_token:e}=Qt(),t=r,s=e;if(!t||!s){let i=Yt();t=i.access_token,s=i.refresh_token}return{accessToken:t,refreshToken:s}};var Zt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(H(),W)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var ye=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},Ge=class extends ye{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Ke=class extends ye{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Ve=class extends ye{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Ye;(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"})(Ye||(Ye={}));var gr=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(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((s=s.apply(r,e||[])).next())})},we=class{constructor(e,{headers:t={},customFetch:s,region:i=Ye.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Zt(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return gr(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(y=>{throw new Ge(y)}),u=c.headers.get("x-relay-error");if(u&&u==="true")throw new Ke(c);if(!c.ok)throw new Ve(c);let d=((s=c.headers.get("Content-Type"))!==null&&s!==void 0?s:"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 ds=Kt(us(),1),{PostgrestClient:fs,PostgrestQueryBuilder:$i,PostgrestFilterBuilder:Li,PostgrestTransformBuilder:Ui,PostgrestBuilder:Di}=ds.default;var ps="2.10.2";var ms={"X-Client-Info":`realtime-js/${ps}`},gs="1.0.0",tt=1e4,_s=1e3,G;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(G||(G={}));var T;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(T||(T={}));var x;(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"})(x||(x={}));var et;(function(r){r.websocket="websocket"})(et||(et={}));var B;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(B||(B={}));var Ae=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 l=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:l,payload:h}}};var K=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var v;(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"})(v||(v={}));var Rt=(r,e,t={})=>{var s;let i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Or(o,r,e,i),n),{})},Or=(r,e,t,s)=>{let i=e.find(a=>a.name===r),n=i?.type,o=t[r];return n&&!s.includes(n)?ys(n,o):Pt(o)},ys=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return jr(e,t)}switch(r){case v.bool:return Pr(e);case v.float4:case v.float8:case v.int2:case v.int4:case v.int8:case v.numeric:case v.oid:return Rr(e);case v.json:case v.jsonb:return Cr(e);case v.timestamp:return Ir(e);case v.abstime:case v.date:case v.daterange:case v.int4range:case v.int8range:case v.money:case v.reltime:case v.text:case v.time:case v.timestamptz:case v.timetz:case v.tsrange:case v.tstzrange:return Pt(e);default:return Pt(e)}},Pt=r=>r,Pr=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},Rr=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},Cr=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},jr=(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=>ys(e,a))}return r},Ir=r=>typeof r=="string"?r.replace(" ","T"):r,st=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var V=class{constructor(e,t,s={},i=tt){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 Ct;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(Ct||(Ct={}));var oe=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,i,n,o),this.pendingDiffs.forEach(l=>{this.state=r.syncDiff(this.state,l,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={},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(_=>_.presence_ref),f=u.map(_=>_.presence_ref),y=c.filter(_=>f.indexOf(_.presence_ref)<0),w=u.filter(_=>d.indexOf(_.presence_ref)<0);y.length>0&&(a[h]=y),w.length>0&&(l[h]=w)}else a[h]=c}),this.syncDiff(n,{joins:a,leaves:l},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,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)}s(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(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 jt;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(jt||(jt={}));var It;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(It||(It={}));var $t;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})($t||($t={}));var ae=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,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 V(this,x.join,this.params,this.timeout),this.rejoinTimer=new K(()=>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(x.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new oe(this),this.broadcastEndpointURL=st(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(c=>e&&e("CHANNEL_ERROR",c)),this._onClose(()=>e&&e("CLOSED"));let l={},h={broadcast:n,presence:o,postgres_changes:(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.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,y=[];for(let w=0;w<f;w++){let _=d[w],{filter:{event:S,schema:R,table:P,filter:b}}=_,m=c&&c[w];if(m&&m.event===S&&m.schema===R&&m.table===P&&m.filter===b)y.push(Object.assign(Object.assign({},_),{id:m.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,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,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 l=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s: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(x.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let i=new V(this,x.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 V(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:l,leave:h,join:c}=x;if(s&&[a,l,h,c].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 y,w,_;return((y=f.filter)===null||y===void 0?void 0:y.event)==="*"||((_=(w=f.filter)===null||w===void 0?void 0:w.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(f=>f.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var y,w,_,S,R,P;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let b=f.id,m=(y=f.filter)===null||y===void 0?void 0:y.event;return b&&((w=t.ids)===null||w===void 0?void 0:w.includes(b))&&(m==="*"||m?.toLocaleLowerCase()===((_=t.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{let b=(R=(S=f?.filter)===null||S===void 0?void 0:S.event)===null||R===void 0?void 0:R.toLocaleLowerCase();return b==="*"||b===((P=t?.event)===null||P===void 0?void 0:P.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let y=d.data,{schema:w,table:_,commit_timestamp:S,type:R,errors:P}=y;d=Object.assign(Object.assign({},{schema:w,table:_,commit_timestamp:S,eventType:R,new:{},old:{},errors:P}),this._getPayloadRecords(y))}f.callback(d,s)})}_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,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(x.close,{},e)}_onError(e){this._on(x.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=Rt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Rt(e.columns,e.old_record)),t}};var Lr=()=>{},Ur=typeof WebSocket<"u",le=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=ms,this.params={},this.timeout=tt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Lr,this.conn=null,this.sendBuffer=[],this.serializer=new Ae,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(H(),W)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${et.websocket}`,this.httpEndpoint=st(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 K(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(Ur){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Lt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Kt(vs())).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 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 s=new ae(`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 l;(l=this.conn)===null||l===void 0||l.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(x.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:gs}))}_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(x.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let s=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${s}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(_s,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Lt=class{constructor(e,t,s){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=s.close}};var ce=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function k(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var rt=class extends ce{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Oe=class extends ce{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Dr=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(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((s=s.apply(r,e||[])).next())})},it=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(H(),W)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},bs=()=>Dr(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(H(),W))).Response:Response});var he=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(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((s=s.apply(r,e||[])).next())})},Ut=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Nr=(r,e)=>he(void 0,void 0,void 0,function*(){let t=yield bs();r instanceof t?r.json().then(s=>{e(new rt(Ut(s),r.status||500))}).catch(s=>{e(new Oe(Ut(s),s))}):e(new Oe(Ut(r),r))}),qr=(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 nt(r,e,t,s,i,n){return he(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,qr(e,s,i,n)).then(l=>{if(!l.ok)throw l;return s?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Nr(l,a))})})}function Pe(r,e,t,s){return he(this,void 0,void 0,function*(){return nt(r,"GET",e,t,s)})}function I(r,e,t,s,i){return he(this,void 0,void 0,function*(){return nt(r,"POST",e,s,i,t)})}function ks(r,e,t,s,i){return he(this,void 0,void 0,function*(){return nt(r,"PUT",e,s,i,t)})}function ot(r,e,t,s,i){return he(this,void 0,void 0,function*(){return nt(r,"DELETE",e,s,i,t)})}var A=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(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((s=s.apply(r,e||[])).next())})},Mr={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ss={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Re=class{constructor(e,t={},s,i){this.url=e,this.headers=t,this.bucketId=s,this.fetch=it(i)}uploadOrUpdate(e,t,s,i){return A(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Ss),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 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,s){return A(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return A(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:Ss.upsert},i),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&s instanceof Blob?(l=new FormData,l.append("cacheControl",h.cacheControl),l.append("",s)):typeof FormData<"u"&&s instanceof FormData?(l=s,l.append("cacheControl",h.cacheControl)):(l=s,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 A(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 I(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 ce("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}update(e,t,s){return A(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return A(this,void 0,void 0,function*(){try{return{data:yield I(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(k(i))return{data:null,error:i};throw i}})}copy(e,t,s){return A(this,void 0,void 0,function*(){try{return{data:{path:(yield I(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(k(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return A(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield I(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(k(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return A(this,void 0,void 0,function*(){try{let i=yield I(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(k(i))return{data:null,error:i};throw i}})}download(e,t){return A(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 Pe(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 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",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&i.push(l);let h=i.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${h}`)}}}remove(e){return A(this,void 0,void 0,function*(){try{return{data:yield ot(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,s){return A(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Mr),t),{prefix:e||""});return{data:yield I(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),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 Es="2.6.0";var Ts={"X-Client-Info":`storage-js/${Es}`};var ue=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((s=s.apply(r,e||[])).next())})},Ce=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},Ts),t),this.fetch=it(s)}listBuckets(){return ue(this,void 0,void 0,function*(){try{return{data:yield Pe(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 ue(this,void 0,void 0,function*(){try{return{data:yield Pe(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 ue(this,void 0,void 0,function*(){try{return{data:yield I(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(k(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return ue(this,void 0,void 0,function*(){try{return{data:yield ks(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(k(s))return{data:null,error:s};throw s}})}emptyBucket(e){return ue(this,void 0,void 0,function*(){try{return{data:yield I(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 ue(this,void 0,void 0,function*(){try{return{data:yield ot(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}};var je=class extends Ce{constructor(e,t={},s){super(e,t,s)}from(e){return new Re(this.url,this.headers,e,this.fetch)}};var xs="2.44.4";var Ie="";typeof Deno<"u"?Ie="deno":typeof document<"u"?Ie="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ie="react-native":Ie="node";var Fr={"X-Client-Info":`supabase-js-${Ie}/${xs}`},As={headers:Fr},Os={schema:"public"},Ps={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Rs={};H();var Hr=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(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((s=s.apply(r,e||[])).next())})},Br=r=>{let e;return r?e=r:typeof fetch>"u"?e=_t:e=fetch,(...t)=>e(...t)},zr=()=>typeof Headers>"u"?yt:Headers,Cs=(r,e,t)=>{let s=Br(t),i=zr();return(n,o)=>Hr(void 0,void 0,void 0,function*(){var a;let l=(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 ${l}`),s(n,Object.assign(Object.assign({},o),{headers:h}))})};function js(r){return r.replace(/\/$/,"")}function Is(r,e){let{db:t,auth:s,realtime:i,global:n}=r,{db:o,auth:a,realtime:l,global:h}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},l),i),global:Object.assign(Object.assign({},h),n)}}var at="2.64.4";var $s="http://localhost:9999",Ls="supabase.auth.token";var Us={"X-Client-Info":`gotrue-js/${at}`},Dt=10;var $e="X-Supabase-Api-Version",Nt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Ds(r){return Math.round(Date.now()/1e3)+r}function Ns(){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 O=()=>typeof document<"u",Y={tested:!1,writable:!1},z=()=>{if(!O())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Y.tested)return Y.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Y.tested=!0,Y.writable=!0}catch{Y.tested=!0,Y.writable=!1}return Y.writable};function lt(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 ct=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(H(),W)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},qs=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",qt=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},Ue=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},ht=async(r,e)=>{await r.removeItem(e)};function Jr(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,i,n,o,a,l,h,c=0;for(r=r.replace("-","+").replace("_","/");c<r.length;)o=e.indexOf(r.charAt(c++)),a=e.indexOf(r.charAt(c++)),l=e.indexOf(r.charAt(c++)),h=e.indexOf(r.charAt(c++)),s=o<<2|a>>4,i=(a&15)<<4|l>>2,n=(l&3)<<6|h,t=t+String.fromCharCode(s),l!=64&&i!=0&&(t=t+String.fromCharCode(i)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Le=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Le.promiseConstructor=Promise;function Mt(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(Jr(s))}async function Ms(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function Fs(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 Wr(r){return("0"+r.toString(16)).substr(-2)}function Gr(){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,Wr).join("")}async function Kr(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 Vr(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Yr(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 Kr(r);return Vr(t)}async function Q(r,e,t=!1){let s=Gr(),i=s;t&&(i+="/PASSWORD_RECOVERY"),await qt(r,`${e}-code-verifier`,i);let n=await Yr(s);return[n,s===n?"plain":"s256"]}var Qr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Hs(r){let e=r.headers.get($e);if(!e||!e.match(Qr))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var De=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 ut=class extends De{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function Bs(r){return p(r)&&r.name==="AuthApiError"}var de=class extends De{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},D=class extends De{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}},$=class extends D{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},fe=class extends D{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},X=class extends D{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Z=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}}},Ne=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}}},pe=class extends D{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function dt(r){return p(r)&&r.name==="AuthRetryableFetchError"}var qe=class extends D{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var Xr=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},ee=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Zr=[502,503,504];async function zs(r){var e;if(!qs(r))throw new pe(ee(r),0);if(Zr.includes(r.status))throw new pe(ee(r),r.status);let t;try{t=await r.json()}catch(n){throw new de(ee(n),n)}let s,i=Hs(r);if(i&&i.getTime()>=Nt["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 qe(ee(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 qe(ee(t),r.status,t.weak_password.reasons);throw new ut(ee(t),r.status||500,s)}var ei=(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[$e]||(n[$e]=Nt["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():"",l=await ti(r,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function ti(r,e,t,s,i,n){let o=ei(e,s,i,n),a;try{a=await r(t,Object.assign({},o))}catch(l){throw console.error(l),new pe(ee(l),0)}if(a.ok||await zs(a),s?.noResolveJson)return a;try{return await a.json()}catch(l){await zs(l)}}function N(r){var e;let t=null;si(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=Ds(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function Ft(r){let e=N(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 L(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function Js(r){return{data:r,error:null}}function Ws(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=Xr(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},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Gs(r){return r}function si(r){return r.access_token&&r.refresh_token&&r.expires_in}var ri=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},te=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=ct(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:L})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=ri(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:Ws,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:L})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,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:(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:Gs});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(y=>{let w=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(y.split(";")[1].split("=")[1]);h[`${_}Page`]=w}),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:L})}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:L})}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:L})}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 Ks={getItem:r=>z()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{z()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{z()&&globalThis.localStorage.removeItem(r)}};function Ht(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function Vs(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var se={debug:!!(globalThis&&z()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Me=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},ft=class extends Me{};async function Bt(r,e,t){se.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),se.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){se.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{se.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw se.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new ft(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(se.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}Vs();var ii={url:$s,storageKey:Ls,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Us,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Fe=30*1e3,Ys=3;async function Qs(r,e,t){return await t()}var re=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&&O()&&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({},ii),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new te({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=ct(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:O()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Bt: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:z()?this.storage=Ks:(this.memoryStorage={},this.storage=Ht(this.memoryStorage)):(this.memoryStorage={},this.storage=Ht(this.memoryStorage)),O()&&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} (${at}) ${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=O()?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 de("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: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,s,i;try{let n;if("email"in e){let{email:c,password:u,options:d}=e,f=null,y=null;this.flowType==="pkce"&&([f,y]=await Q(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:y},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:(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:N})}else throw new X("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let 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:Ft})}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:Ft})}else throw new X("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 fe}:(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 Ue(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:N});return await ht(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 fe}:(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: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 fe}:(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,s,i,n,o;try{if("email"in e){let{email:a,options:l}=e,h=null,c=null;this.flowType==="pkce"&&([h,c]=await Q(this.storage,this.storageKey));let{error:u}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!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 X("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,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: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,s,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Q(this.storage,this.storageKey)),await g(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(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:Js})}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 $;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 X("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let 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 Ue(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:(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:L}):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 $}: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:L})})}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 $;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Q(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:L});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(s){if(p(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return Mt(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 $;let t=Date.now()/1e3,s=t,i=!0,n=null,o=Mt(e.access_token);if(o.exp&&(s=o.exp,i=s<=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: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 $;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(!O())throw new Z("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Z("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Ne("Not a valid PKCE flow url.");let t=lt(window.location.href);if(e){if(!t.code)throw new Ne("No code detected.");let{data:R,error:P}=await this._exchangeCodeForSession(t.code);if(P)throw P;let b=new URL(window.location.href);return b.searchParams.delete("code"),window.history.replaceState(window.history.state,"",b.toString()),{data:{session:R.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Z(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,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 Z("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<=Fe&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let y=d-u;c-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,d,c):c-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",y,d,c);let{data:w,error:_}=await this._getUser(n);if(_)throw _;let S={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:w.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=lt(window.location.href);return!!(O()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=lt(window.location.href),t=await Ue(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&&!(Bs(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await ht(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Ns(),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 Q(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,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 O()&&!(!((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 Fs(async i=>(i>0&&await Ms(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&&dt(n)&&Date.now()+o-s<Fe})}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),O()&&!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 Ue(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+Dt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Dt}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),dt(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 $;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Le;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new $;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 dt(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(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 qt(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await ht(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&O()&&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(),Fe);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)/Fe);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Fe}ms, refresh threshold is ${Ys} ticks`),i<=Ys&&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 Me)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!O()||!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 Q(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: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:(s=n?.session)===null||s===void 0?void 0:s.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 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 l=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&&(l="aal2");let c=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:c},error:null}}))}};re.nextInstanceID=0;var ni=re,zt=ni;var pt=class extends zt{constructor(e){super(e)}};var oi=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(c){try{h(s.next(c))}catch(u){o(u)}}function l(c){try{h(s.throw(c))}catch(u){o(u)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((s=s.apply(r,e||[])).next())})},He=class{constructor(e,t,s){var i,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=js(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let l=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:Os,realtime:Rs,auth:Object.assign(Object.assign({},Ps),{storageKey:l}),global:As},c=Is(s??{},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=Cs(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new fs(`${a}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new we(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new je(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 oi(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},l,h){var c;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new pt({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(c="Authorization"in this.headers)!==null&&c!==void 0?c:!1})}_initRealtimeClient(e){return new le(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 Xs=(r,e,t)=>new He(r,e,t);var me={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var mt=class{constructor(){this.sessionData=null;this.supabase=Xs(me.supaBaseUrl,me.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||me.redirectUri}}),console.log("Signed in with Google")}catch(t){throw console.error("Error signing in with Google:",t),t}}async signInWithApple(e){try{await this.supabase.auth.signInWithOAuth({provider:"apple",options:{redirectTo:e||me.redirectUri}}),console.log("Signed in with Apple")}catch(t){throw console.error("Error signing in with Apple:",t),t}}async setSession(e,t){try{let{data:s,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=s?.session??null,this.sessionData}catch(s){throw 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:me.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}};function ai(){try{let r=document.createElement("canvas"),e=r.getContext("webgl")||r.getContext("experimental-webgl");if(e){let t=e.getExtension("WEBGL_debug_renderer_info");if(!t)return"mac_unknown";let s=e.getParameter(t.UNMASKED_RENDERER_WEBGL);console.log(`WebGL Renderer: ${s}`);let i=String(s||"").toLowerCase();return i.includes("apple gpu")?"mac_unknown":i.includes("apple")?"mac_m1":i.includes("intel")||i.includes("amd")||i.includes("nvidia")?"mac_intel":"mac_unknown"}}catch{}return"mac_unknown"}var Zs=async()=>{if(navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1)return"iOS";try{let r=await navigator.userAgentData.getHighEntropyValues(["architecture","platform"]);return r.platform==="macOS"?r.architecture==="arm"?"mac_m1":"mac_intel":r.platform}catch{let{userAgent:r}=navigator;return r.includes("Macintosh")?ai():r.includes("Windows")?"Windows":r.includes("Linux")?"Linux":/iPhone|iPad|iPod/.test(r)?"iOS":/Android/.test(r)?"Android":"Unknown"}};var er=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var q=(r,e)=>{window.posthog.capture(r,e)};window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let r=sessionStorage.getItem("referral_status");r&&console.log("raw email signup:",JSON.parse(r));let e=new URLSearchParams(window.location.search),t=e.get("referral"),s=e.get("plan"),i=e.get("stripe_checkout_success");console.log("Referral queryparam:",t),console.log("Plan queryparam:",s);let n=!1,o=setTimeout(()=>{n||(document.body.style.visibility="visible")},4e3),a=new mt,{accessToken:l,refreshToken:h}=Xt(),c;try{c=await Zs()}catch(m){console.error("Platform detection failed:",m),c="Unknown"}let u=localStorage.getItem("email");if((t||s)&&u&&(!l||!h)){localStorage.removeItem("email"),localStorage.removeItem("conversion_sent"),sessionStorage.removeItem("referral_status"),window.location.href=`/get-started${window.location.search}`;return}i==="true"&&q("stripe_checkout_success",{email:localStorage.getItem("email"),device_type:c,source:"downloads_page",plan:localStorage.getItem("checkout_plan")}),localStorage.removeItem("checkout_plan");let d=document.querySelector("#hello-text"),f=document.querySelector("#logout-button");f.style.display="none";let y=er(),{dub_id:w,referral:_}=y;if(l&&h)try{a.setCookies(l,h);let m=a.checkAndSetSession(),M=new Promise((Be,J)=>setTimeout(()=>J(new Error("Session timeout")),3e3));await Promise.race([m,M]);let U=a.sessionData?.user.email,F=a.sessionData?.user.user_metadata.full_name||" ",[ie,ge]=Vt(F),_e=a.sessionData?.user.id,C={access_token:l,first_name:ie,last_name:ge,dub_click_id:w||void 0,referral:_||void 0};if(localStorage.setItem("email",U),!localStorage.getItem("conversion_sent")||t){let Be=await We.signupUser(C);t&&(hi(Be),console.log("OAuth signup response:",Be),console.log("Showing referral UI"))}if(localStorage.getItem("conversion_sent")||await li(c,w,_,U),d.textContent=`Hi ${ie}!`,f.style.display="flex",s&&l){if(!["FLOW_PRO_MONTHLY","FLOW_PRO_YEARLY"].includes(s)){window.location.href=t?`/downloads?referral=${t}`:"/downloads";return}document.body.innerHTML='<div style="display: flex; padding-left: 20px; padding-right: 20px; text-align: center; justify-content: center; align-items: center; height: 100vh;"><h3>Checking your subscription...</h3></div>',document.body.style.visibility="visible";try{let J=await fetch("https://api.wisprflow.ai/api/v1/payment/subscription",{method:"GET",headers:{accept:"application/json",Authorization:l}});if(console.log("Subscription status response:",J),J.ok){let Wt=await J.json();if(console.log("User status:",Wt),Wt.is_subscribed){let sr=window.location.pathname;window.history.pushState({},"",sr),document.body.innerHTML=`
1
+ "use strict";(()=>{var is=Object.create;var We=Object.defineProperty;var ns=Object.getOwnPropertyDescriptor;var os=Object.getOwnPropertyNames;var as=Object.getPrototypeOf,ls=Object.prototype.hasOwnProperty;var cs=(s,e)=>()=>(s&&(e=s(s=0)),e);var j=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),hs=(s,e)=>{for(var t in e)We(s,t,{get:e[t],enumerable:!0})},Gt=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of os(e))!ls.call(s,i)&&i!==t&&We(s,i,{get:()=>e[i],enumerable:!(r=ns(e,i))||r.enumerable});return s};var Kt=(s,e,t)=>(t=s!=null?is(as(s)):{},Gt(e||!s||!s.__esModule?We(t,"default",{value:s,enumerable:!0}):t,s)),us=s=>Gt(We({},"__esModule",{value:!0}),s);var J={};hs(J,{Headers:()=>yt,Request:()=>ps,Response:()=>ms,default:()=>_t,fetch:()=>fs});var ds,ne,fs,_t,yt,ps,ms,H=cs(()=>{"use strict";ds=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")},ne=ds(),fs=ne.fetch,_t=ne.fetch.bind(ne),yt=ne.Headers,ps=ne.Request,ms=ne.Response});var er=j(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});var wt=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};vt.default=wt});var kt=j(ve=>{"use strict";var tr=ve&&ve.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ve,"__esModule",{value:!0});var _s=tr((H(),us(J))),ys=tr(er()),bt=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=_s.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 w=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),_=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");w&&_&&_.length>1&&(u=parseInt(_[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 w=await n.text();try{h=JSON.parse(w),Array.isArray(h)&&n.status===404&&(c=[],h=null,d=200,f="OK")}catch{n.status===404&&w===""?(d=204,f="No Content"):h={message:w}}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 ys.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)}};ve.default=bt});var Et=j(be=>{"use strict";var ws=be&&be.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(be,"__esModule",{value:!0});var vs=ws(kt()),St=class extends vs.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}};be.default=St});var Qe=j(ke=>{"use strict";var bs=ke&&ke.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ke,"__esModule",{value:!0});var ks=bs(Et()),Tt=class extends ks.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};ke.default=Tt});var At=j(Ee=>{"use strict";var Ss=Ee&&Ee.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ee,"__esModule",{value:!0});var Se=Ss(Qe()),xt=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 Se.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 Se.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 Se.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 Se.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 Se.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Ee.default=xt});var rr=j(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.version=void 0;Xe.version="0.0.0-automated"});var sr=j(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.DEFAULT_HEADERS=void 0;var Es=rr();Ze.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Es.version}`}});var nr=j(Te=>{"use strict";var ir=Te&&Te.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Te,"__esModule",{value:!0});var Ts=ir(At()),xs=ir(Qe()),As=sr(),Ot=class s{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},As.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new Ts.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 xs.default({method:o,url:a,headers:h,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};Te.default=Ot});var ur=j(E=>{"use strict";var xe=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 or=xe(nr());E.PostgrestClient=or.default;var ar=xe(At());E.PostgrestQueryBuilder=ar.default;var lr=xe(Qe());E.PostgrestFilterBuilder=lr.default;var cr=xe(Et());E.PostgrestTransformBuilder=cr.default;var hr=xe(kt());E.PostgrestBuilder=hr.default;E.default={PostgrestClient:or.default,PostgrestQueryBuilder:ar.default,PostgrestFilterBuilder:lr.default,PostgrestTransformBuilder:cr.default,PostgrestBuilder:hr.default}});var vr=j((Zi,wr)=>{"use strict";wr.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var ze="https://api.wisprflow.ai",gt=class{static async signupUser(e){try{let t=`${ze}/signup`,i=document.cookie.split(";").find(o=>o.trim().startsWith("trial_promo="));i&&i.trim().split("=")[1]==="3mo"&&(t+="?trial_promo=3mo");let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`Signup failed with status ${n.status}`);return console.log("User signed up successfully"),await n.json()}catch(t){throw console.error("Error during signup:",t),t}}static async addRawUserEmail(e){try{let t=await fetch(`${ze}/signup_raw_email`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Adding raw user failed with status ${t.status}`);return console.log("Added raw user successfully"),await t.json()}catch(t){throw console.error("Error during raw user signup:",t),t}}static async addToWaitlist(e){try{let t=await fetch(`${ze}/add_to_waitlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying waitlist failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async applyReferralCode(e){try{let t=await fetch(`${ze}/api/v1/referral/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Applying referral code failed with status ${t.status}`)}catch(t){throw console.error("Error applying referral code:",t),t}}static async associateAppSumoLicense(e){try{let t=await fetch("https://api.wisprflow.ai/app_sumo/associate_license_key",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Associating AppSumo license failed with status ${t.status}`);console.log("Successfully associated AppSumo license")}catch(t){throw console.error("Error associating AppSumo license:",t),t}}};function Vt(s){let[e,...t]=s.split(" "),r=t.join(" ");return[e,r]}var Je=gt;var Yt=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var Qt=()=>{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 Xt=()=>{let{access_token:s,refresh_token:e}=Qt(),t=s,r=e;if(!t||!r){let i=Yt();t=i.access_token,r=i.refresh_token}return{accessToken:t,refreshToken:r}};var Zt=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(H(),J)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};var ye=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Ge=class extends ye{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Ke=class extends ye{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Ve=class extends ye{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Ye;(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"})(Ye||(Ye={}));var gs=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())})},we=class{constructor(e,{headers:t={},customFetch:r,region:i=Ye.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Zt(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return gs(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(y=>{throw new Ge(y)}),u=c.headers.get("x-relay-error");if(u&&u==="true")throw new Ke(c);if(!c.ok)throw new Ve(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 dr=Kt(ur(),1),{PostgrestClient:fr,PostgrestQueryBuilder:$i,PostgrestFilterBuilder:Li,PostgrestTransformBuilder:Ui,PostgrestBuilder:Di}=dr.default;var pr="2.10.2";var mr={"X-Client-Info":`realtime-js/${pr}`},gr="1.0.0",tt=1e4,_r=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 x;(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"})(x||(x={}));var et;(function(s){s.websocket="websocket"})(et||(et={}));var B;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(B||(B={}));var Ae=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 K=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var v;(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"})(v||(v={}));var Rt=(s,e,t={})=>{var r;let i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=Os(o,s,e,i),n),{})},Os=(s,e,t,r)=>{let i=e.find(a=>a.name===s),n=i?.type,o=t[s];return n&&!r.includes(n)?yr(n,o):Pt(o)},yr=(s,e)=>{if(s.charAt(0)==="_"){let t=s.slice(1,s.length);return js(e,t)}switch(s){case v.bool:return Ps(e);case v.float4:case v.float8:case v.int2:case v.int4:case v.int8:case v.numeric:case v.oid:return Rs(e);case v.json:case v.jsonb:return Cs(e);case v.timestamp:return Is(e);case v.abstime:case v.date:case v.daterange:case v.int4range:case v.int8range:case v.money:case v.reltime:case v.text:case v.time:case v.timestamptz:case v.timetz:case v.tsrange:case v.tstzrange:return Pt(e);default:return Pt(e)}},Pt=s=>s,Ps=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Rs=s=>{if(typeof s=="string"){let e=parseFloat(s);if(!Number.isNaN(e))return e}return s},Cs=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},js=(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=>yr(e,a))}return s},Is=s=>typeof s=="string"?s.replace(" ","T"):s,rt=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var V=class{constructor(e,t,r={},i=tt){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 Ct;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Ct||(Ct={}));var oe=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(_=>_.presence_ref),f=u.map(_=>_.presence_ref),y=c.filter(_=>f.indexOf(_.presence_ref)<0),w=u.filter(_=>d.indexOf(_.presence_ref)<0);y.length>0&&(a[h]=y),w.length>0&&(l[h]=w)}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 jt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(jt||(jt={}));var It;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes"})(It||(It={}));var $t;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})($t||($t={}));var ae=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 V(this,x.join,this.params,this.timeout),this.rejoinTimer=new K(()=>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(x.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new oe(this),this.broadcastEndpointURL=rt(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,y=[];for(let w=0;w<f;w++){let _=d[w],{filter:{event:S,schema:R,table:P,filter:b}}=_,m=c&&c[w];if(m&&m.event===S&&m.schema===R&&m.table===P&&m.filter===b)y.push(Object.assign(Object.assign({},_),{id:m.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,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(x.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let i=new V(this,x.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){let i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new V(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:h,join:c}=x;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,w,_;return((y=f.filter)===null||y===void 0?void 0:y.event)==="*"||((_=(w=f.filter)===null||w===void 0?void 0:w.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(f=>f.callback(d,r)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var y,w,_,S,R,P;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let b=f.id,m=(y=f.filter)===null||y===void 0?void 0:y.event;return b&&((w=t.ids)===null||w===void 0?void 0:w.includes(b))&&(m==="*"||m?.toLocaleLowerCase()===((_=t.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{let b=(R=(S=f?.filter)===null||S===void 0?void 0:S.event)===null||R===void 0?void 0:R.toLocaleLowerCase();return b==="*"||b===((P=t?.event)===null||P===void 0?void 0:P.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let y=d.data,{schema:w,table:_,commit_timestamp:S,type:R,errors:P}=y;d=Object.assign(Object.assign({},{schema:w,table:_,commit_timestamp:S,eventType:R,new:{},old:{},errors:P}),this._getPayloadRecords(y))}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(x.close,{},e)}_onError(e){this._on(x.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=Rt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Rt(e.columns,e.old_record)),t}};var Ls=()=>{},Us=typeof WebSocket<"u",le=class{constructor(e,t){var r;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=mr,this.params={},this.timeout=tt,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Ls,this.conn=null,this.sendBuffer=[],this.serializer=new Ae,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(H(),J)).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${et.websocket}`,this.httpEndpoint=rt(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=(r=t?.params)===null||r===void 0?void 0:r.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t?.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new K(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(Us){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Lt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Kt(vr())).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 ae(`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(x.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:gr}))}_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(x.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(_r,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Lt=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 ce=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 st=class extends ce{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Oe=class extends ce{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};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())})},it=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(H(),J)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},br=()=>Ds(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(H(),J))).Response:Response});var he=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())})},Ut=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Ns=(s,e)=>he(void 0,void 0,void 0,function*(){let t=yield br();s instanceof t?s.json().then(r=>{e(new st(Ut(r),s.status||500))}).catch(r=>{e(new Oe(Ut(r),r))}):e(new Oe(Ut(s),s))}),qs=(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 nt(s,e,t,r,i,n){return he(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,qs(e,r,i,n)).then(l=>{if(!l.ok)throw l;return r?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Ns(l,a))})})}function Pe(s,e,t,r){return he(this,void 0,void 0,function*(){return nt(s,"GET",e,t,r)})}function I(s,e,t,r,i){return he(this,void 0,void 0,function*(){return nt(s,"POST",e,r,i,t)})}function kr(s,e,t,r,i){return he(this,void 0,void 0,function*(){return nt(s,"PUT",e,r,i,t)})}function ot(s,e,t,r,i){return he(this,void 0,void 0,function*(){return nt(s,"DELETE",e,r,i,t)})}var A=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())})},Ms={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Sr={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Re=class{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=it(i)}uploadOrUpdate(e,t,r,i){return A(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},Sr),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 A(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return A(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:Sr.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 A(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 I(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 ce("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 A(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return A(this,void 0,void 0,function*(){try{return{data:yield I(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 A(this,void 0,void 0,function*(){try{return{data:{path:(yield I(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 A(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield I(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 A(this,void 0,void 0,function*(){try{let i=yield I(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 A(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 Pe(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 A(this,void 0,void 0,function*(){try{return{data:yield ot(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 A(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Ms),t),{prefix:e||""});return{data:yield I(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 Er="2.6.0";var Tr={"X-Client-Info":`storage-js/${Er}`};var ue=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(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())})},Ce=class{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Tr),t),this.fetch=it(r)}listBuckets(){return ue(this,void 0,void 0,function*(){try{return{data:yield Pe(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 ue(this,void 0,void 0,function*(){try{return{data:yield Pe(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 ue(this,void 0,void 0,function*(){try{return{data:yield I(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 ue(this,void 0,void 0,function*(){try{return{data:yield kr(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 ue(this,void 0,void 0,function*(){try{return{data:yield I(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 ue(this,void 0,void 0,function*(){try{return{data:yield ot(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}};var je=class extends Ce{constructor(e,t={},r){super(e,t,r)}from(e){return new Re(this.url,this.headers,e,this.fetch)}};var xr="2.44.4";var Ie="";typeof Deno<"u"?Ie="deno":typeof document<"u"?Ie="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ie="react-native":Ie="node";var Fs={"X-Client-Info":`supabase-js-${Ie}/${xr}`},Ar={headers:Fs},Or={schema:"public"},Pr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Rr={};H();var Hs=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())})},Bs=s=>{let e;return s?e=s:typeof fetch>"u"?e=_t:e=fetch,(...t)=>e(...t)},Ws=()=>typeof Headers>"u"?yt:Headers,Cr=(s,e,t)=>{let r=Bs(t),i=Ws();return(n,o)=>Hs(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 jr(s){return s.replace(/\/$/,"")}function Ir(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 at="2.64.4";var $r="http://localhost:9999",Lr="supabase.auth.token";var Ur={"X-Client-Info":`gotrue-js/${at}`},Dt=10;var $e="X-Supabase-Api-Version",Nt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Dr(s){return Math.round(Date.now()/1e3)+s}function Nr(){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 O=()=>typeof document<"u",Y={tested:!1,writable:!1},W=()=>{if(!O())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Y.tested)return Y.writable;let s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),Y.tested=!0,Y.writable=!0}catch{Y.tested=!0,Y.writable=!1}return Y.writable};function lt(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 ct=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(H(),J)).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},qr=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",qt=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},Ue=async(s,e)=>{let t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},ht=async(s,e)=>{await s.removeItem(e)};function zs(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 Le=class s{constructor(){this.promise=new s.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Le.promiseConstructor=Promise;function Mt(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(zs(r))}async function Mr(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 Js(s){return("0"+s.toString(16)).substr(-2)}function Gs(){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,Js).join("")}async function Ks(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 Vs(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ys(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 Ks(s);return Vs(t)}async function Q(s,e,t=!1){let r=Gs(),i=r;t&&(i+="/PASSWORD_RECOVERY"),await qt(s,`${e}-code-verifier`,i);let n=await Ys(r);return[n,r===n?"plain":"s256"]}var Qs=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Hr(s){let e=s.headers.get($e);if(!e||!e.match(Qs))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var De=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 ut=class extends De{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function Br(s){return p(s)&&s.name==="AuthApiError"}var de=class extends De{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},D=class extends De{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}},$=class extends D{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},fe=class extends D{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},X=class extends D{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Z=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}}},Ne=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}}},pe=class extends D{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function dt(s){return p(s)&&s.name==="AuthRetryableFetchError"}var qe=class extends D{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};var Xs=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},ee=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Zs=[502,503,504];async function Wr(s){var e;if(!qr(s))throw new pe(ee(s),0);if(Zs.includes(s.status))throw new pe(ee(s),s.status);let t;try{t=await s.json()}catch(n){throw new de(ee(n),n)}let r,i=Hr(s);if(i&&i.getTime()>=Nt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new qe(ee(t),s.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[])}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new qe(ee(t),s.status,t.weak_password.reasons);throw new ut(ee(t),s.status||500,r)}var ei=(s,e,t,r)=>{let i={method:s,headers:e?.headers||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function g(s,e,t,r){var i;let n=Object.assign({},r?.headers);n[$e]||(n[$e]=Nt["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 ti(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 ti(s,e,t,r,i,n){let o=ei(e,r,i,n),a;try{a=await s(t,Object.assign({},o))}catch(l){throw console.error(l),new pe(ee(l),0)}if(a.ok||await Wr(a),r?.noResolveJson)return a;try{return await a.json()}catch(l){await Wr(l)}}function N(s){var e;let t=null;ri(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Dr(s.expires_in)));let r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function Ft(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 L(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function zr(s){return{data:s,error:null}}function Jr(s){let{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Xs(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 Gr(s){return s}function ri(s){return s.access_token&&s.refresh_token&&s.expires_in}var si=function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t},te=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=ct(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:L})}catch(r){if(p(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{let{options:t}=e,r=si(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:Jr,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:L})}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:Gr});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(y=>{let w=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(y.split(";")[1].split("=")[1]);h[`${_}Page`]=w}),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:L})}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:L})}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:L})}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 Kr={getItem:s=>W()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{W()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{W()&&globalThis.localStorage.removeItem(s)}};function Ht(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function Vr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var re={debug:!!(globalThis&&W()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Me=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},ft=class extends Me{};async function Bt(s,e,t){re.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);let r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),re.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){re.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{re.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw re.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new ft(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(re.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}Vr();var ii={url:$r,storageKey:Lr,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ur,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Fe=30*1e3,Yr=3;async function Qr(s,e,t){return await t()}var se=class s{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=s.nextInstanceID,s.nextInstanceID+=1,this.instanceID>0&&O()&&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({},ii),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new te({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=ct(i.fetch),this.lock=i.lock||Qr,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:O()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Bt:this.lock=Qr,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:W()?this.storage=Kr:(this.memoryStorage={},this.storage=Ht(this.memoryStorage)):(this.memoryStorage={},this.storage=Ht(this.memoryStorage)),O()&&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} (${at}) ${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=O()?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 de("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{let n=await 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,y=null;this.flowType==="pkce"&&([f,y]=await Q(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:y},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 X("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let 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:Ft})}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:Ft})}else throw new X("You must provide either an email or phone number and a password");let{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new fe}:(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 Ue(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 ht(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 fe}:(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 fe}:(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 Q(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 X("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform: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 Q(this.storage,this.storageKey)),await g(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:zr})}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 $;let{error:i}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(p(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:i,options:n}=e,{error:o}=await g(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:r,type:i,options:n}=e,{data:o,error:a}=await g(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new X("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Ue(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:L}):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 $}: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:L})})}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 $;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Q(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:L});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 Mt(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 $;let t=Date.now()/1e3,r=t,i=!0,n=null,o=Mt(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 $;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(!O())throw new Z("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new Z("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Ne("Not a valid PKCE flow url.");let t=lt(window.location.href);if(e){if(!t.code)throw new Ne("No code detected.");let{data:R,error:P}=await this._exchangeCodeForSession(t.code);if(P)throw P;let b=new URL(window.location.href);return b.searchParams.delete("code"),window.history.replaceState(window.history.state,"",b.toString()),{data:{session:R.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new Z(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:h}=t;if(!n||!a||!o||!h)throw new Z("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<=Fe&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let y=d-u;c-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,d,c):c-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",y,d,c);let{data:w,error:_}=await this._getUser(n);if(_)throw _;let S={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:w.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=lt(window.location.href);return!!(O()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=lt(window.location.href),t=await Ue(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&&!(Br(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await ht(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Nr(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{let{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await Q(this.storage,this.storageKey,!0));try{return await g(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(p(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:r,error:i}=await this._useSession(async n=>{var o,a,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 O()&&!(!((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 Mr(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&&dt(n)&&Date.now()+o-r<Fe})}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),O()&&!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 Ue(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+Dt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Dt}s`),n){if(this.autoRefreshToken&&r.refresh_token){let{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),dt(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 $;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Le;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new $;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 dt(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 qt(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await ht(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&O()&&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(),Fe);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)/Fe);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Fe}ms, refresh threshold is ${Yr} ticks`),i<=Yr&&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 Me)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!O()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let i=[`provider=${encodeURIComponent(t)}`];if(r?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r?.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){let[n,o]=await Q(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(r?.queryParams){let n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r?.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i?.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error: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}}))}};se.nextInstanceID=0;var ni=se,Wt=ni;var pt=class extends Wt{constructor(e){super(e)}};var oi=function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(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())})},He=class{constructor(e,t,r){var i,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let a=jr(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:Or,realtime:Rr,auth:Object.assign(Object.assign({},Pr),{storageKey:l}),global:Ar},c=Ir(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=Cr(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},c.realtime)),this.rest=new fr(`${a}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new we(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new je(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return oi(this,void 0,void 0,function*(){let{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:n,flowType:o,debug:a},l,h){var c;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new pt({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 le(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 Xr=(s,e,t)=>new He(s,e,t);var me={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var mt=class{constructor(){this.sessionData=null;this.supabase=Xr(me.supaBaseUrl,me.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||me.redirectUri}}),console.log("Signed in with Google")}catch(t){throw console.error("Error signing in with Google:",t),t}}async signInWithApple(e){try{await this.supabase.auth.signInWithOAuth({provider:"apple",options:{redirectTo:e||me.redirectUri}}),console.log("Signed in with Apple")}catch(t){throw console.error("Error signing in with Apple:",t),t}}async setSession(e,t){try{let{data:r,error:i}=await this.supabase.auth.setSession({access_token:e,refresh_token:t});if(i)throw i;return this.sessionData=r?.session??null,this.sessionData}catch(r){throw 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:me.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}};function ai(){try{let s=document.createElement("canvas"),e=s.getContext("webgl")||s.getContext("experimental-webgl");if(e){let t=e.getExtension("WEBGL_debug_renderer_info");if(!t)return"mac_unknown";let r=e.getParameter(t.UNMASKED_RENDERER_WEBGL);console.log(`WebGL Renderer: ${r}`);let i=String(r||"").toLowerCase();return i.includes("apple gpu")?"mac_unknown":i.includes("apple")?"mac_m1":i.includes("intel")||i.includes("amd")||i.includes("nvidia")?"mac_intel":"mac_unknown"}}catch{}return"mac_unknown"}var Zr=async()=>{if(navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1)return"iOS";try{let s=await navigator.userAgentData.getHighEntropyValues(["architecture","platform"]);if(s.platform==="macOS")return s.architecture&&s.architecture.includes("arm")?"mac_m1":s.architecture&&s.architecture.includes("x86")?"mac_intel":"mac_unknown";if(s.platform==="Windows"){if(s.architecture&&s.architecture.includes("x86"))return"Windows";if(s.architecture&&s.architecture.includes("arm"))return"win_unknown";if(!s.architecture){let{userAgent:e}=navigator;return/ARM64/i.test(e)?"win_unknown":/(Win64;\s*x64|WOW64)/i.test(e)?"Windows":"win_unknown"}return"win_unknown"}return s.platform}catch{let{userAgent:s}=navigator;return s.includes("Macintosh")?ai():s.includes("Windows")?/ARM64/i.test(s)?"win_unknown":"Windows":s.includes("Linux")?"Linux":/iPhone|iPad|iPod/.test(s)?"iOS":/Android/.test(s)?"Android":"Unknown"}};var es=()=>document.cookie.split("; ").reduce((s,e)=>{let[t,r]=e.split("=");return s[t]=r,s},{});var q=(s,e)=>{window.posthog.capture(s,e)};window.Webflow||(window.Webflow=[]);window.Webflow.push(async()=>{let s=sessionStorage.getItem("referral_status");s&&console.log("raw email signup:",JSON.parse(s));let e=new URLSearchParams(window.location.search),t=e.get("referral"),r=e.get("plan"),i=e.get("stripe_checkout_success");console.log("Referral queryparam:",t),console.log("Plan queryparam:",r);let n=!1,o=setTimeout(()=>{n||(document.body.style.visibility="visible")},4e3),a=new mt,{accessToken:l,refreshToken:h}=Xt(),c;try{c=await Zr()}catch(m){console.error("Platform detection failed:",m),c="Unknown"}let u=localStorage.getItem("email");if((t||r)&&u&&(!l||!h)){localStorage.removeItem("email"),localStorage.removeItem("conversion_sent"),sessionStorage.removeItem("referral_status"),window.location.href=`/get-started${window.location.search}`;return}i==="true"&&q("stripe_checkout_success",{email:localStorage.getItem("email"),device_type:c,source:"downloads_page",plan:localStorage.getItem("checkout_plan")}),localStorage.removeItem("checkout_plan");let d=document.querySelector("#hello-text"),f=document.querySelector("#logout-button");f.style.display="none";let y=es(),{dub_id:w,referral:_}=y;if(l&&h)try{a.setCookies(l,h);let m=a.checkAndSetSession(),M=new Promise((Be,z)=>setTimeout(()=>z(new Error("Session timeout")),3e3));await Promise.race([m,M]);let U=a.sessionData?.user.email,F=a.sessionData?.user.user_metadata.full_name||" ",[ie,ge]=Vt(F),_e=a.sessionData?.user.id,C={access_token:l,first_name:ie,last_name:ge,dub_click_id:w||void 0,referral:_||void 0};if(localStorage.setItem("email",U),!localStorage.getItem("conversion_sent")||t){let Be=await Je.signupUser(C);t&&(hi(Be),console.log("OAuth signup response:",Be),console.log("Showing referral UI"))}if(localStorage.getItem("conversion_sent")||await li(c,w,_,U),d.textContent=`Hi ${ie}!`,f.style.display="flex",r&&l){if(!["FLOW_PRO_MONTHLY","FLOW_PRO_YEARLY"].includes(r)){window.location.href=t?`/downloads?referral=${t}`:"/downloads";return}document.body.innerHTML='<div style="display: flex; padding-left: 20px; padding-right: 20px; text-align: center; justify-content: center; align-items: center; height: 100vh;"><h3>Checking your subscription...</h3></div>',document.body.style.visibility="visible";try{let z=await fetch("https://api.wisprflow.ai/api/v1/payment/subscription",{method:"GET",headers:{accept:"application/json",Authorization:l}});if(console.log("Subscription status response:",z),z.ok){let Jt=await z.json();if(console.log("User status:",Jt),Jt.is_subscribed){let rs=window.location.pathname;window.history.pushState({},"",rs),document.body.innerHTML=`
2
2
  <div style="display: flex; padding-left: 20px; padding-right: 20px; text-align: center; flex-direction: column; justify-content: center; align-items: center; height: 100vh;">
3
3
  <h3>\u2705 You already have an active subscription!</h3>
4
4
  <div class="spacer-medium"></div>
5
5
  <p class="text-size-medium">Redirecting you to downloads page in <span id="countdown">3</span> seconds...</p>
6
6
  </div>
7
- `;let rr=t?`/downloads?referral=${t}`:"/downloads";ci(3,rr)}else await Jt(s,l,t)}else await Jt(s,l,t)}catch(J){console.error("Status check error:",J),await Jt(s,l,t)}return}clearTimeout(o),document.body.style.visibility="visible",s||tr(c)}catch(m){n=!0,clearTimeout(o),window.location.href="/get-started",console.error("Error during session setup:",m)}else localStorage.getItem("email")?(d.textContent=`Hi ${localStorage.getItem("email")}!`,f.style.display="flex",clearTimeout(o),document.body.style.visibility="visible",s||tr(c)):(n=!0,clearTimeout(o),window.location.href="/get-started");document.querySelectorAll("[active-download]").forEach(function(m){if(!c.startsWith("mac")&&m.getAttribute("active-download")?.startsWith("mac")){m.onclick=M=>{if(M.preventDefault(),!localStorage.getItem("email"))return n=!0,clearTimeout(o),window.location.href="/get-started",!1;q("app_waitlist",{device_type:m.getAttribute("active-download")});let U={email:localStorage.getItem("email"),device_type:m.getAttribute("active-download")||"unknown"};return We.addToWaitlist(U),m.innerText="We emailed you the download link!",!1};return}m.onclick=()=>(q("app_download",{device_type:c,download_type:m.getAttribute("active-download"),auto_download:!0,source:"downloads-page",email:localStorage.getItem("email")||"not-found"}),!0)}),document.querySelectorAll("[download-link]").forEach(function(m){m.onclick=()=>(q("app_download",{device_type:c,source:"downloads-page-fallback",email:localStorage.getItem("email")||"not-found"}),!0)}),document.querySelectorAll("[waitlist]").forEach(function(m){m.onclick=M=>{if(M.preventDefault(),!localStorage.getItem("email"))return n=!0,clearTimeout(o),window.location.href="/get-started",!1;q("app_waitlist",{device_type:m.getAttribute("waitlist")});let U={email:localStorage.getItem("email"),device_type:m.getAttribute("waitlist")||"unknown"};return We.addToWaitlist(U),m.innerText="You're on the waitlist!",!1}});let b=document.querySelector("[download-email-form]");b&&b.addEventListener("submit",async m=>{m.preventDefault(),m.stopPropagation();let M=b.querySelector("[email-input]"),U=b.querySelector("[platform-name]"),F=b.querySelector('input[type="submit"]');if(!M||!U||!F){console.error("Form fields not found");return}let ie=M.value.trim(),ge=U.value.trim();if(!ie||!ge){console.error("Email or platform is empty");return}F.value="Please wait...",F.classList.add("pointer-events-none");try{let _e=await fetch("https://api.wisprflow.ai/api/v1/referral/download-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:ge,recipient_email:ie})});if(_e.ok){console.log("Email sent successfully");let C=document.querySelector("[success-div]");C&&(C.style.display="block"),b.style.display="none",F.classList.remove("pointer-events-none"),q("download_link_email_success",{platform_requested:ge,email:ie,source:"downloads_page_form",device_type:c})}else{console.error("API error:",_e.status);let C=document.querySelector("[error-div]");C&&(C.style.display="block"),F.classList.remove("pointer-events-none")}}catch(_e){console.error("Network error:",_e);let C=document.querySelector("[error-div]");C&&(C.style.display="block"),F.classList.remove("pointer-events-none")}}),f.addEventListener("click",async()=>{try{await a.signOut(),localStorage.removeItem("email"),localStorage.removeItem("conversion_sent"),sessionStorage.removeItem("referral_status"),n=!0,clearTimeout(o),window.location.href="/get-started"}catch(m){console.error("Error during sign-out:",m)}})});async function li(r,e,t,s){localStorage.getItem("conversion_sent")||(q("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:r,dub_id:e,referral:t,email:s}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown"}),localStorage.setItem("conversion_sent","true"))}async function Jt(r,e,t){if(r&&e)try{let i=await(await fetch(`https://api.wisprflow.ai/api/v1/payment/create-checkout-session?plan=${r}&custom_redirect=true`,{method:"POST",headers:{accept:"application/json",Authorization:e}})).json();console.log("Checkout details:",i);let{url:n}=i,o=t?`/downloads?referral=${t}`:"/downloads";window.history.pushState({},"",o),localStorage.setItem("checkout_plan",r),q("stripe_checkout_redirect",{plan:r,email:localStorage.getItem("email"),device_type:window.userPlatform,source:"downloads_page"}),window.open(n,"_blank"),document.body.innerHTML=`<div style="display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh;"><h3>Redirecting to checkout...</h3><div class="spacer-medium"></div><p class="text-size-medium">If you were not redirected automatically, <a href=${n} target="_blank">click here.</a></p></div>`}catch(s){console.error("Checkout error:",s)}}function ci(r,e){let t=r,s=setInterval(()=>{t--;let i=document.getElementById("countdown");i&&(i.textContent=t.toString()),t<=0&&(clearInterval(s),window.location.href=e)},1e3)}function hi(r){if(r.is_student===!0){document.querySelectorAll("[students-div]").forEach(t=>{t.style.display="block"});return}r.referral_status&&(r.referral_status.referral_code_valid?r.referral_status.was_previously_referred===!0?document.querySelectorAll("[already-referred-div]").forEach(t=>{t.style.display="block"}):r.referral_status.user_exists===!0?document.querySelectorAll("[existing-user-div]").forEach(t=>{t.style.display="block"}):document.querySelectorAll("[success-referral-div]").forEach(t=>{t.style.display="block"}):r.referral_status.message==="Invalid referral code."?document.querySelectorAll("[invalid-code-div]").forEach(t=>{t.style.display="block"}):r.referral_status.message==="Cannot refer yourself."&&document.querySelectorAll("[self-referral-div]").forEach(t=>{t.style.display="block"}))}function tr(r){let e=r==="mac_m1"||r==="mac_intel",t=r==="Windows",s=r==="iOS";if(e){document.querySelectorAll("[mac]").forEach(a=>{a.style.display="block"}),document.querySelectorAll("[header-content]").forEach(a=>{a.style.display="block"});let o=document.querySelector(`[active-download="${r}"]`);o&&o.href&&document.querySelectorAll("[download-link]").forEach(l=>{l.href=o.href}),setTimeout(()=>{let a=document.querySelector(`[active-download="${r}"]`);a&&(window.location.href=a.href,a.onclick&&a.onclick.call(a,new MouseEvent("click")))},500)}else if(t){document.querySelectorAll("[windows]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[header-content]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[windows-card]").forEach(l=>{l.style.display="none"});let a=document.querySelector('[active-download="windows"]');a&&a.href&&document.querySelectorAll("[download-link]").forEach(h=>{h.href=a.href}),setTimeout(()=>{let l=document.querySelector('[active-download="windows"]');l&&(window.location.href=l.href,l.onclick&&l.onclick.call(l,new MouseEvent("click")))},500)}else if(s){document.querySelectorAll("[header-content]").forEach(h=>{h.style.display="block"});let n=document.querySelector("[default-h1]");n&&(n.textContent="Download Flow for iOS");let o=document.querySelector("[default-para]");o&&(o.textContent="Download the iOS app and use voice dictation anywhere\u2014texts, emails, DMs, and more."),document.querySelectorAll("[ios-download]").forEach(h=>{h.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(h=>{h.style.display="none"})}else r==="mac_unknown"||r==="Unknown"?(document.querySelectorAll("[all-download-cards]").forEach(a=>{a.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(a=>{a.style.display="none"}),document.querySelectorAll("[other-platforms]").forEach(a=>{a.style.display="none"})):(document.querySelectorAll("[not-available]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[all-download-cards]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(l=>{l.style.display="none"}),document.querySelectorAll("[other-platforms]").forEach(l=>{l.style.display="none"}))}})();
7
+ `;let ss=t?`/downloads?referral=${t}`:"/downloads";ci(3,ss)}else await zt(r,l,t)}else await zt(r,l,t)}catch(z){console.error("Status check error:",z),await zt(r,l,t)}return}clearTimeout(o),document.body.style.visibility="visible",r||ts(c)}catch(m){n=!0,clearTimeout(o),window.location.href="/get-started",console.error("Error during session setup:",m)}else localStorage.getItem("email")?(d.textContent=`Hi ${localStorage.getItem("email")}!`,f.style.display="flex",clearTimeout(o),document.body.style.visibility="visible",r||ts(c)):(n=!0,clearTimeout(o),window.location.href="/get-started");document.querySelectorAll("[active-download]").forEach(function(m){if(!c.startsWith("mac")&&m.getAttribute("active-download")?.startsWith("mac")){m.onclick=M=>{if(M.preventDefault(),!localStorage.getItem("email"))return n=!0,clearTimeout(o),window.location.href="/get-started",!1;q("app_waitlist",{device_type:m.getAttribute("active-download")});let U={email:localStorage.getItem("email"),device_type:m.getAttribute("active-download")||"unknown"};return Je.addToWaitlist(U),m.innerText="We emailed you the download link!",!1};return}m.onclick=()=>(q("app_download",{device_type:c,download_type:m.getAttribute("active-download"),auto_download:!0,source:"downloads-page",email:localStorage.getItem("email")||"not-found"}),!0)}),document.querySelectorAll("[download-link]").forEach(function(m){m.onclick=()=>(q("app_download",{device_type:c,source:"downloads-page-fallback",email:localStorage.getItem("email")||"not-found"}),!0)}),document.querySelectorAll("[waitlist]").forEach(function(m){m.onclick=M=>{if(M.preventDefault(),!localStorage.getItem("email"))return n=!0,clearTimeout(o),window.location.href="/get-started",!1;q("app_waitlist",{device_type:m.getAttribute("waitlist")});let U={email:localStorage.getItem("email"),device_type:m.getAttribute("waitlist")||"unknown"};return Je.addToWaitlist(U),m.innerText="You're on the waitlist!",!1}});let b=document.querySelector("[download-email-form]");b&&b.addEventListener("submit",async m=>{m.preventDefault(),m.stopPropagation();let M=b.querySelector("[email-input]"),U=b.querySelector("[platform-name]"),F=b.querySelector('input[type="submit"]');if(!M||!U||!F){console.error("Form fields not found");return}let ie=M.value.trim(),ge=U.value.trim();if(!ie||!ge){console.error("Email or platform is empty");return}F.value="Please wait...",F.classList.add("pointer-events-none");try{let _e=await fetch("https://api.wisprflow.ai/api/v1/referral/download-link",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:ge,recipient_email:ie})});if(_e.ok){console.log("Email sent successfully");let C=document.querySelector("[success-div]");C&&(C.style.display="block"),b.style.display="none",F.classList.remove("pointer-events-none"),q("download_link_email_success",{platform_requested:ge,email:ie,source:"downloads_page_form",device_type:c})}else{console.error("API error:",_e.status);let C=document.querySelector("[error-div]");C&&(C.style.display="block"),F.classList.remove("pointer-events-none")}}catch(_e){console.error("Network error:",_e);let C=document.querySelector("[error-div]");C&&(C.style.display="block"),F.classList.remove("pointer-events-none")}}),f.addEventListener("click",async()=>{try{await a.signOut(),localStorage.removeItem("email"),localStorage.removeItem("conversion_sent"),sessionStorage.removeItem("referral_status"),n=!0,clearTimeout(o),window.location.href="/get-started"}catch(m){console.error("Error during sign-out:",m)}})});async function li(s,e,t,r){localStorage.getItem("conversion_sent")||(q("email_submission_success",{signin_provider:localStorage.getItem("signin_provider")||"unknown",device_type:s,dub_id:e,referral:t,email:r}),window.dataLayer=window.dataLayer||[],window.dataLayer.push({event:"email_submission_success",signup_method:localStorage.getItem("signin_provider")||"unknown"}),localStorage.setItem("conversion_sent","true"))}async function zt(s,e,t){if(s&&e)try{let i=await(await fetch(`https://api.wisprflow.ai/api/v1/payment/create-checkout-session?plan=${s}&custom_redirect=true`,{method:"POST",headers:{accept:"application/json",Authorization:e}})).json();console.log("Checkout details:",i);let{url:n}=i,o=t?`/downloads?referral=${t}`:"/downloads";window.history.pushState({},"",o),localStorage.setItem("checkout_plan",s),q("stripe_checkout_redirect",{plan:s,email:localStorage.getItem("email"),device_type:window.userPlatform,source:"downloads_page"}),window.open(n,"_blank"),document.body.innerHTML=`<div style="display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100vh;"><h3>Redirecting to checkout...</h3><div class="spacer-medium"></div><p class="text-size-medium">If you were not redirected automatically, <a href=${n} target="_blank">click here.</a></p></div>`}catch(r){console.error("Checkout error:",r)}}function ci(s,e){let t=s,r=setInterval(()=>{t--;let i=document.getElementById("countdown");i&&(i.textContent=t.toString()),t<=0&&(clearInterval(r),window.location.href=e)},1e3)}function hi(s){if(s.is_student===!0){document.querySelectorAll("[students-div]").forEach(t=>{t.style.display="block"});return}s.referral_status&&(s.referral_status.referral_code_valid?s.referral_status.was_previously_referred===!0?document.querySelectorAll("[already-referred-div]").forEach(t=>{t.style.display="block"}):s.referral_status.user_exists===!0?document.querySelectorAll("[existing-user-div]").forEach(t=>{t.style.display="block"}):document.querySelectorAll("[success-referral-div]").forEach(t=>{t.style.display="block"}):s.referral_status.message==="Invalid referral code."?document.querySelectorAll("[invalid-code-div]").forEach(t=>{t.style.display="block"}):s.referral_status.message==="Cannot refer yourself."&&document.querySelectorAll("[self-referral-div]").forEach(t=>{t.style.display="block"}))}function ts(s){let e=s==="mac_m1"||s==="mac_intel",t=s==="Windows",r=s==="iOS";if(e){document.querySelectorAll("[mac]").forEach(a=>{a.style.display="block"}),document.querySelectorAll("[header-content]").forEach(a=>{a.style.display="block"});let o=document.querySelector(`[active-download="${s}"]`);o&&o.href&&document.querySelectorAll("[download-link]").forEach(l=>{l.href=o.href}),setTimeout(()=>{let a=document.querySelector(`[active-download="${s}"]`);a&&(window.location.href=a.href,a.onclick&&a.onclick.call(a,new MouseEvent("click")))},500)}else if(t){document.querySelectorAll("[windows]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[header-content]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[windows-card]").forEach(l=>{l.style.display="none"});let a=document.querySelector('[active-download="windows"]');a&&a.href&&document.querySelectorAll("[download-link]").forEach(h=>{h.href=a.href}),setTimeout(()=>{let l=document.querySelector('[active-download="windows"]');l&&(window.location.href=l.href,l.onclick&&l.onclick.call(l,new MouseEvent("click")))},500)}else if(r){document.querySelectorAll("[header-content]").forEach(h=>{h.style.display="block"});let n=document.querySelector("[default-h1]");n&&(n.textContent="Download Flow for iOS");let o=document.querySelector("[default-para]");o&&(o.textContent="Download the iOS app and use voice dictation anywhere\u2014texts, emails, DMs, and more."),document.querySelectorAll("[ios-download]").forEach(h=>{h.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(h=>{h.style.display="none"})}else s==="mac_unknown"||s==="win_unknown"||s==="Unknown"?(document.querySelectorAll("[all-download-cards]").forEach(a=>{a.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(a=>{a.style.display="none"}),document.querySelectorAll("[other-platforms]").forEach(a=>{a.style.display="none"})):(document.querySelectorAll("[not-available]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[all-download-cards]").forEach(l=>{l.style.display="block"}),document.querySelectorAll("[ios-section]").forEach(l=>{l.style.display="none"}),document.querySelectorAll("[other-platforms]").forEach(l=>{l.style.display="none"}))}})();