@tanay-wispr/webflow-package 4.10.0 → 4.10.2

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 Zs=Object.create;var Ne=Object.defineProperty;var er=Object.getOwnPropertyDescriptor;var tr=Object.getOwnPropertyNames;var sr=Object.getPrototypeOf,rr=Object.prototype.hasOwnProperty;var ir=(r,e)=>()=>(r&&(e=r(r=0)),e);var C=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),nr=(r,e)=>{for(var t in e)Ne(r,t,{get:e[t],enumerable:!0})},Mt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of tr(e))!rr.call(r,i)&&i!==t&&Ne(r,i,{get:()=>e[i],enumerable:!(s=er(e,i))||s.enumerable});return r};var Bt=(r,e,t)=>(t=r!=null?Zs(sr(r)):{},Mt(e||!r||!r.__esModule?Ne(t,"default",{value:r,enumerable:!0}):t,r)),or=r=>Mt(Ne({},"__esModule",{value:!0}),r);var M={};nr(M,{Headers:()=>dt,Request:()=>lr,Response:()=>hr,default:()=>ut,fetch:()=>cr});var ar,Z,cr,ut,dt,lr,hr,D=ir(()=>{"use strict";ar=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")},Z=ar(),cr=Z.fetch,ut=Z.fetch.bind(Z),dt=Z.Headers,lr=Z.Request,hr=Z.Response});var Kt=C(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});var ft=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};pt.default=ft});var mt=C(fe=>{"use strict";var Vt=fe&&fe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(fe,"__esModule",{value:!0});var dr=Vt((D(),or(M))),fr=Vt(Kt()),gt=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=dr.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let h=null,l=null,u=null,d=n.status,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let m=await n.text();m===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=m:l=JSON.parse(m))}let v=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),y=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");v&&y&&y.length>1&&(u=parseInt(y[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(h={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,u=null,d=406,f="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let v=await n.text();try{h=JSON.parse(v),Array.isArray(h)&&n.status===404&&(l=[],h=null,d=200,f="OK")}catch{n.status===404&&v===""?(d=204,f="No Content"):h={message:v}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new fr.default(h)}return{error:h,data:l,count:u,status:d,statusText:f}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};fe.default=gt});var yt=C(pe=>{"use strict";var pr=pe&&pe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(pe,"__esModule",{value:!0});var gr=pr(mt()),_t=class extends gr.default{select(e){let t=!1,s=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:i=s}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};pe.default=_t});var Je=C(ge=>{"use strict";var mr=ge&&ge.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ge,"__esModule",{value:!0});var _r=mr(yt()),vt=class extends _r.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}};ge.default=vt});var bt=C(_e=>{"use strict";var yr=_e&&_e.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(_e,"__esModule",{value:!0});var me=yr(Je()),wt=class{constructor(e,{headers:t={},schema:s,fetch:i}){this.url=e,this.headers=t,this.schema=s,this.fetch=i}select(e,{head:t=!1,count:s}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new me.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new me.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((h,l)=>h.concat(Object.keys(l)),[]);if(c.length>0){let h=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",h.join(","))}}return new me.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let s="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new me.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t="DELETE",s=[];return e&&s.push(`count=${e}`),this.headers.Prefer&&s.unshift(this.headers.Prefer),this.headers.Prefer=s.join(","),new me.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};_e.default=wt});var Yt=C(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.version=void 0;We.version="0.0.0-automated"});var Qt=C(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.DEFAULT_HEADERS=void 0;var vr=Yt();Ge.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${vr.version}`}});var Zt=C(ye=>{"use strict";var Xt=ye&&ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ye,"__esModule",{value:!0});var wr=Xt(bt()),br=Xt(Je()),kr=Qt(),kt=class r{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},kr.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new wr.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||i?(o=s?"HEAD":"GET",Object.entries(t).filter(([l,u])=>u!==void 0).map(([l,u])=>[l,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([l,u])=>{a.searchParams.append(l,u)})):(o="POST",c=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new br.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};ye.default=kt});var ns=C(E=>{"use strict";var ve=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 es=ve(Zt());E.PostgrestClient=es.default;var ts=ve(bt());E.PostgrestQueryBuilder=ts.default;var ss=ve(Je());E.PostgrestFilterBuilder=ss.default;var rs=ve(yt());E.PostgrestTransformBuilder=rs.default;var is=ve(mt());E.PostgrestBuilder=is.default;E.default={PostgrestClient:es.default,PostgrestQueryBuilder:ts.default,PostgrestFilterBuilder:ss.default,PostgrestTransformBuilder:rs.default,PostgrestBuilder:is.default}});var ps=C((Vi,fs)=>{"use strict";fs.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var qe="https://api.wisprflow.ai",ht=class{static async signupUser(e){try{let t=`${qe}/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(`${qe}/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(`${qe}/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(`${qe}/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 Ht(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}var Fe=ht;var zt=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var Jt=()=>{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 Wt=()=>{let{access_token:r,refresh_token:e}=Jt(),t=r,s=e;if(!t||!s){let i=zt();t=i.access_token,s=i.refresh_token}return{accessToken:t,refreshToken:s}};var Gt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(D(),M)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var ue=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},Me=class extends ue{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Be=class extends ue{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},He=class extends ue{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},ze;(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"})(ze||(ze={}));var ur=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},de=class{constructor(e,{headers:t={},customFetch:s,region:i=ze.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Gt(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return ur(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let h;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData<"u"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:h}).catch(_=>{throw new Me(_)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new Be(l);if(!l.ok)throw new He(l);let d=((s=l.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield l.json():d==="application/octet-stream"?f=yield l.blob():d==="text/event-stream"?f=l:d==="multipart/form-data"?f=yield l.formData():f=yield l.text(),{data:f,error:null}}catch(i){return{data:null,error:i}}})}};var os=Bt(ns(),1),{PostgrestClient:as,PostgrestQueryBuilder:Pi,PostgrestFilterBuilder:Ci,PostgrestTransformBuilder:ji,PostgrestBuilder:Ii}=os.default;var cs="2.10.2";var ls={"X-Client-Info":`realtime-js/${cs}`},hs="1.0.0",Ve=1e4,us=1e3,B;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(B||(B={}));var x;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(x||(x={}));var O;(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"})(O||(O={}));var Ke;(function(r){r.websocket="websocket"})(Ke||(Ke={}));var N;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(N||(N={}));var we=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+i));o=o+i;let c=s.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:h}}};var H=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var w;(function(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"})(w||(w={}));var Et=(r,e,t={})=>{var s;let i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Sr(o,r,e,i),n),{})},Sr=(r,e,t,s)=>{let i=e.find(a=>a.name===r),n=i?.type,o=t[r];return n&&!s.includes(n)?ds(n,o):St(o)},ds=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return Ar(e,t)}switch(r){case w.bool:return Er(e);case w.float4:case w.float8:case w.int2:case w.int4:case w.int8:case w.numeric:case w.oid:return Tr(e);case w.json:case w.jsonb:return xr(e);case w.timestamp:return Or(e);case w.abstime:case w.date:case w.daterange:case w.int4range:case w.int8range:case w.money:case w.reltime:case w.text:case w.time:case w.timestamptz:case w.timetz:case w.tsrange:case w.tstzrange:return St(e);default:return St(e)}},St=r=>r,Er=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},Tr=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},xr=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},Ar=(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=>ds(e,a))}return r},Or=r=>typeof r=="string"?r.replace(" ","T"):r,Ye=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var z=class{constructor(e,t,s={},i=Ve){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 Tt;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(Tt||(Tt={}));var ee=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=r.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(h,l)=>{o[h]||(c[h]=l)}),this.map(o,(h,l)=>{let u=n[h];if(u){let d=l.map(y=>y.presence_ref),f=u.map(y=>y.presence_ref),_=l.filter(y=>f.indexOf(y.presence_ref)<0),v=u.filter(y=>d.indexOf(y.presence_ref)<0);_.length>0&&(a[h]=_),v.length>0&&(c[h]=v)}else a[h]=l}),this.syncDiff(n,{joins:a,leaves:c},s,i)}static syncDiff(e,t,s,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var h;let l=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(c),l.length>0){let u=e[a].map(f=>f.presence_ref),d=l.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}s(a,l,c)}),this.map(o,(a,c)=>{let h=e[a];if(!h)return;let l=c.map(u=>u.presence_ref);h=h.filter(u=>l.indexOf(u.presence_ref)<0),e[a]=h,i(a,h,c),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let i=e[s];return"metas"in i?t[s]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var xt;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(xt||(xt={}));var At;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(At||(At={}));var Ot;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Ot||(Ot={}));var te=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=x.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new z(this,O.join,this.params,this.timeout),this.rejoinTimer=new H(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=x.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=x.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this._on(O.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new ee(this),this.broadcastEndpointURL=Ye(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},h={broadcast:n,presence:o,postgres_changes:(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:h},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,f=(u=d?.length)!==null&&u!==void 0?u:0,_=[];for(let v=0;v<f;v++){let y=d[v],{filter:{event:m,schema:S,table:k,filter:A}}=y,T=l&&l[v];if(T&&T.event===m&&T.schema===S&&T.table===k&&T.filter===A)_.push(Object.assign(Object.assign({},y),{id:T.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),h.receive("ok",()=>n("ok")),h.receive("error",()=>n("error")),h.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=x.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(O.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let i=new z(this,O.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 z(this,e,t,s);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:h,join:l}=O;if(s&&[a,c,h,l].indexOf(o)>=0&&s!==this._joinRef())return;let d=this._onMessage(o,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(f=>{var _,v,y;return((_=f.filter)===null||_===void 0?void 0:_.event)==="*"||((y=(v=f.filter)===null||v===void 0?void 0:v.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===o}).map(f=>f.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var _,v,y,m,S,k;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let A=f.id,T=(_=f.filter)===null||_===void 0?void 0:_.event;return A&&((v=t.ids)===null||v===void 0?void 0:v.includes(A))&&(T==="*"||T?.toLocaleLowerCase()===((y=t.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))}else{let A=(S=(m=f?.filter)===null||m===void 0?void 0:m.event)===null||S===void 0?void 0:S.toLocaleLowerCase();return A==="*"||A===((k=t?.event)===null||k===void 0?void 0:k.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let _=d.data,{schema:v,table:y,commit_timestamp:m,type:S,errors:k}=_;d=Object.assign(Object.assign({},{schema:v,table:y,commit_timestamp:m,eventType:S,new:{},old:{},errors:k}),this._getPayloadRecords(_))}f.callback(d,s)})}_isClosed(){return this.state===x.closed}_isJoined(){return this.state===x.joined}_isJoining(){return this.state===x.joining}_isLeaving(){return this.state===x.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,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(O.close,{},e)}_onError(e){this._on(O.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=x.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Et(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Et(e.columns,e.old_record)),t}};var Pr=()=>{},Cr=typeof WebSocket<"u",se=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=ls,this.params={},this.timeout=Ve,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Pr,this.conn=null,this.sendBuffer=[],this.serializer=new we,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(D(),M)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Ke.websocket}`,this.httpEndpoint=Ye(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let 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 H(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(Cr){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Rt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Bt(ps())).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 B.connecting:return N.Connecting;case B.open:return N.Open;case B.closing:return N.Closing;default:return N.Closed}}isConnected(){return this.connectionState()===N.Open}channel(e,t={config:{}}){let s=new te(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${s} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(O.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(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:hs}))}_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(O.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(us,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Rt=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=B.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var re=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function b(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Qe=class extends re{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},be=class extends re{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var jr=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Xe=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(D(),M)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},gs=()=>jr(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(D(),M))).Response:Response});var ie=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Pt=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Ir=(r,e)=>ie(void 0,void 0,void 0,function*(){let t=yield gs();r instanceof t?r.json().then(s=>{e(new Qe(Pt(s),r.status||500))}).catch(s=>{e(new be(Pt(s),s))}):e(new be(Pt(r),r))}),$r=(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 Ze(r,e,t,s,i,n){return ie(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,$r(e,s,i,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>Ir(c,a))})})}function ke(r,e,t,s){return ie(this,void 0,void 0,function*(){return Ze(r,"GET",e,t,s)})}function j(r,e,t,s,i){return ie(this,void 0,void 0,function*(){return Ze(r,"POST",e,s,i,t)})}function ms(r,e,t,s,i){return ie(this,void 0,void 0,function*(){return Ze(r,"PUT",e,s,i,t)})}function et(r,e,t,s,i){return ie(this,void 0,void 0,function*(){return Ze(r,"DELETE",e,s,i,t)})}var R=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Lr={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},_s={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Se=class{constructor(e,t={},s,i){this.url=e,this.headers=t,this.bucketId=s,this.fetch=Xe(i)}uploadOrUpdate(e,t,s,i){return R(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},_s),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),h=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield l.json();return l.ok?{data:{path:c,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(b(n))return{data:null,error:n};throw n}})}upload(e,t,s){return R(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return R(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,h=Object.assign({upsert:_s.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",h.cacheControl)):(c=s,l["cache-control"]=`max-age=${h.cacheControl}`,l["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(b(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return R(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield j(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new re("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(b(s))return{data:null,error:s};throw s}})}update(e,t,s){return R(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return R(this,void 0,void 0,function*(){try{return{data:yield j(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}copy(e,t,s){return R(this,void 0,void 0,function*(){try{return{data:{path:(yield j(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return R(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield j(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return R(this,void 0,void 0,function*(){try{let i=yield j(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(b(i))return{data:null,error:i};throw i}})}download(e,t){return R(this,void 0,void 0,function*(){let i=typeof t?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(t?.transform||{}),o=n?`?${n}`:"";try{let a=this._getFinalPath(e);return{data:yield(yield ke(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(b(a))return{data:null,error:a};throw a}})}getPublicUrl(e,t){let s=this._getFinalPath(e),i=[],n=t?.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);let a=typeof t?.transform<"u"?"render/image":"object",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let h=i.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${h}`)}}}remove(e){return R(this,void 0,void 0,function*(){try{return{data:yield et(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}list(e,t,s){return R(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Lr),t),{prefix:e||""});return{data:yield j(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if(b(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 ys="2.6.0";var vs={"X-Client-Info":`storage-js/${ys}`};var ne=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Ee=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},vs),t),this.fetch=Xe(s)}listBuckets(){return ne(this,void 0,void 0,function*(){try{return{data:yield ke(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(b(e))return{data:null,error:e};throw e}})}getBucket(e){return ne(this,void 0,void 0,function*(){try{return{data:yield ke(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return ne(this,void 0,void 0,function*(){try{return{data:yield j(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(b(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return ne(this,void 0,void 0,function*(){try{return{data:yield ms(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(b(s))return{data:null,error:s};throw s}})}emptyBucket(e){return ne(this,void 0,void 0,function*(){try{return{data:yield j(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}deleteBucket(e){return ne(this,void 0,void 0,function*(){try{return{data:yield et(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}};var Te=class extends Ee{constructor(e,t={},s){super(e,t,s)}from(e){return new Se(this.url,this.headers,e,this.fetch)}};var ws="2.44.4";var xe="";typeof Deno<"u"?xe="deno":typeof document<"u"?xe="web":typeof navigator<"u"&&navigator.product==="ReactNative"?xe="react-native":xe="node";var Ur={"X-Client-Info":`supabase-js-${xe}/${ws}`},bs={headers:Ur},ks={schema:"public"},Ss={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Es={};D();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(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Nr=r=>{let e;return r?e=r:typeof fetch>"u"?e=ut:e=fetch,(...t)=>e(...t)},qr=()=>typeof Headers>"u"?dt:Headers,Ts=(r,e,t)=>{let s=Nr(t),i=qr();return(n,o)=>Dr(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,h=new i(o?.headers);return h.has("apikey")||h.set("apikey",r),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:h}))})};function xs(r){return r.replace(/\/$/,"")}function As(r,e){let{db:t,auth:s,realtime:i,global:n}=r,{db:o,auth:a,realtime:c,global:h}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},h),n)}}var tt="2.64.4";var Os="http://localhost:9999",Rs="supabase.auth.token";var Ps={"X-Client-Info":`gotrue-js/${tt}`},Ct=10;var Ae="X-Supabase-Api-Version",jt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Cs(r){return Math.round(Date.now()/1e3)+r}function js(){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 P=()=>typeof document<"u",J={tested:!1,writable:!1},q=()=>{if(!P())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(J.tested)return J.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),J.tested=!0,J.writable=!0}catch{J.tested=!0,J.writable=!1}return J.writable};function st(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((s,i)=>{e[i]=s}),e}var rt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(D(),M)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Is=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",It=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},Re=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},it=async(r,e)=>{await r.removeItem(e)};function Fr(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,i,n,o,a,c,h,l=0;for(r=r.replace("-","+").replace("_","/");l<r.length;)o=e.indexOf(r.charAt(l++)),a=e.indexOf(r.charAt(l++)),c=e.indexOf(r.charAt(l++)),h=e.indexOf(r.charAt(l++)),s=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|h,t=t+String.fromCharCode(s),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Oe=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Oe.promiseConstructor=Promise;function $t(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(Fr(s))}async function $s(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function Ls(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 Mr(r){return("0"+r.toString(16)).substr(-2)}function Br(){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,Mr).join("")}async function Hr(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 zr(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Jr(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 Hr(r);return zr(t)}async function W(r,e,t=!1){let s=Br(),i=s;t&&(i+="/PASSWORD_RECOVERY"),await It(r,`${e}-code-verifier`,i);let n=await Jr(s);return[n,s===n?"plain":"s256"]}var Wr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Us(r){let e=r.headers.get(Ae);if(!e||!e.match(Wr))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Pe=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 nt=class extends Pe{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function Ds(r){return p(r)&&r.name==="AuthApiError"}var oe=class extends Pe{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},L=class extends Pe{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}},I=class extends L{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},ae=class extends L{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},G=class extends L{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},K=class extends L{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},Ce=class extends L{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},ce=class extends L{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function ot(r){return p(r)&&r.name==="AuthRetryableFetchError"}var je=class extends L{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var Gr=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},V=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Kr=[502,503,504];async function Ns(r){var e;if(!Is(r))throw new ce(V(r),0);if(Kr.includes(r.status))throw new ce(V(r),r.status);let t;try{t=await r.json()}catch(n){throw new oe(V(n),n)}let s,i=Us(r);if(i&&i.getTime()>=jt["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 je(V(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 je(V(t),r.status,t.weak_password.reasons);throw new nt(V(t),r.status||500,s)}var Vr=(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[Ae]||(n[Ae]=jt["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(i=s?.query)!==null&&i!==void 0?i:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Yr(r,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function Yr(r,e,t,s,i,n){let o=Vr(e,s,i,n),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new ce(V(c),0)}if(a.ok||await Ns(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await Ns(c)}}function U(r){var e;let t=null;Qr(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=Cs(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function Lt(r){let e=U(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=r.weak_password),e}function $(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function qs(r){return{data:r,error:null}}function Fs(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=Gr(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function Ms(r){return r}function Qr(r){return r.access_token&&r.refresh_token&&r.expires_in}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},Y=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=rt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await g(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(p(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await g(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:$})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=Xr(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:Fs,redirectTo:t?.redirectTo})}catch(t){if(p(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await g(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:$})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,i,n,o,a,c;try{let h={nextPage:null,lastPage:0,total:0},l=await g(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:Ms});if(l.error)throw l.error;let u=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(_=>{let v=parseInt(_.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(_.split(";")[1].split("=")[1]);h[`${y}Page`]=v}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(p(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:$})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:$})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:$})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(p(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}};var Bs={getItem:r=>q()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{q()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{q()&&globalThis.localStorage.removeItem(r)}};function Ut(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function Hs(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var Q={debug:!!(globalThis&&q()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Ie=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},at=class extends Ie{};async function Dt(r,e,t){Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Q.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new at(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Q.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}Hs();var Zr={url:Os,storageKey:Rs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ps,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},$e=30*1e3,zs=3;async function Js(r,e,t){return await t()}var X=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&&P()&&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({},Zr),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Y({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=rt(i.fetch),this.lock=i.lock||Js,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:P()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Dt:this.lock=Js,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:q()?this.storage=Bs:(this.memoryStorage={},this.storage=Ut(this.memoryStorage)):(this.memoryStorage={},this.storage=Ut(this.memoryStorage)),P()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${tt}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=P()?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 oe("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{let n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:U}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,i;try{let n;if("email"in e){let{email:l,password:u,options:d}=e,f=null,_=null;this.flowType==="pkce"&&([f,_]=await W(this.storage,this.storageKey)),n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:_},xform:U})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:u,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(i=d?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:U})}else throw new G("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Lt})}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:Lt})}else throw new G("You must provide either an email or phone number and a password");let{data:s,error:i}=t;return i?{data:{user:null,session:null},error:i}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new ae}:(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 Re(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(t??"").split("/"),{data:n,error:o}=await g(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:U});return await it(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 ae}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:i,access_token:n,nonce:o}=e,a=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:U}),{data:c,error:h}=a;return h?{data:{user:null,session:null},error:h}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new ae}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,i,n,o;try{if("email"in e){let{email:a,options:c}=e,h=null,l=null;this.flowType==="pkce"&&([h,l]=await W(this.storage,this.storageKey));let{error:u}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:h,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:c}=e,{data:h,error:l}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:l}}throw new G("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:U});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(p(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,s,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await W(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:qs})}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 I;let{error:i}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(p(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:n}=e,{error:o}=await g(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:i,options:n}=e,{data:o,error:a}=await g(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new G("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Re(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,h,l)=>(!o&&h==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,h,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:$}):await this._useSession(async t=>{var s,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new I}:await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:$})})}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 I;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await W(this.storage,this.storageKey));let{data:h,error:l}=await g(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:$});if(l)throw l;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return $t(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new I;let t=Date.now()/1e3,s=t,i=!0,n=null,o=$t(e.access_token);if(o.exp&&(s=o.exp,i=s<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(p(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new I;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!P())throw new K("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new K("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new Ce("Not a valid PKCE flow url.");let t=st(window.location.href);if(e){if(!t.code)throw new Ce("No code detected.");let{data:S,error:k}=await this._exchangeCodeForSession(t.code);if(k)throw k;let A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:S.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new K(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:h}=t;if(!n||!a||!o||!h)throw new K("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;c&&(d=parseInt(c));let f=d-l;f*1e3<=$e&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let _=d-u;l-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,d,l):l-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",_,d,l);let{data:v,error:y}=await this._getUser(n);if(y)throw y;let m={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:m,redirectType:t.type},error:null}}catch(t){if(p(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=st(window.location.href);return!!(P()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=st(window.location.href),t=await Re(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&&!(Ds(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await it(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=js(),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 W(this.storage,this.storageKey,!0));try{return await g(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(p(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:i}=await this._useSession(async n=>{var o,a,c,h,l;let{data:u,error:d}=n;if(d)throw d;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await g(this.fetch,"GET",f,{headers:this.headers,jwt:(l=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return P()&&!(!((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 Ls(async i=>(i>0&&await $s(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await g(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:U})),(i,n)=>{let o=200*Math.pow(2,i);return n&&ot(n)&&Date.now()+o-s<$e})}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),P()&&!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 Re(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+Ct;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Ct}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),ot(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new I;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Oe;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new I;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),p(n)){let o={session:null,error:n};return ot(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,s=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await It(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await it(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&P()&&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(),$e);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)/$e);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${$e}ms, refresh threshold is ${zs} ticks`),i<=zs&&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 Ie)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!P()||!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 W(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);i.push(n.toString())}return s?.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await g(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],i=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};X.nextInstanceID=0;var ei=X,Nt=ei;var ct=class extends Nt{constructor(e){super(e)}};var ti=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Le=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=xs(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:ks,realtime:Es,auth:Object.assign(Object.assign({},Ss),{storageKey:c}),global:bs},l=As(s??{},h);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=Ts(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new as(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new de(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Te(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return ti(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,storageKey:n,flowType:o,debug:a},c,h){var l;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ct({url:this.authUrl,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new se(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?(this.realtime.setAuth(s??null),this.changedAccessToken=s):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var Ws=(r,e,t)=>new Le(r,e,t);var le={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var lt=class{constructor(){this.sessionData=null;this.supabase=Ws(le.supaBaseUrl,le.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||le.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||le.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:le.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 si(){try{let r=document.createElement("canvas"),e=r.getContext("webgl")||r.getContext("experimental-webgl");if(e){let t=e.getExtension("WEBGL_debug_renderer_info"),s=e.getParameter(t.UNMASKED_RENDERER_WEBGL);return console.log(`WebGL Renderer: ${s}`),s.includes("Apple")}}catch{return!1}}var Gs=async()=>{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")?si()?"mac_m1":"mac_intel":r.includes("Windows")?"Windows":r.includes("Linux")?"Linux":/iPhone|iPad|iPod/.test(r)?"iOS":/Android/.test(r)?"Android":"Unknown"}};var Ks=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var Ue=(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");console.log("Referral queryparam:",t),console.log("Plan queryparam:",s);let i=!1,n=setTimeout(()=>{i||(document.body.style.visibility="visible")},4e3),o=new lt,{accessToken:a,refreshToken:c}=Wt(),h=await Gs(),l=document.querySelector("#hello-text"),u=document.querySelector("#logout-button");u.style.display="none";let d=Ks(),{dub_id:f,referral:_}=d;if(a&&c)try{o.setCookies(a,c);let m=o.checkAndSetSession(),S=new Promise((De,F)=>setTimeout(()=>F(new Error("Session timeout")),3e3));await Promise.race([m,S]);let k=o.sessionData?.user.email,A=o.sessionData?.user.user_metadata.full_name||" ",[T,Vs]=Ht(A),oi=o.sessionData?.user.id,Ys={access_token:a,first_name:T,last_name:Vs,dub_click_id:f||void 0,referral:_||void 0};if(localStorage.setItem("email",k),!localStorage.getItem("conversion_sent")||t){let De=await Fe.signupUser(Ys);console.log("OAuth signup response:",De),t&&(ni(De),console.log("Showing referral UI"))}if(localStorage.getItem("conversion_sent")||await ri(h,f,_,k),l.textContent=`Hi ${T}!`,u.style.display="flex",s&&a){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; justify-content: center; align-items: center; height: 100vh;"><h3>Checking your subscription...</h3></div>',document.body.style.visibility="visible";try{let F=await fetch("https://api.wisprflow.ai/api/v1/payment/subscription",{method:"GET",headers:{accept:"application/json",Authorization:a}});if(console.log("Subscription status response:",F),F.ok){let Ft=await F.json();if(console.log("User status:",Ft),Ft.is_subscribed){let Qs=window.location.pathname;window.history.pushState({},"",Qs),document.body.innerHTML=`
1
+ "use strict";(()=>{var er=Object.create;var Ne=Object.defineProperty;var tr=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var rr=Object.getPrototypeOf,ir=Object.prototype.hasOwnProperty;var nr=(r,e)=>()=>(r&&(e=r(r=0)),e);var C=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),or=(r,e)=>{for(var t in e)Ne(r,t,{get:e[t],enumerable:!0})},Bt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of sr(e))!ir.call(r,i)&&i!==t&&Ne(r,i,{get:()=>e[i],enumerable:!(s=tr(e,i))||s.enumerable});return r};var Ht=(r,e,t)=>(t=r!=null?er(rr(r)):{},Bt(e||!r||!r.__esModule?Ne(t,"default",{value:r,enumerable:!0}):t,r)),ar=r=>Bt(Ne({},"__esModule",{value:!0}),r);var M={};or(M,{Headers:()=>dt,Request:()=>hr,Response:()=>ur,default:()=>ut,fetch:()=>lr});var cr,ee,lr,ut,dt,hr,ur,D=nr(()=>{"use strict";cr=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},ee=cr(),lr=ee.fetch,ut=ee.fetch.bind(ee),dt=ee.Headers,hr=ee.Request,ur=ee.Response});var Vt=C(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});var ft=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};pt.default=ft});var mt=C(pe=>{"use strict";var Yt=pe&&pe.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(pe,"__esModule",{value:!0});var fr=Yt((D(),ar(M))),pr=Yt(Vt()),gt=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=fr.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");let s=this.fetch,i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,c;let h=null,l=null,u=null,d=n.status,f=n.statusText;if(n.ok){if(this.method!=="HEAD"){let E=await n.text();E===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?l=E:l=JSON.parse(E))}let _=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),y=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");_&&y&&y.length>1&&(u=parseInt(y[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(l)&&(l.length>1?(h={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},l=null,u=null,d=406,f="Not Acceptable"):l.length===1?l=l[0]:l=null)}else{let _=await n.text();try{h=JSON.parse(_),Array.isArray(h)&&n.status===404&&(l=[],h=null,d=200,f="OK")}catch{n.status===404&&_===""?(d=204,f="No Content"):h={message:_}}if(h&&this.isMaybeSingle&&(!((c=h?.details)===null||c===void 0)&&c.includes("0 rows"))&&(h=null,d=200,f="OK"),h&&this.shouldThrowOnError)throw new pr.default(h)}return{error:h,data:l,count:u,status:d,statusText:f}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,c;return{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:`${(a=n?.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(c=n?.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};pe.default=gt});var yt=C(ge=>{"use strict";var gr=ge&&ge.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ge,"__esModule",{value:!0});var mr=gr(mt()),_t=class extends mr.default{select(e){let t=!1,s=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:i,referencedTable:n=i}={}){let o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){let i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:i=s}={}){let n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;let c=[e?"analyze":null,t?"verbose":null,s?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; options=${c};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};ge.default=_t});var Je=C(me=>{"use strict";var _r=me&&me.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(me,"__esModule",{value:!0});var yr=_r(yt()),vt=class extends yr.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let s=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${s})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");let o=s===void 0?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,s])=>{this.url.searchParams.append(t,`eq.${s}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){let i=s?`${s}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}};me.default=vt});var bt=C(ye=>{"use strict";var vr=ye&&ye.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ye,"__esModule",{value:!0});var _e=vr(Je()),wt=class{constructor(e,{headers:t={},schema:s,fetch:i}){this.url=e,this.headers=t,this.schema=s,this.fetch=i}select(e,{head:t=!1,count:s}={}){let i=t?"HEAD":"GET",n=!1,o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),s&&(this.headers.Prefer=`count=${s}`),new _e.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){let i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),s||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let o=e.reduce((a,c)=>a.concat(Object.keys(c)),[]);if(o.length>0){let a=[...new Set(o)].map(c=>`"${c}"`);this.url.searchParams.set("columns",a.join(","))}}return new _e.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:i,defaultToNull:n=!0}={}){let o="POST",a=[`resolution=${s?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let c=e.reduce((h,l)=>h.concat(Object.keys(l)),[]);if(c.length>0){let h=[...new Set(c)].map(l=>`"${l}"`);this.url.searchParams.set("columns",h.join(","))}}return new _e.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 _e.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 _e.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};ye.default=wt});var Qt=C(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.version=void 0;We.version="0.0.0-automated"});var Xt=C(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.DEFAULT_HEADERS=void 0;var wr=Qt();Ge.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${wr.version}`}});var es=C(ve=>{"use strict";var Zt=ve&&ve.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ve,"__esModule",{value:!0});var br=Zt(bt()),kr=Zt(Je()),Sr=Xt(),kt=class r{constructor(e,{headers:t={},schema:s,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},Sr.DEFAULT_HEADERS),t),this.schemaName=s,this.fetch=i}from(e){let t=new URL(`${this.url}/${e}`);return new br.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:i=!1,count:n}={}){let o,a=new URL(`${this.url}/rpc/${e}`),c;s||i?(o=s?"HEAD":"GET",Object.entries(t).filter(([l,u])=>u!==void 0).map(([l,u])=>[l,Array.isArray(u)?`{${u.join(",")}}`:`${u}`]).forEach(([l,u])=>{a.searchParams.append(l,u)})):(o="POST",c=t);let h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new kr.default({method:o,url:a,headers:h,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};ve.default=kt});var os=C(T=>{"use strict";var we=T&&T.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(T,"__esModule",{value:!0});T.PostgrestBuilder=T.PostgrestTransformBuilder=T.PostgrestFilterBuilder=T.PostgrestQueryBuilder=T.PostgrestClient=void 0;var ts=we(es());T.PostgrestClient=ts.default;var ss=we(bt());T.PostgrestQueryBuilder=ss.default;var rs=we(Je());T.PostgrestFilterBuilder=rs.default;var is=we(yt());T.PostgrestTransformBuilder=is.default;var ns=we(mt());T.PostgrestBuilder=ns.default;T.default={PostgrestClient:ts.default,PostgrestQueryBuilder:ss.default,PostgrestFilterBuilder:rs.default,PostgrestTransformBuilder:is.default,PostgrestBuilder:ns.default}});var gs=C((Yi,ps)=>{"use strict";ps.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var qe="https://api.wisprflow.ai",ht=class{static async signupUser(e){try{let t=`${qe}/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(`${qe}/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(`${qe}/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(`${qe}/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 zt(r){let[e,...t]=r.split(" "),s=t.join(" ");return[e,s]}var Fe=ht;var Jt=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var Wt=()=>{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 Gt=()=>{let{access_token:r,refresh_token:e}=Wt(),t=r,s=e;if(!t||!s){let i=Jt();t=i.access_token,s=i.refresh_token}return{accessToken:t,refreshToken:s}};var Kt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(D(),M)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};var de=class extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}},Me=class extends de{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Be=class extends de{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},He=class extends de{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},ze;(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"})(ze||(ze={}));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(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},fe=class{constructor(e,{headers:t={},customFetch:s,region:i=ze.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=Kt(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return dr(this,void 0,void 0,function*(){try{let{headers:i,method:n,body:o}=t,a={},{region:c}=t;c||(c=this.region),c&&c!=="any"&&(a["x-region"]=c);let h;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData<"u"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:h}).catch(m=>{throw new Me(m)}),u=l.headers.get("x-relay-error");if(u&&u==="true")throw new Be(l);if(!l.ok)throw new He(l);let d=((s=l.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield l.json():d==="application/octet-stream"?f=yield l.blob():d==="text/event-stream"?f=l:d==="multipart/form-data"?f=yield l.formData():f=yield l.text(),{data:f,error:null}}catch(i){return{data:null,error:i}}})}};var as=Ht(os(),1),{PostgrestClient:cs,PostgrestQueryBuilder:Ci,PostgrestFilterBuilder:ji,PostgrestTransformBuilder:Ii,PostgrestBuilder:$i}=as.default;var ls="2.10.2";var hs={"X-Client-Info":`realtime-js/${ls}`},us="1.0.0",Ve=1e4,ds=1e3,B;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(B||(B={}));var x;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(x||(x={}));var O;(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"})(O||(O={}));var Ke;(function(r){r.websocket="websocket"})(Ke||(Ke={}));var N;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(N||(N={}));var be=class{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){let t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){let i=t.getUint8(1),n=t.getUint8(2),o=this.HEADER_LENGTH+2,a=s.decode(e.slice(o,o+i));o=o+i;let c=s.decode(e.slice(o,o+n));o=o+n;let h=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:c,payload:h}}};var H=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};var w;(function(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"})(w||(w={}));var Et=(r,e,t={})=>{var s;let i=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((n,o)=>(n[o]=Er(o,r,e,i),n),{})},Er=(r,e,t,s)=>{let i=e.find(a=>a.name===r),n=i?.type,o=t[r];return n&&!s.includes(n)?fs(n,o):St(o)},fs=(r,e)=>{if(r.charAt(0)==="_"){let t=r.slice(1,r.length);return Or(e,t)}switch(r){case w.bool:return Tr(e);case w.float4:case w.float8:case w.int2:case w.int4:case w.int8:case w.numeric:case w.oid:return xr(e);case w.json:case w.jsonb:return Ar(e);case w.timestamp:return Rr(e);case w.abstime:case w.date:case w.daterange:case w.int4range:case w.int8range:case w.money:case w.reltime:case w.text:case w.time:case w.timestamptz:case w.timetz:case w.tsrange:case w.tstzrange:return St(e);default:return St(e)}},St=r=>r,Tr=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},xr=r=>{if(typeof r=="string"){let e=parseFloat(r);if(!Number.isNaN(e))return e}return r},Ar=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch(e){return console.log(`JSON parse error: ${e}`),r}return r},Or=(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=>fs(e,a))}return r},Rr=r=>typeof r=="string"?r.replace(" ","T"):r,Ye=r=>{let e=r;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};var z=class{constructor(e,t,s={},i=Ve){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 Tt;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(Tt||(Tt={}));var te=class r{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=r.syncState(this.state,i,n,o),this.pendingDiffs.forEach(c=>{this.state=r.syncDiff(this.state,c,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},i=>{let{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=r.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,i){let n=this.cloneDeep(e),o=this.transformState(t),a={},c={};return this.map(n,(h,l)=>{o[h]||(c[h]=l)}),this.map(o,(h,l)=>{let u=n[h];if(u){let d=l.map(y=>y.presence_ref),f=u.map(y=>y.presence_ref),m=l.filter(y=>f.indexOf(y.presence_ref)<0),_=u.filter(y=>d.indexOf(y.presence_ref)<0);m.length>0&&(a[h]=m),_.length>0&&(c[h]=_)}else a[h]=l}),this.syncDiff(n,{joins:a,leaves:c},s,i)}static syncDiff(e,t,s,i){let{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),i||(i=()=>{}),this.map(n,(a,c)=>{var h;let l=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(c),l.length>0){let u=e[a].map(f=>f.presence_ref),d=l.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}s(a,l,c)}),this.map(o,(a,c)=>{let h=e[a];if(!h)return;let l=c.map(u=>u.presence_ref);h=h.filter(u=>l.indexOf(u.presence_ref)<0),e[a]=h,i(a,h,c),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{let i=e[s];return"metas"in i?t[s]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[s]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};var xt;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(xt||(xt={}));var At;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes"})(At||(At={}));var Ot;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Ot||(Ot={}));var se=class r{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=x.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new z(this,O.join,this.params,this.timeout),this.rejoinTimer=new H(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=x.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=x.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=x.errored,this.rejoinTimer.scheduleTimeout())}),this._on(O.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new te(this),this.broadcastEndpointURL=Ye(this.socket.endPoint)+"/api/broadcast"}subscribe(e,t=this.timeout){var s,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(l=>e&&e("CHANNEL_ERROR",l)),this._onClose(()=>e&&e("CLOSED"));let c={},h={broadcast:n,presence:o,postgres_changes:(i=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(l=>l.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessToken&&(c.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:h},c)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:l})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),l===void 0){e&&e("SUBSCRIBED");return}else{let d=this.bindings.postgres_changes,f=(u=d?.length)!==null&&u!==void 0?u:0,m=[];for(let _=0;_<f;_++){let y=d[_],{filter:{event:E,schema:v,table:S,filter:b}}=y,A=l&&l[_];if(A&&A.event===E&&A.schema===v&&A.table===S&&A.filter===b)m.push(Object.assign(Object.assign({},y),{id:A.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=m,e&&e("SUBSCRIBED");return}}).receive("error",l=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(l).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,i;if(!this._canPush()&&e.type==="broadcast"){let{event:n,payload:o}=e,a={method:"POST",headers:{Authorization:this.socket.accessToken?`Bearer ${this.socket.accessToken}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,c;let h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||c===void 0)&&c.ack)&&n("ok"),h.receive("ok",()=>n("ok")),h.receive("error",()=>n("error")),h.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=x.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(O.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{let i=new z(this,O.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 z(this,e,t,s);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var i,n;let o=e.toLocaleLowerCase(),{close:a,error:c,leave:h,join:l}=O;if(s&&[a,c,h,l].indexOf(o)>=0&&s!==this._joinRef())return;let d=this._onMessage(o,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(f=>{var m,_,y;return((m=f.filter)===null||m===void 0?void 0:m.event)==="*"||((y=(_=f.filter)===null||_===void 0?void 0:_.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===o}).map(f=>f.callback(d,s)):(n=this.bindings[o])===null||n===void 0||n.filter(f=>{var m,_,y,E,v,S;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let b=f.id,A=(m=f.filter)===null||m===void 0?void 0:m.event;return b&&((_=t.ids)===null||_===void 0?void 0:_.includes(b))&&(A==="*"||A?.toLocaleLowerCase()===((y=t.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))}else{let b=(v=(E=f?.filter)===null||E===void 0?void 0:E.event)===null||v===void 0?void 0:v.toLocaleLowerCase();return b==="*"||b===((S=t?.event)===null||S===void 0?void 0:S.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){let m=d.data,{schema:_,table:y,commit_timestamp:E,type:v,errors:S}=m;d=Object.assign(Object.assign({},{schema:_,table:y,commit_timestamp:E,eventType:v,new:{},old:{},errors:S}),this._getPayloadRecords(m))}f.callback(d,s)})}_isClosed(){return this.state===x.closed}_isJoined(){return this.state===x.joined}_isJoining(){return this.state===x.joining}_isLeaving(){return this.state===x.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,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(O.close,{},e)}_onError(e){this._on(O.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=x.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Et(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Et(e.columns,e.old_record)),t}};var Cr=()=>{},jr=typeof WebSocket<"u",re=class{constructor(e,t){var s;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=hs,this.params={},this.timeout=Ve,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Cr,this.conn=null,this.sendBuffer=[],this.serializer=new be,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>Promise.resolve().then(()=>(D(),M)).then(({default:c})=>c(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${Ke.websocket}`,this.httpEndpoint=Ye(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let 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 H(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(jr){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new Rt(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Ht(gs())).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 B.connecting:return N.Connecting;case B.open:return N.Open;case B.closing:return N.Closing;default:return N.Closed}}isConnected(){return this.connectionState()===N.Open}channel(e,t={config:{}}){let s=new se(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){let{topic:t,event:s,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var c;(c=this.conn)===null||c===void 0||c.send(a)})};this.log("push",`${t} ${s} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(O.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(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:us}))}_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(O.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(ds,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}},Rt=class{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=B.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}};var ie=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 Qe=class extends ie{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},ke=class extends ie{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var Ir=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Xe=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(D(),M)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},ms=()=>Ir(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Promise.resolve().then(()=>(D(),M))).Response:Response});var ne=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Pt=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),$r=(r,e)=>ne(void 0,void 0,void 0,function*(){let t=yield ms();r instanceof t?r.json().then(s=>{e(new Qe(Pt(s),r.status||500))}).catch(s=>{e(new ke(Pt(s),s))}):e(new ke(Pt(r),r))}),Lr=(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 Ze(r,e,t,s,i,n){return ne(this,void 0,void 0,function*(){return new Promise((o,a)=>{r(t,Lr(e,s,i,n)).then(c=>{if(!c.ok)throw c;return s?.noResolveJson?c:c.json()}).then(c=>o(c)).catch(c=>$r(c,a))})})}function Se(r,e,t,s){return ne(this,void 0,void 0,function*(){return Ze(r,"GET",e,t,s)})}function j(r,e,t,s,i){return ne(this,void 0,void 0,function*(){return Ze(r,"POST",e,s,i,t)})}function _s(r,e,t,s,i){return ne(this,void 0,void 0,function*(){return Ze(r,"PUT",e,s,i,t)})}function et(r,e,t,s,i){return ne(this,void 0,void 0,function*(){return Ze(r,"DELETE",e,s,i,t)})}var R=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Ur={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ys={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Ee=class{constructor(e,t={},s,i){this.url=e,this.headers=t,this.bucketId=s,this.fetch=Xe(i)}uploadOrUpdate(e,t,s,i){return R(this,void 0,void 0,function*(){try{let n,o=Object.assign(Object.assign({},ys),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&s instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),n.append("",s)):typeof FormData<"u"&&s instanceof FormData?(n=s,n.append("cacheControl",o.cacheControl)):(n=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);let c=this._removeEmptyFolders(t),h=this._getFinalPath(c),l=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:n,headers:a},o?.duplex?{duplex:o.duplex}:{})),u=yield l.json();return l.ok?{data:{path:c,id:u.Id,fullPath:u.Key},error:null}:{data:null,error:u}}catch(n){if(k(n))return{data:null,error:n};throw n}})}upload(e,t,s){return R(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,i){return R(this,void 0,void 0,function*(){let n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let c,h=Object.assign({upsert:ys.upsert},i),l=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&s instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",s)):typeof FormData<"u"&&s instanceof FormData?(c=s,c.append("cacheControl",h.cacheControl)):(c=s,l["cache-control"]=`max-age=${h.cacheControl}`,l["content-type"]=h.contentType);let u=yield this.fetch(a.toString(),{method:"PUT",body:c,headers:l}),d=yield u.json();return u.ok?{data:{path:n,fullPath:d.Key},error:null}:{data:null,error:d}}catch(c){if(k(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return R(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=Object.assign({},this.headers);t?.upsert&&(i["x-upsert"]="true");let n=yield j(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new ie("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 R(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return R(this,void 0,void 0,function*(){try{return{data:yield j(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(k(i))return{data:null,error:i};throw i}})}copy(e,t,s){return R(this,void 0,void 0,function*(){try{return{data:{path:(yield j(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(k(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,s){return R(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield j(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers}),o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(k(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,s){return R(this,void 0,void 0,function*(){try{let i=yield j(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(k(i))return{data:null,error:i};throw i}})}download(e,t){return R(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 Se(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",c=this.transformOptsToQueryString(t?.transform||{});c!==""&&i.push(c);let h=i.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${h}`)}}}remove(e){return R(this,void 0,void 0,function*(){try{return{data:yield et(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}list(e,t,s){return R(this,void 0,void 0,function*(){try{let i=Object.assign(Object.assign(Object.assign({},Ur),t),{prefix:e||""});return{data:yield j(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},s),error:null}}catch(i){if(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 vs="2.6.0";var ws={"X-Client-Info":`storage-js/${vs}`};var oe=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Te=class{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},ws),t),this.fetch=Xe(s)}listBuckets(){return oe(this,void 0,void 0,function*(){try{return{data:yield Se(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 oe(this,void 0,void 0,function*(){try{return{data:yield Se(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 oe(this,void 0,void 0,function*(){try{return{data:yield j(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(k(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return oe(this,void 0,void 0,function*(){try{return{data:yield _s(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 oe(this,void 0,void 0,function*(){try{return{data:yield j(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}deleteBucket(e){return oe(this,void 0,void 0,function*(){try{return{data:yield et(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(k(t))return{data:null,error:t};throw t}})}};var xe=class extends Te{constructor(e,t={},s){super(e,t,s)}from(e){return new Ee(this.url,this.headers,e,this.fetch)}};var bs="2.44.4";var Ae="";typeof Deno<"u"?Ae="deno":typeof document<"u"?Ae="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ae="react-native":Ae="node";var Dr={"X-Client-Info":`supabase-js-${Ae}/${bs}`},ks={headers:Dr},Ss={schema:"public"},Es={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ts={};D();var Nr=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},qr=r=>{let e;return r?e=r:typeof fetch>"u"?e=ut:e=fetch,(...t)=>e(...t)},Fr=()=>typeof Headers>"u"?dt:Headers,xs=(r,e,t)=>{let s=qr(t),i=Fr();return(n,o)=>Nr(void 0,void 0,void 0,function*(){var a;let c=(a=yield e())!==null&&a!==void 0?a:r,h=new i(o?.headers);return h.has("apikey")||h.set("apikey",r),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),s(n,Object.assign(Object.assign({},o),{headers:h}))})};function As(r){return r.replace(/\/$/,"")}function Os(r,e){let{db:t,auth:s,realtime:i,global:n}=r,{db:o,auth:a,realtime:c,global:h}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},h),n)}}var tt="2.64.4";var Rs="http://localhost:9999",Ps="supabase.auth.token";var Cs={"X-Client-Info":`gotrue-js/${tt}`},Ct=10;var Oe="X-Supabase-Api-Version",jt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function js(r){return Math.round(Date.now()/1e3)+r}function Is(){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 P=()=>typeof document<"u",J={tested:!1,writable:!1},q=()=>{if(!P())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(J.tested)return J.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),J.tested=!0,J.writable=!0}catch{J.tested=!0,J.writable=!1}return J.writable};function st(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((s,i)=>{e[i]=s}),e}var rt=r=>{let e;return r?e=r:typeof fetch>"u"?e=(...t)=>Promise.resolve().then(()=>(D(),M)).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},$s=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",It=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},Pe=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},it=async(r,e)=>{await r.removeItem(e)};function Mr(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",s,i,n,o,a,c,h,l=0;for(r=r.replace("-","+").replace("_","/");l<r.length;)o=e.indexOf(r.charAt(l++)),a=e.indexOf(r.charAt(l++)),c=e.indexOf(r.charAt(l++)),h=e.indexOf(r.charAt(l++)),s=o<<2|a>>4,i=(a&15)<<4|c>>2,n=(c&3)<<6|h,t=t+String.fromCharCode(s),c!=64&&i!=0&&(t=t+String.fromCharCode(i)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}var Re=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Re.promiseConstructor=Promise;function $t(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(Mr(s))}async function Ls(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function Us(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 Br(r){return("0"+r.toString(16)).substr(-2)}function Hr(){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,Br).join("")}async function zr(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 Jr(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Wr(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 zr(r);return Jr(t)}async function W(r,e,t=!1){let s=Hr(),i=s;t&&(i+="/PASSWORD_RECOVERY"),await It(r,`${e}-code-verifier`,i);let n=await Wr(s);return[n,s===n?"plain":"s256"]}var Gr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ds(r){let e=r.headers.get(Oe);if(!e||!e.match(Gr))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Ce=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 nt=class extends Ce{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}};function Ns(r){return p(r)&&r.name==="AuthApiError"}var ae=class extends Ce{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},L=class extends Ce{constructor(e,t,s,i){super(e,s,i),this.name=t,this.status=s}},I=class extends L{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}},ce=class extends L{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},G=class extends L{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},K=class extends L{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},je=class extends L{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},le=class extends L{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function ot(r){return p(r)&&r.name==="AuthRetryableFetchError"}var Ie=class extends L{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}};var Kr=function(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(r);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(r,s[i])&&(t[s[i]]=r[s[i]]);return t},V=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Vr=[502,503,504];async function qs(r){var e;if(!$s(r))throw new le(V(r),0);if(Vr.includes(r.status))throw new le(V(r),r.status);let t;try{t=await r.json()}catch(n){throw new ae(V(n),n)}let s,i=Ds(r);if(i&&i.getTime()>=jt["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 Ie(V(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 Ie(V(t),r.status,t.weak_password.reasons);throw new nt(V(t),r.status||500,s)}var Yr=(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[Oe]||(n[Oe]=jt["2024-01-01"].name),s?.jwt&&(n.Authorization=`Bearer ${s.jwt}`);let o=(i=s?.query)!==null&&i!==void 0?i:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Qr(r,e,t+a,{headers:n,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function Qr(r,e,t,s,i,n){let o=Yr(e,s,i,n),a;try{a=await r(t,Object.assign({},o))}catch(c){throw console.error(c),new le(V(c),0)}if(a.ok||await qs(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await qs(c)}}function U(r){var e;let t=null;Xr(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=js(r.expires_in)));let s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function Lt(r){let e=U(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=r.weak_password),e}function $(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function Fs(r){return{data:r,error:null}}function Ms(r){let{action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n}=r,o=Kr(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:i,verification_type:n},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function Bs(r){return r}function Xr(r){return r.access_token&&r.refresh_token&&r.expires_in}var Zr=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},Y=class{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=rt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await g(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(p(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await g(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:$})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:t}=e,s=Zr(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:Ms,redirectTo:t?.redirectTo})}catch(t){if(p(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await g(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:$})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,i,n,o,a,c;try{let h={nextPage:null,lastPage:0,total:0},l=await g(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(n=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:Bs});if(l.error)throw l.error;let u=await l.json(),d=(o=l.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(c=(a=l.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return f.length>0&&(f.forEach(m=>{let _=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(m.split(";")[1].split("=")[1]);h[`${y}Page`]=_}),h.total=parseInt(d)),{data:Object.assign(Object.assign({},u),h),error:null}}catch(h){if(p(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await g(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:$})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await g(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:$})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await g(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:$})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{let{data:t,error:s}=await g(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:s}}catch(t){if(p(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await g(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}};var Hs={getItem:r=>q()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{q()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{q()&&globalThis.localStorage.removeItem(r)}};function Ut(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function zs(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}var Q={debug:!!(globalThis&&q()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},$e=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},at=class extends $e{};async function Dt(r,e,t){Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),Q.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async i=>{if(i){Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,i.name);try{return await t()}finally{Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,i.name)}}else{if(e===0)throw Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new at(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Q.debug)try{let n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}zs();var ei={url:Rs,storageKey:Ps,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Cs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},Le=30*1e3,Js=3;async function Ws(r,e,t){return await t()}var X=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&&P()&&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({},ei),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Y({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=rt(i.fetch),this.lock=i.lock||Ws,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:P()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=Dt:this.lock=Ws,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:q()?this.storage=Hs:(this.memoryStorage={},this.storage=Ut(this.memoryStorage)):(this.memoryStorage={},this.storage=Ut(this.memoryStorage)),P()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${tt}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{let e=P()?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 ae("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,i;try{let n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:U}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,i;try{let n;if("email"in e){let{email:l,password:u,options:d}=e,f=null,m=null;this.flowType==="pkce"&&([f,m]=await W(this.storage,this.storageKey)),n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:l,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:m},xform:U})}else if("phone"in e){let{phone:l,password:u,options:d}=e;n=await g(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:l,password:u,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(i=d?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:U})}else throw new G("You must provide either an email or phone number and a password");let{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};let c=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(n){if(p(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){let{email:n,password:o,options:a}=e;t=await g(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Lt})}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:Lt})}else throw new G("You must provide either an email or phone number and a password");let{data:s,error:i}=t;return i?{data:{user:null,session:null},error:i}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new ce}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:i})}catch(t){if(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 Pe(this.storage,`${this.storageKey}-code-verifier`),[s,i]=(t??"").split("/"),{data:n,error:o}=await g(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:U});return await it(this.storage,`${this.storageKey}-code-verifier`),o?{data:{user:null,session:null,redirectType:null},error:o}:!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new ce}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}async signInWithIdToken(e){try{let{options:t,provider:s,token:i,access_token:n,nonce:o}=e,a=await g(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:U}),{data:c,error:h}=a;return h?{data:{user:null,session:null},error:h}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new ce}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,i,n,o;try{if("email"in e){let{email:a,options:c}=e,h=null,l=null;this.flowType==="pkce"&&([h,l]=await W(this.storage,this.storageKey));let{error:u}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:h,code_challenge_method:l},redirectTo:c?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){let{phone:a,options:c}=e,{data:h,error:l}=await g(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=c?.data)!==null&&i!==void 0?i:{},create_user:(n=c?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(o=c?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h?.message_id},error:l}}throw new G("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:U});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,h=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(p(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,s,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await W(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:Fs})}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 I;let{error:i}=await g(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(p(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:s,type:i,options:n}=e,{error:o}=await g(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}},redirectTo:n?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){let{phone:s,type:i,options:n}=e,{data:o,error:a}=await g(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:i,gotrue_meta_security:{captcha_token:n?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new G("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await Pe(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let s=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,h,l)=>(!o&&h==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,h,l))})}return{data:{session:e},error:null}}let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:$}):await this._useSession(async t=>{var s,i,n;let{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new I}:await g(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:$})})}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 I;let o=i.session,a=null,c=null;this.flowType==="pkce"&&e.email!=null&&([a,c]=await W(this.storage,this.storageKey));let{data:h,error:l}=await g(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:c}),jwt:o.access_token,xform:$});if(l)throw l;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}_decodeJWT(e){return $t(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new I;let t=Date.now()/1e3,s=t,i=!0,n=null,o=$t(e.access_token);if(o.exp&&(s=o.exp,i=s<=t),i){let{session:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!a)return{data:{user:null,session:null},error:null};n=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)throw c;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(p(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){let{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new I;let{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!P())throw new K("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new K("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new je("Not a valid PKCE flow url.");let t=st(window.location.href);if(e){if(!t.code)throw new je("No code detected.");let{data:v,error:S}=await this._exchangeCodeForSession(t.code);if(S)throw S;let b=new URL(window.location.href);return b.searchParams.delete("code"),window.history.replaceState(window.history.state,"",b.toString()),{data:{session:v.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new K(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:c,token_type:h}=t;if(!n||!a||!o||!h)throw new K("No session defined in URL");let l=Math.round(Date.now()/1e3),u=parseInt(a),d=l+u;c&&(d=parseInt(c));let f=d-l;f*1e3<=Le&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let m=d-u;l-m>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",m,d,l):l-m<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",m,d,l);let{data:_,error:y}=await this._getUser(n);if(y)throw y;let E={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:o,token_type:h,user:_.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:E,redirectType:t.type},error:null}}catch(t){if(p(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){let e=st(window.location.href);return!!(P()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=st(window.location.href),t=await Pe(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&&!(Ns(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await it(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t=Is(),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 W(this.storage,this.storageKey,!0));try{return await g(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(p(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{let{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:s,error:i}=await this._useSession(async n=>{var o,a,c,h,l;let{data:u,error:d}=n;if(d)throw d;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await g(this.fetch,"GET",f,{headers:this.headers,jwt:(l=(h=u.session)===null||h===void 0?void 0:h.access_token)!==null&&l!==void 0?l:void 0})});if(i)throw i;return P()&&!(!((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 Us(async i=>(i>0&&await Ls(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await g(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:U})),(i,n)=>{let o=200*Math.pow(2,i);return n&&ot(n)&&Date.now()+o-s<Le})}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),P()&&!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 Pe(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+Ct;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${Ct}s`),n){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),ot(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new I;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Re;let{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new I;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);let a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),p(n)){let o={session:null,error:n};return ot(n)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,s=!0){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(c){n.push(c)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await It(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await it(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&P()&&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(),Le);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)/Le);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Le}ms, refresh threshold is ${Js} ticks`),i<=Js&&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 $e)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!P()||!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 W(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(s?.queryParams){let n=new URLSearchParams(s.queryParams);i.push(n.toString())}return s?.skipBrowserRedirect&&i.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,i;let{data:n,error:o}=t;if(o)return{data:null,error:o};let{data:a,error:c}=await g(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(!((i=a?.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:o,error:a}=await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;let{data:i,error:n}=t;return n?{data:null,error:n}:await g(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let s=e?.factors||[],i=s.filter(n=>n.factor_type==="totp"&&n.status==="verified");return{data:{all:s,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;let{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let o=this._decodeJWT(i.access_token),a=null;o.aal&&(a=o.aal);let c=a;((s=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let l=o.amr||[];return{data:{currentLevel:a,nextLevel:c,currentAuthenticationMethods:l},error:null}}))}};X.nextInstanceID=0;var ti=X,Nt=ti;var ct=class extends Nt{constructor(e){super(e)}};var si=function(r,e,t,s){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(l){try{h(s.next(l))}catch(u){o(u)}}function c(l){try{h(s.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):i(l.value).then(a,c)}h((s=s.apply(r,e||[])).next())})},Ue=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=As(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:Ss,realtime:Ts,auth:Object.assign(Object.assign({},Es),{storageKey:c}),global:ks},l=Os(s??{},h);this.storageKey=(i=l.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},this.auth=this._initSupabaseAuthClient((o=l.auth)!==null&&o!==void 0?o:{},this.headers,l.global.fetch),this.fetch=xs(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new cs(`${a}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new fe(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new xe(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return si(this,void 0,void 0,function*(){let{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,storageKey:n,flowType:o,debug:a},c,h){var l;let u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ct({url:this.authUrl,headers:Object.assign(Object.assign({},u),c),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:i,flowType:o,debug:a,fetch:h,hasCustomAuthorizationHeader:(l="Authorization"in this.headers)!==null&&l!==void 0?l:!1})}_initRealtimeClient(e){return new re(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 Gs=(r,e,t)=>new Ue(r,e,t);var he={supaBaseUrl:"https://dodjkfqhwrzqjwkfnthl.supabase.co",supaBaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRvZGprZnFod3J6cWp3a2ZudGhsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTk4ODQzMDcsImV4cCI6MjAzNTQ2MDMwN30.h6EeQ_6kqFeznH25icVUX0Szn9__kc8HoSXAsxxBWG8",redirectUri:`${window.location.origin}/downloads`};var lt=class{constructor(){this.sessionData=null;this.supabase=Gs(he.supaBaseUrl,he.supaBaseKey)}async signInWithGoogle(e){try{await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:e||he.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||he.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:he.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 ri(){try{let r=document.createElement("canvas"),e=r.getContext("webgl")||r.getContext("experimental-webgl");if(e){let t=e.getExtension("WEBGL_debug_renderer_info"),s=e.getParameter(t.UNMASKED_RENDERER_WEBGL);return console.log(`WebGL Renderer: ${s}`),s.includes("Apple")}}catch{return!1}}var Ks=async()=>{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")?ri()?"mac_m1":"mac_intel":r.includes("Windows")?"Windows":r.includes("Linux")?"Linux":/iPhone|iPad|iPod/.test(r)?"iOS":/Android/.test(r)?"Android":"Unknown"}};var Vs=()=>document.cookie.split("; ").reduce((r,e)=>{let[t,s]=e.split("=");return r[t]=s,r},{});var Z=(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 lt,{accessToken:c,refreshToken:h}=Gt(),l=await Ks();i==="true"&&Z("stripe_checkout_success",{email:localStorage.getItem("email"),device_type:l,source:"downloads_page",plan:localStorage.getItem("checkout_plan")}),localStorage.removeItem("checkout_plan");let u=document.querySelector("#hello-text"),d=document.querySelector("#logout-button");d.style.display="none";let f=Vs(),{dub_id:m,referral:_}=f;if(c&&h)try{a.setCookies(c,h);let v=a.checkAndSetSession(),S=new Promise((De,F)=>setTimeout(()=>F(new Error("Session timeout")),3e3));await Promise.race([v,S]);let b=a.sessionData?.user.email,A=a.sessionData?.user.user_metadata.full_name||" ",[Ft,Ys]=zt(A),ai=a.sessionData?.user.id,Qs={access_token:c,first_name:Ft,last_name:Ys,dub_click_id:m||void 0,referral:_||void 0};if(localStorage.setItem("email",b),!localStorage.getItem("conversion_sent")||t){let De=await Fe.signupUser(Qs);t&&(oi(De),console.log("OAuth signup response:",De),console.log("Showing referral UI"))}if(localStorage.getItem("conversion_sent")||await ii(l,m,_,b),u.textContent=`Hi ${Ft}!`,d.style.display="flex",s&&c){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; justify-content: center; align-items: center; height: 100vh;"><h3>Checking your subscription...</h3></div>',document.body.style.visibility="visible";try{let F=await fetch("https://api.wisprflow.ai/api/v1/payment/subscription",{method:"GET",headers:{accept:"application/json",Authorization:c}});if(console.log("Subscription status response:",F),F.ok){let Mt=await F.json();if(console.log("User status:",Mt),Mt.is_subscribed){let Xs=window.location.pathname;window.history.pushState({},"",Xs),document.body.innerHTML=`
2
2
  <div style="display: flex; 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 Xs=t?`/downloads?referral=${t}`:"/downloads";ii(3,Xs)}else await qt(s,a,t)}else await qt(s,a,t)}catch(F){console.error("Status check error:",F),await qt(s,a,t)}return}clearTimeout(n),document.body.style.visibility="visible"}catch(m){i=!0,clearTimeout(n),window.location.href="/get-started",console.error("Error during session setup:",m)}else localStorage.getItem("email")?(l.textContent=`Hi ${localStorage.getItem("email")}!`,u.style.display="flex",clearTimeout(n),document.body.style.visibility="visible"):(i=!0,clearTimeout(n),window.location.href="/get-started");document.querySelectorAll("[active-download]").forEach(function(m){if(!h.startsWith("mac")&&m.getAttribute("active-download")?.startsWith("mac")){m.onclick=S=>{if(S.preventDefault(),!localStorage.getItem("email"))return i=!0,clearTimeout(n),window.location.href="/get-started",!1;Ue("app_waitlist",{device_type:m.getAttribute("active-download")});let k={email:localStorage.getItem("email"),device_type:m.getAttribute("active-download")||"unknown"};return Fe.addToWaitlist(k),m.innerText="We emailed you the download link!",!1};return}m.onclick=()=>(Ue("app_download",{device_type:m.getAttribute("active-download"),source:"downloads-page",email:localStorage.getItem("email")||"not-found"}),m.getAttribute("active-download")?.startsWith("mac")?setTimeout(()=>{window.location.href="/congratulations-mac"},5e3):m.getAttribute("active-download")?.startsWith("windows")&&setTimeout(()=>{window.location.href="/congratulations-windows"},5e3),!0)}),document.querySelectorAll("[waitlist]").forEach(function(m){m.onclick=S=>{if(S.preventDefault(),!localStorage.getItem("email"))return i=!0,clearTimeout(n),window.location.href="/get-started",!1;Ue("app_waitlist",{device_type:m.getAttribute("waitlist")});let k={email:localStorage.getItem("email"),device_type:m.getAttribute("waitlist")||"unknown"};return Fe.addToWaitlist(k),m.innerText="You're on the waitlist!",!1}}),u.addEventListener("click",async()=>{try{await o.signOut(),localStorage.removeItem("email"),localStorage.removeItem("conversion_sent"),sessionStorage.removeItem("referral_status"),i=!0,clearTimeout(n),window.location.href="/get-started"}catch(m){console.error("Error during sign-out:",m)}})});async function ri(r,e,t,s){localStorage.getItem("conversion_sent")||(Ue("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 qt(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),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 ii(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 he(){document.querySelectorAll("[default-h1]").forEach(e=>{e.style.display="none"})}function ni(r){if(r.is_student===!0){document.querySelectorAll("[students-div]").forEach(t=>{t.style.display="block"}),he();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"}),he()):r.referral_status.user_exists===!0?(document.querySelectorAll("[existing-user-div]").forEach(t=>{t.style.display="block"}),he()):(document.querySelectorAll("[success-referral-div]").forEach(t=>{t.style.display="block"}),he()):r.referral_status.message==="Invalid referral code."?(document.querySelectorAll("[invalid-code-div]").forEach(t=>{t.style.display="block"}),he()):r.referral_status.message==="Cannot refer yourself."&&(document.querySelectorAll("[self-referral-div]").forEach(t=>{t.style.display="block"}),he()))}})();
7
+ `;let Zs=t?`/downloads?referral=${t}`:"/downloads";ni(3,Zs)}else await qt(s,c,t)}else await qt(s,c,t)}catch(F){console.error("Status check error:",F),await qt(s,c,t)}return}clearTimeout(o),document.body.style.visibility="visible"}catch(v){n=!0,clearTimeout(o),window.location.href="/get-started",console.error("Error during session setup:",v)}else localStorage.getItem("email")?(u.textContent=`Hi ${localStorage.getItem("email")}!`,d.style.display="flex",clearTimeout(o),document.body.style.visibility="visible"):(n=!0,clearTimeout(o),window.location.href="/get-started");document.querySelectorAll("[active-download]").forEach(function(v){if(!l.startsWith("mac")&&v.getAttribute("active-download")?.startsWith("mac")){v.onclick=S=>{if(S.preventDefault(),!localStorage.getItem("email"))return n=!0,clearTimeout(o),window.location.href="/get-started",!1;Z("app_waitlist",{device_type:v.getAttribute("active-download")});let b={email:localStorage.getItem("email"),device_type:v.getAttribute("active-download")||"unknown"};return Fe.addToWaitlist(b),v.innerText="We emailed you the download link!",!1};return}v.onclick=()=>(Z("app_download",{device_type:v.getAttribute("active-download"),source:"downloads-page",email:localStorage.getItem("email")||"not-found"}),v.getAttribute("active-download")?.startsWith("mac")?setTimeout(()=>{window.location.href="/congratulations-mac"},5e3):v.getAttribute("active-download")?.startsWith("windows")&&setTimeout(()=>{window.location.href="/congratulations-windows"},5e3),!0)}),document.querySelectorAll("[waitlist]").forEach(function(v){v.onclick=S=>{if(S.preventDefault(),!localStorage.getItem("email"))return n=!0,clearTimeout(o),window.location.href="/get-started",!1;Z("app_waitlist",{device_type:v.getAttribute("waitlist")});let b={email:localStorage.getItem("email"),device_type:v.getAttribute("waitlist")||"unknown"};return Fe.addToWaitlist(b),v.innerText="You're on the waitlist!",!1}}),d.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(v){console.error("Error during sign-out:",v)}})});async function ii(r,e,t,s){localStorage.getItem("conversion_sent")||(Z("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 qt(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),Z("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 ni(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 ue(){document.querySelectorAll("[default-h1]").forEach(e=>{e.style.display="none"})}function oi(r){if(r.is_student===!0){document.querySelectorAll("[students-div]").forEach(t=>{t.style.display="block"}),ue();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"}),ue()):r.referral_status.user_exists===!0?(document.querySelectorAll("[existing-user-div]").forEach(t=>{t.style.display="block"}),ue()):(document.querySelectorAll("[success-referral-div]").forEach(t=>{t.style.display="block"}),ue()):r.referral_status.message==="Invalid referral code."?(document.querySelectorAll("[invalid-code-div]").forEach(t=>{t.style.display="block"}),ue()):r.referral_status.message==="Cannot refer yourself."&&(document.querySelectorAll("[self-referral-div]").forEach(t=>{t.style.display="block"}),ue()))}})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanay-wispr/webflow-package",
3
- "version": "4.10.0",
3
+ "version": "4.10.2",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },