@convokitapp/chat-embed 0.0.0-stage → 1.0.1

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/main.js ADDED
@@ -0,0 +1,77 @@
1
+ "use strict";var ConvoKitWidgetBundle=(()=>{var ui=Object.defineProperty;var Qr=t=>{throw TypeError(t)};var hi=(t,e,r)=>e in t?ui(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var R=(t,e,r)=>hi(t,typeof e!="symbol"?e+"":e,r),Zr=(t,e,r)=>e.has(t)||Qr("Cannot "+r);var lr=(t,e,r)=>(Zr(t,e,"read from private field"),r?r.call(t):e.get(t)),es=(t,e,r)=>e.has(t)?Qr("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),ts=(t,e,r,s)=>(Zr(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r);var di="https://api.convokit.app",J=t=>{throw new TypeError(`ConvoKitWidget: ${t}`)},K=t=>typeof t=="string"?t.trim():"",rs=(t,e)=>{let r=K(t);return r?(/^\d+(\.\d+)?(px|vh|vw|%|rem|em)$/.test(r)||J(`invalid size "${r}"`),r):e};function ss(t){(!t||typeof t!="object")&&J("start() needs a configuration object");let e=K(t.clientId)||J("clientId is required"),r=t.mode;r!=="guest"&&r!=="uid"&&r!=="authToken"&&J('mode must be "guest", "uid" or "authToken"'),r!=="authToken"&&!K(t.widgetKey)&&J(`widgetKey is required in ${r} mode`),r==="uid"&&!K(t.uid)&&J("uid is required in uid mode"),r==="authToken"&&(K(t.userId)||J("userId is required in authToken mode"),!t.tokenProvider&&!K(t.tokenUrl)&&J("tokenUrl or tokenProvider is required in authToken mode"),t.widgetKey&&J("do not put a widget key in authToken mode; your server issues the token")),t.startConversationWith!==void 0&&(!Array.isArray(t.startConversationWith)||!t.startConversationWith.every(n=>K(n)))&&J("startConversationWith must be an array of user IDs");let s=K(t.theme?.primaryColor)||"#4f46e5";return!/^#[0-9a-f]{3,8}$/i.test(s)&&!/^(rgb|hsl)a?\([\d\s.,%]+\)$/i.test(s)&&J("theme.primaryColor must be a hex, rgb() or hsl() color"),{...t,clientId:e,mode:r,widgetKey:K(t.widgetKey)||void 0,uid:K(t.uid)||void 0,userId:K(t.userId)||void 0,startConversationWith:[...new Set((t.startConversationWith??[]).map(n=>n.trim()))],isDocked:t.isDocked??!0,dockedAlignment:t.dockedAlignment==="left"?"left":"right",width:rs(t.width,"380px"),height:rs(t.height,"560px"),title:K(t.title)||"Chat",storageMode:t.storageMode==="SESSION"?"SESSION":"LOCAL",apiUrl:(K(t.apiUrl)||di).replace(/\/+$/,""),primaryColor:s}}var fi=Symbol.for("@supabase/supabase-js.traceContextExtractor");function ns(){return globalThis[fi]}function we(t,e){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(r[s[n]]=t[s[n]]);return r}function is(t,e,r,s){function n(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(u){try{l(s.next(u))}catch(h){o(h)}}function c(u){try{l(s.throw(u))}catch(h){o(h)}}function l(u){u.done?i(u.value):n(u.value).then(a,c)}l((s=s.apply(t,e||[])).next())})}var os=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);var Oe=class extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}toJSON(){return{name:this.name,message:this.message,context:this.context}}},Ze=class extends Oe{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Pe=class extends Oe{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Ne=class extends Oe{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},et;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(et||(et={}));var tt=class{constructor(e,{headers:r={},customFetch:s,region:n=et.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=os(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return is(this,arguments,void 0,function*(r,s={}){var n,i;let o,a,c;try{let{headers:l,method:u,body:h,signal:f,timeout:d}=s,p={},{region:g}=s;g||(g=this.region);let m=new URL(`${this.url}/${r}`);g&&g!=="any"&&(p["x-region"]=g,m.searchParams.set("forceFunctionRegion",g));let w,_=!!l&&Object.keys(l).some(Qe=>Qe.toLowerCase()==="content-type");h&&!_?typeof Blob<"u"&&h instanceof Blob||h instanceof ArrayBuffer?(p["Content-Type"]=h.type||"application/octet-stream",w=h):typeof h=="string"?(p["Content-Type"]="text/plain",w=h):typeof FormData<"u"&&h instanceof FormData?w=h:(p["Content-Type"]="application/json",w=JSON.stringify(h)):h&&typeof h!="string"&&!(typeof Blob<"u"&&h instanceof Blob)&&!(h instanceof ArrayBuffer)&&!(typeof FormData<"u"&&h instanceof FormData)?w=JSON.stringify(h):w=h;let b=f;d&&(a=new AbortController,o=setTimeout(()=>a.abort(),d),f?(b=a.signal,c=()=>a.abort(),f.addEventListener("abort",c)):b=a.signal);let A=yield this.fetch(m.toString(),{method:u||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),l),body:w,signal:b}).catch(Qe=>{throw new Ze(Qe)}),B=A.headers.get("x-relay-error");if(B&&B==="true")throw new Pe(A);if(!A.ok)throw new Ne(A);let C=((n=A.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim().toLowerCase(),x;return C==="application/json"?x=yield A.json():C==="application/octet-stream"||C==="application/pdf"?x=yield A.blob():C==="text/event-stream"?x=A:C==="multipart/form-data"?x=yield A.formData():x=yield A.text(),{data:x,error:null,response:A}}catch(l){return{data:null,error:l,response:l instanceof Ne||l instanceof Pe?l.context:void 0}}finally{o&&clearTimeout(o),c&&((i=s.signal)===null||i===void 0||i.removeEventListener("abort",c))}})}};var _e=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}},ds=3,as=t=>Math.min(1e3*2**t,3e4),pi=[520,503],fs=["GET","HEAD","OPTIONS"];function rt(t){"@babel/helpers - typeof";return rt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},rt(t)}function gi(t,e){if(rt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(rt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function mi(t){var e=gi(t,"string");return rt(e)=="symbol"?e:e+""}function yi(t,e,r){return(e=mi(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function cs(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function be(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?cs(Object(r),!0).forEach(function(s){yi(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):cs(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}function ls(t,e){return new Promise(r=>{if(e?.aborted){r();return}let s=setTimeout(()=>{e?.removeEventListener("abort",n),r()},t);function n(){clearTimeout(s),r()}e?.addEventListener("abort",n)})}function vi(t,e,r,s){return!(!s||r>=ds||!fs.includes(t)||!pi.includes(e))}async function ps(t,e,r,s){let n=0;for(;;){let c=be({},r.headers);n>0&&(c["X-Retry-Count"]=String(n));let l;try{l=await t(e,{method:r.method,headers:c,body:r.body,signal:r.signal})}catch(u){var i;if(u?.name==="AbortError"||u?.code==="ABORT_ERR"||u?.name==="TimeoutError"&&(!((i=r.signal)===null||i===void 0)&&i.aborted)||!fs.includes(r.method))throw u;if(s&&n<ds){let h=as(n);n++,await ls(h,r.signal);continue}throw u}if(vi(r.method,l.status,n,s)){var o,a;let u=(o=(a=l.headers)===null||a===void 0?void 0:a.get("Retry-After"))!==null&&o!==void 0?o:null,h=u!==null?Math.max(0,parseInt(u,10)||0)*1e3:as(n);await l.text(),n++,await ls(h,r.signal);continue}return l}}var wi=class{constructor(t){var e,r,s,n,i;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(s=t.shouldStripNulls)!==null&&s!==void 0?s:!1,this.urlLengthLimit=(n=t.urlLengthLimit)!==null&&n!==void 0?n:8e3,this.retryEnabled=(i=t.retry)!==null&&i!==void 0?i:!0,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var r=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){let o=this.headers.get("Accept");o==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!o||o==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let s=this.fetch,i=(async()=>{let o={};r.headers.forEach((c,l)=>{o[l]=c});let a=await ps(s,r.url.toString(),{method:r.method,headers:o,body:JSON.stringify(r.body,(c,l)=>typeof l=="bigint"?l.toString():l),signal:r.signal},r.retryEnabled);return await r.processResponse(a)})();return this.shouldThrowOnError||(i=i.catch(o=>{var a;let c="",l="",u="",h=o?.cause;if(h){var f,d,p,g;let _=(f=h?.message)!==null&&f!==void 0?f:"",b=(d=h?.code)!==null&&d!==void 0?d:"";c=`${(p=o?.name)!==null&&p!==void 0?p:"FetchError"}: ${o?.message}`,c+=`
2
+
3
+ Caused by: ${(g=h?.name)!==null&&g!==void 0?g:"Error"}: ${_}`,b&&(c+=` (${b})`),h?.stack&&(c+=`
4
+ ${h.stack}`)}else{var m;c=(m=o?.stack)!==null&&m!==void 0?m:""}let w=this.url.toString().length;return o?.name==="AbortError"||o?.code==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${w} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(h?.name==="HeadersOverflowError"||h?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(l+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${(a=o?.name)!==null&&a!==void 0?a:"FetchError"}: ${o?.message}`,details:c,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}async processResponse(t){var e=this;let r=null,s=null,n=null,i=t.status,o=t.statusText;if(t.ok){var a,c;if(e.method!=="HEAD"){var l;let d=await t.text();if(d!=="")if(e.headers.get("Accept")==="text/csv")s=d;else if(e.headers.get("Accept")&&(!((l=e.headers.get("Accept"))===null||l===void 0)&&l.includes("application/vnd.pgrst.plan+text")))s=d;else try{s=JSON.parse(d)}catch{if(r={message:d},s=null,e.shouldThrowOnError)throw new _e({message:d,details:"",hint:"",code:""})}}let h=(a=e.headers.get("Prefer"))===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),f=(c=t.headers.get("content-range"))===null||c===void 0?void 0:c.split("/");if(h&&f&&f.length>1&&(n=parseInt(f[1])),e.isMaybeSingle&&Array.isArray(s))if(s.length>1){if(r={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,n=null,i=406,o="Not Acceptable",e.shouldThrowOnError){var u;throw new _e(be(be({},r),{},{hint:(u=r.hint)!==null&&u!==void 0?u:""}))}}else s.length===1?s=s[0]:s=null}else{let h=await t.text();try{r=JSON.parse(h),Array.isArray(r)&&t.status===404&&(s=[],r=null,i=200,o="OK")}catch{t.status===404&&h===""?(i=204,o="No Content"):r={message:h}}if(r&&e.shouldThrowOnError)throw new _e(r)}return{success:r===null,error:r,data:s,count:n,status:i,statusText:o}}returns(){return this}overrideTypes(){return this}},bi=class extends wi{throwOnError(){return super.throwOnError()}select(t){let e=!1,r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){let i=n?`${n}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){let n=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${a};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},us=new RegExp("[,()]"),Ue=class extends bi{throwOnError(){return super.throwOnError()}eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&us.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&us.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${i}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},_i=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:n=8e3,retry:i}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=n,this.retry=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:s}=e??{},n=r?"HEAD":"GET",i=!1,o=(t??"*").split("").map(l=>/\s/.test(l)&&!i?"":(l==='"'&&(i=!i),l)).join(""),{url:a,headers:c}=this.cloneRequestState();return a.searchParams.set("select",o),s&&c.append("Prefer",`count=${s}`),new Ue({method:n,url:a,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;let n="POST",{url:i,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((c,l)=>c.concat(Object.keys(l)),[]);if(a.length>0){let c=[...new Set(a)].map(l=>`"${l}"`);i.searchParams.set("columns",c.join(","))}}return new Ue({method:n,url:i,headers:o,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;let o="POST",{url:a,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),n||c.append("Prefer","missing=default"),Array.isArray(t)){let l=t.reduce((u,h)=>u.concat(Object.keys(h)),[]);if(l.length>0){let u=[...new Set(l)].map(h=>`"${h}"`);a.searchParams.set("columns",u.join(","))}}return new Ue({method:o,url:a,headers:c,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;let s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Ue({method:s,url:n,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;let r="DELETE",{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Ue({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function Ei(t,e){try{let o=JSON.parse(t);if(o&&typeof o=="object"&&!Array.isArray(o)){var r,s,n,i;return new _e({message:String((r=o.message)!==null&&r!==void 0?r:t),details:(s=o.details)!==null&&s!==void 0?s:"",hint:(n=o.hint)!==null&&n!==void 0?n:"",code:(i=o.code)!==null&&i!==void 0?i:""})}}catch{}return new _e({message:t||e,details:"",hint:"",code:""})}function hs(t,e,r){var s;let n=t;return{success:!1,error:new _e({message:`${(s=n?.name)!==null&&s!==void 0?s:"FetchError"}: ${n?.message}`,details:"",hint:"",code:""}),data:null,count:null,status:e,statusText:r}}var gs=class ms{constructor(e,{headers:r={},schema:s,fetch:n,timeout:i,urlLengthLimit:o=8e3,retry:a}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=o;let c=n??globalThis.fetch;i!==void 0&&i>0?this.fetch=(l,u)=>{let h=new AbortController,f=setTimeout(()=>h.abort(),i),d=u?.signal;if(d){if(d.aborted)return clearTimeout(f),c(l,u);let p=()=>{clearTimeout(f),h.abort()};return d.addEventListener("abort",p,{once:!0}),c(l,be(be({},u),{},{signal:h.signal})).finally(()=>{clearTimeout(f),d.removeEventListener("abort",p)})}return c(l,be(be({},u),{},{signal:h.signal})).finally(()=>clearTimeout(f))}:this.fetch=c,this.retry=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new _i(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new ms(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}async getOpenApiSpec(){var e=this,r;let s=new Headers(e.headers);s.set("Accept","application/openapi+json"),e.schemaName&&s.set("Accept-Profile",e.schemaName);let n={};s.forEach((l,u)=>{n[u]=l});let i=(r=e.fetch)!==null&&r!==void 0?r:globalThis.fetch,o;try{var a;o=await ps(i,`${e.url}/`,{method:"GET",headers:n},(a=e.retry)!==null&&a!==void 0?a:!0)}catch(l){return hs(l,0,"")}let c;try{c=await o.text()}catch(l){return hs(l,o.status,o.statusText)}if(o.ok)try{return{success:!0,error:null,data:JSON.parse(c),count:null,status:o.status,statusText:o.statusText}}catch{}return{success:!1,error:Ei(c,o.statusText),data:null,count:null,status:o.status,statusText:o.statusText}}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var o;let a,c=new URL(`${this.url}/rpc/${e}`),l,u=d=>d!==null&&typeof d=="object"&&(!Array.isArray(d)||d.some(u)),h=s&&Object.values(r).some(u);h?(a="POST",l=r):s||n?(a=s?"HEAD":"GET",Object.entries(r).filter(([d,p])=>p!==void 0).map(([d,p])=>[d,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([d,p])=>{c.searchParams.append(d,p)})):(a="POST",l=r);let f=new Headers(this.headers);return h?f.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&f.set("Prefer",`count=${i}`),new Ue({method:a,url:c,headers:f,schema:this.schemaName,body:l,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};var ur=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};let r=globalThis;if(typeof globalThis<"u"&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};let s=typeof global<"u"?global:void 0;if(s&&typeof s.WebSocket<"u")return{type:"native",wsConstructor:s.WebSocket};if(typeof globalThis<"u"&&typeof r.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&r.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let n=globalThis.process;if(n){let i=n.versions;if(i&&i.node)return{type:"unsupported",error:"Node.js detected but native WebSocket not found.",workaround:"Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
5
+
6
+ Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{return this.detectEnvironment().type==="native"}catch{return!1}}},hr=ur;var ys="2.118.0";var vs=`realtime-js/${ys}`,ws="1.0.0",dr="2.0.0",bs=dr;var _s=1e4,Es=15e3,Ss=1e4;var Ts=100;var Q={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},It={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var st={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var nt=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,s;let n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,s;let n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},o=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,s){var n,i;let o=new TextEncoder,a=o.encode(e.topic),c=o.encode((n=e.ref)!==null&&n!==void 0?n:""),l=o.encode((i=e.join_ref)!==null&&i!==void 0?i:""),u=o.encode(e.payload.event),h=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},f=o.encode(Object.keys(h).length===0?"":JSON.stringify(h));if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`ref length ${c.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`topic length ${a.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(f.length>255)throw new Error(`metadata length ${f.length} exceeds maximum of 255`);let d=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+c.length+a.length+u.length+f.length,p=new ArrayBuffer(this.HEADER_LENGTH+d),g=new DataView(p),m=new Uint8Array(p),w=0;g.setUint8(w++,this.KINDS.userBroadcastPush),g.setUint8(w++,l.length),g.setUint8(w++,c.length),g.setUint8(w++,a.length),g.setUint8(w++,u.length),g.setUint8(w++,f.length),g.setUint8(w++,r),m.set(l,w),w+=l.length,m.set(c,w),w+=c.length,m.set(a,w),w+=a.length,m.set(u,w),w+=u.length,m.set(f,w),w+=f.length;var _=new Uint8Array(p.byteLength+s.byteLength);return _.set(new Uint8Array(p),0),_.set(new Uint8Array(s),p.byteLength),_.buffer}decode(e,r){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return r(s)}if(typeof e=="string"){let s=JSON.parse(e),[n,i,o,a,c]=s;return r({join_ref:n,ref:i,topic:o,event:a,payload:c})}return r({})}_binaryDecode(e){let r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;if(s===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,s){let n=r.getUint8(1),i=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),c=this.HEADER_LENGTH+4,l=s.decode(e.slice(c,c+n));c=c+n;let u=s.decode(e.slice(c,c+i));c=c+i;let h=s.decode(e.slice(c,c+o));c=c+o;let f=e.slice(c,e.byteLength),d=a===this.JSON_ENCODING?JSON.parse(s.decode(f)):f,p={type:this.BROADCAST_EVENT,event:u,payload:d};return o>0&&(p.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>r.includes(s)))}};var I;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(I||(I={}));var pr=(t,e,r={})=>{var s;let n=(s=r.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=Si(o,t,e,n),i),{}):{}},Si=(t,e,r,s)=>{let n=e.find(a=>a.name===t),i=n?.type,o=r[t];return i&&!s.includes(i)?ks(i,o):fr(o)},ks=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Ri(e,r)}switch(t){case I.bool:return Ti(e);case I.float4:case I.float8:case I.int2:case I.int4:case I.int8:case I.numeric:case I.oid:return ki(e);case I.json:case I.jsonb:return Ai(e);case I.timestamp:return Ci(e);case I.abstime:case I.date:case I.daterange:case I.int4range:case I.int8range:case I.money:case I.reltime:case I.text:case I.time:case I.timestamptz:case I.timetz:case I.tsrange:case I.tstzrange:return fr(e);default:return fr(e)}},fr=t=>t,Ti=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},ki=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Ai=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Ri=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let i,o=t.slice(1,r);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>ks(e,a))}return t},Ci=t=>typeof t=="string"?t.replace(" ","T"):t,xt=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var $e=t=>typeof t=="function"?t:function(){return t},xi=typeof self<"u"?self:null,Le=typeof window<"u"?window:null,Z=xi||Le||globalThis,Oi="2.0.0",Pi=1e4,Ni=1e3,Ui=100,ee={connecting:0,open:1,closing:2,closed:3},F={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},le={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},gr={longpoll:"longpoll",websocket:"websocket"},ji={complete:4},mr="base64url.bearer.phx.",Ot=class{constructor(t,e,r,s){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),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()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(s=>s.status===t).forEach(s=>s.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},As=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}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))}},Li=class{constructor(t,e,r){this.state=F.closed,this.topic=t,this.params=$e(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Ot(this,le.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new As(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=F.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=F.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=F.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=F.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Ot(this,le.leave,$e({}),this.timeout).send(),this.state=F.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(le.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=F.closed,this.bindings=[]}onClose(t){this.on(le.close,t)}onError(t){return this.on(le.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new Ot(this,t,function(){return e},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=F.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(le.close,"leave")},r=new Ot(this,le.leave,$e({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=F.joining,this.joinPush.resend(t))}trigger(t,e,r,s){let n=this.onMessage(t,e,r,s);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(o=>o.event===t&&this.filterBindings(o,e,r));for(let o=0;o<i.length;o++)i[o].callback(n,r,s||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===F.closed}isErrored(){return this.state===F.errored}isJoined(){return this.state===F.joined}isJoining(){return this.state===F.joining}isLeaving(){return this.state===F.leaving}},Nt=class{static request(t,e,r,s,n,i,o){if(Z.XDomainRequest){let a=new Z.XDomainRequest;return this.xdomainRequest(a,t,e,s,n,i,o)}else if(Z.XMLHttpRequest){let a=new Z.XMLHttpRequest;return this.xhrRequest(a,t,e,r,s,n,i,o)}else{if(Z.fetch&&Z.AbortController)return this.fetchRequest(t,e,r,s,n,i,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,s,n,i,o){let a={method:t,headers:r,body:s},c=null;if(n){c=new AbortController;let l=setTimeout(()=>c.abort(),n);a.signal=c.signal}return Z.fetch(e,a).then(l=>l.text()).then(l=>this.parseJSON(l)).then(l=>o&&o(l)).catch(l=>{l.name==="AbortError"&&i?i():o&&o(null)}),c}static xdomainRequest(t,e,r,s,n,i,o){return t.timeout=n,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);o&&o(a)},i&&(t.ontimeout=i),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,r,s,n,i,o,a){t.open(e,r,!0),t.timeout=i;for(let[c,l]of Object.entries(s))t.setRequestHeader(c,l);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===ji.complete&&a){let c=this.parseJSON(t.responseText);a(c)}},o&&(t.ontimeout=o),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=e?`${e}[${s}]`:s,i=t[s];typeof i=="object"?r.push(this.serialize(i,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},$i=t=>{let e="",r=new Uint8Array(t),s=r.byteLength;for(let n=0;n<s;n++)e+=String.fromCharCode(r[n]);return btoa(e)},je=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(mr)&&(this.authToken=atob(e[1].slice(mr.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=ee.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+gr.websocket),"$1/"+gr.longpoll)}endpointURL(){return Nt.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=ee.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===ee.open||this.readyState===ee.connecting}poll(){let t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:s,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else r=0;switch(r){case 200:n.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=ee.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=$i(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t,e=0){this.awaitingBatchAck=!0;let r=e+Ui,s=t.slice(e,r);this.ajax("POST",{"Content-Type":"application/x-ndjson"},s.join(`
7
+ `),()=>this.onerror("timeout"),n=>{!n||n.status!==200?(this.awaitingBatchAck=!1,this.onerror(n&&n.status),this.closeAndRetry(1011,"internal server error",!1)):r<t.length?this.batchSend(t,r):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=ee.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,r,s,n){let i,o=()=>{this.reqs.delete(i),s()};i=Nt.request(t,this.endpointURL(),e,r,this.timeout,o,a=>{this.reqs.delete(i),this.isActive()&&n(a)}),this.reqs.add(i)}},Rs=class it{constructor(e,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state=Object.create(null),this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=it.syncState(this.state,n,i,o),this.pendingDiffs.forEach(c=>{this.state=it.syncDiff(this.state,c,i,o)}),this.pendingDiffs=[],a()}),this.channel.on(s.diff,n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=it.syncDiff(this.state,n,i,o),a())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return it.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,s,n){let i=this.toNullProtoObj(this.clone(e));r=this.toNullProtoObj(r);let o=Object.create(null),a=Object.create(null);return this.map(i,(c,l)=>{r[c]||(a[c]=l)}),this.map(r,(c,l)=>{let u=i[c];if(u){let h=l.metas.map(g=>g.phx_ref),f=u.metas.map(g=>g.phx_ref),d=l.metas.filter(g=>f.indexOf(g.phx_ref)<0),p=u.metas.filter(g=>h.indexOf(g.phx_ref)<0);d.length>0&&(o[c]=l,o[c].metas=d),p.length>0&&(a[c]=this.clone(u),a[c].metas=p)}else o[c]=l}),this.syncDiff(i,{joins:o,leaves:a},s,n)}static syncDiff(e,r,s,n){e=this.toNullProtoObj(e);let{joins:i,leaves:o}=this.clone(r);return s||(s=function(){}),n||(n=function(){}),this.map(i,(a,c)=>{let l=e[a];if(e[a]=this.clone(c),l){let u=e[a].metas.map(f=>f.phx_ref),h=l.metas.filter(f=>u.indexOf(f.phx_ref)<0);e[a].metas.unshift(...h)}s(a,l,c)}),this.map(o,(a,c)=>{let l=e[a];if(!l)return;let u=c.metas.map(h=>h.phx_ref);l.metas=l.metas.filter(h=>u.indexOf(h.phx_ref)<0),n(a,l,c),l.metas.length===0&&delete e[a]}),e}static list(e,r){return r||(r=function(s,n){return n}),this.map(e,(s,n)=>r(s,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static toNullProtoObj(e){if(Object.getPrototypeOf(e)===null)return e;let r=Object.create(null);return Object.getOwnPropertyNames(e).forEach(s=>{r[s]=e[s]}),r}static clone(e){return JSON.parse(JSON.stringify(e))}},Pt={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,s,n,i,o]=JSON.parse(t);return e({join_ref:r,ref:s,topic:n,event:i,payload:o})}},binaryEncode(t){let{join_ref:e,ref:r,event:s,topic:n,payload:i}=t,o=new TextEncoder,a=o.encode(e),c=o.encode(r),l=o.encode(n),u=o.encode(s);this.assertFieldSize(a.byteLength,"join_ref"),this.assertFieldSize(c.byteLength,"ref"),this.assertFieldSize(l.byteLength,"topic"),this.assertFieldSize(u.byteLength,"event");let h=this.META_LENGTH+a.byteLength+c.byteLength+l.byteLength+u.byteLength,f=new ArrayBuffer(this.HEADER_LENGTH+h),d=new Uint8Array(f),p=new DataView(f),g=0;p.setUint8(g++,this.KINDS.push),p.setUint8(g++,a.byteLength),p.setUint8(g++,c.byteLength),p.setUint8(g++,l.byteLength),p.setUint8(g++,u.byteLength),d.set(a,g),g+=a.byteLength,d.set(c,g),g+=c.byteLength,d.set(l,g),g+=l.byteLength,d.set(u,g),g+=u.byteLength;var m=new Uint8Array(f.byteLength+i.byteLength);return m.set(d,0),m.set(new Uint8Array(i),f.byteLength),m.buffer},assertFieldSize(t,e){if(t>255)throw new Error(`unable to convert ${e} to binary: must be less than or equal to 255 bytes, but is ${t} bytes`)},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(o,o+s));o=o+s;let c=r.decode(t.slice(o,o+n));o=o+n;let l=r.decode(t.slice(o,o+i));o=o+i;let u=t.slice(o,t.byteLength);return{join_ref:a,ref:null,topic:c,event:l,payload:u}},decodeReply(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,c=r.decode(t.slice(a,a+s));a=a+s;let l=r.decode(t.slice(a,a+n));a=a+n;let u=r.decode(t.slice(a,a+i));a=a+i;let h=r.decode(t.slice(a,a+o));a=a+o;let f=t.slice(a,t.byteLength),d={status:h,response:f};return{join_ref:c,ref:l,topic:u,event:le.reply,payload:d}},decodeBroadcast(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),i=this.HEADER_LENGTH+2,o=r.decode(t.slice(i,i+s));i=i+s;let a=r.decode(t.slice(i,i+n));i=i+n;let c=t.slice(i,t.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:c}}},Cs=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Pi,this.transport=e.transport||Z.WebSocket||je,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=Z&&Z.sessionStorage}catch{}this.sessionStore=e.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=Pt.encode.bind(Pt),this.defaultDecoder=Pt.decode.bind(Pt),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==je?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let s=null;Le&&Le.addEventListener&&(Le.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),s=this.connectClock)}),Le.addEventListener("pageshow",n=>{s===this.connectClock&&(s=null,this.connect())}),Le.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,i,o)=>{console.log(`${n}: ${i}`,o)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=$e(e.params||{}),this.endPoint=`${t}/${gr.websocket}`,this.vsn=e.vsn||Oi,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new As(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken&&$e(e.authToken)}getLongPollTransport(){return je}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Nt.appendParams(Nt.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=$e(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==je?this.connectWithFallback(je,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let s=this.onMessage(n=>{n.ref===e&&(this.off([s]),t(Date.now()-r))});return!0}transportName(t){return t===je?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${mr}${btoa(this.authToken()).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,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)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,s=!0,n,i,o=this.transportName(t),a=c=>{this.log("transport",`falling back to ${o}...`,c),this.off([n,i]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),i=this.onError(c=>{this.log("transport","error",c),s&&!r&&(clearTimeout(this.fallbackTimer),a(c))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let c=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${c}`,"true"),this.log("transport",`established ${c} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(c=>{this.log("transport","connected to primary after",c),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Ni,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();let s=this.conn;this.waitForBufferDone(s,()=>{e?s.close(e,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===ee.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(t),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError(t)}triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(le.error,t)})}connectionState(){switch(this.conn&&this.conn.readyState){case ee.connecting:return"connecting";case ee.open:return"open";case ee.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new Li(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:s,ref:n,join_ref:i}=t;this.log("push",`${e} ${r} (${i}, ${n})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:s,payload:n,ref:i,join_ref:o}=e;if(i&&i===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",a)}catch(c){this.log("error","error in heartbeat callback",c)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${s} ${i&&"("+i+")"||""}`.trim(),n);for(let a=0;a<this.channels.length;a++){let c=this.channels[a];c.isMember(r,s,n,o)&&c.trigger(s,n,i,o)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,s])=>{try{s(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};var ot=class t{constructor(e,r){let s=Mi(r);this.presence=new Rs(e.getChannel(),s),this.presence.onJoin((n,i,o)=>{let a=t.onJoinPayload(n,i,o);e.getChannel().trigger("presence",a)}),this.presence.onLeave((n,i,o)=>{let a=t.onLeavePayload(n,i,o);e.getChannel().trigger("presence",a)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=Di(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{let n=e[s];return r[s]=Ut(n),r},{})}static onJoinPayload(e,r,s){let n=Is(r),i=Ut(s);return{event:"join",key:e,currentPresences:n,newPresences:i}}static onLeavePayload(e,r,s){let n=Is(r),i=Ut(s);return{event:"leave",key:e,currentPresences:n,leftPresences:i}}};function Ut(t){return t.metas.map(e=>{let r=Object.getOwnPropertyDescriptors(e),s=Object.defineProperties({},r);return s.presence_ref=s.phx_ref,delete s.phx_ref,delete s.phx_ref_prev,s})}function Di(t){return JSON.parse(JSON.stringify(t))}function Mi(t){return t?.events&&{events:t.events}}function Is(t){return t?.metas?Ut(t):[]}var yr;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(yr||(yr={}));var De=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new ot(this.channel.channelAdapter,r)}};function xs(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){let e=t;if(typeof e.code=="number"){let r=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${r}`,{cause:t})}return new Error("channel error: transport failure",{cause:t})}return new Error("channel error: connection lost")}var at=class{constructor(e,r,s){let n=qi(s);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,s){let n;try{n=this.channel.push(e,r,s)}catch{throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>Ts){let i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return n}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===Q.joined}isJoined(){return this.state===Q.joined}isJoining(){return this.state===Q.joining}isClosed(){return this.state===Q.closed}isLeaving(){return this.state===Q.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function qi(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var Bi=/[,()"\\]/,Hi=t=>Bi.test(t)||t!==t.trim(),Fi=t=>`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Os=t=>{let e=t===null?"null":String(t);return Hi(e)?Fi(e):e},Ki=t=>t===null?"null":String(t),Wi=(t,e)=>{if(t==="in"){let r=Array.isArray(e)?e:[e];if(r.length===0)throw new Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(r)).map(n=>Os(n)).join(",")})`}return t==="is"?`is.${Ki(e)}`:`${t}.${Os(e)}`},Me=class{constructor(){this.filters=[]}add(e,r,s,n=!1){let i=n?"not.":"";return this.filters.push(`${e}=${i}${Wi(r,s)}`),this}eq(e,r){return this.add(e,"eq",r)}neq(e,r){return this.add(e,"neq",r)}gt(e,r){return this.add(e,"gt",r)}gte(e,r){return this.add(e,"gte",r)}lt(e,r){return this.add(e,"lt",r)}lte(e,r){return this.add(e,"lte",r)}in(e,r){return this.add(e,"in",r)}like(e,r){return this.add(e,"like",r)}ilike(e,r){return this.add(e,"ilike",r)}match(e,r){return this.add(e,"match",r)}imatch(e,r){return this.add(e,"imatch",r)}is(e,r){return this.add(e,"is",r)}isDistinct(e,r){return this.add(e,"isdistinct",r)}not(e,r,s){return this.add(e,r,s,!0)}build(){return this.filters.join(",")}toString(){return this.build()}};var vr;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(vr||(vr={}));var fe;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(fe||(fe={}));var te;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(te||(te={}));var qe=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new at(this.socket.socketAdapter,e,this.params),this.presence=new De(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=xt(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,r=this.timeout){var s,n,i,o;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:a,presence:c,private:l,postgres_changes_options:u}}=this.params,h=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(m=>m.filter))!==null&&n!==void 0?n:[],f=!!this.bindings[fe.PRESENCE]&&this.bindings[fe.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,d={},p=Object.assign({broadcast:a,presence:Object.assign(Object.assign({},c),{enabled:f}),postgres_changes:h,private:l},u?{postgres_changes_options:u}:{});this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(m=>{e?.(te.CHANNEL_ERROR,xs(m))}),this._onClose(()=>e?.(te.CLOSED)),this.updateJoinPayload(Object.assign({config:p},d)),this._updateFilterMessage();let g=u?.wait&&h.length>0?Math.max(r,((o=u.timeout)!==null&&o!==void 0?o:Es)+Ss):r;this.channelAdapter.subscribe(g).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e?.(te.SUBSCRIBED);return}this._updatePostgresBindings(m,e)}).receive("error",m=>{this.state=Q.errored;let w=Object.values(m).join(", ")||"error";e?.(te.CHANNEL_ERROR,new Error(w,{cause:m}))}).receive("timeout",()=>{e?.(te.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var s;let n=this.bindings.postgres_changes,i=(s=n?.length)!==null&&s!==void 0?s:0,o=[];for(let a=0;a<i;a++){let c=n[a],{filter:{event:l,schema:u,table:h,filter:f}}=c,d=e&&e[a];if(d&&d.event===l&&t.isFilterValueEqual(d.schema,u)&&t.isFilterValueEqual(d.table,h)&&t.isFilterValueEqual(d.filter,f))o.push(Object.assign(Object.assign({},c),{id:d.id}));else{this.unsubscribe(),this.state=Q.errored,r?.(te.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=o,this.state!=Q.errored&&r&&r(te.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){let n=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===fe.PRESENCE||e===fe.POSTGRES_CHANGES;if(n&&i)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,s)}async httpSend(e,r,s={}){var n;if(r==null)return Promise.reject(new Error("Payload is required for httpSend()"));let i=r instanceof ArrayBuffer||ArrayBuffer.isView(r),o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":i?"application/octet-stream":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);let a=new URL(this.broadcastEndpointURL);a.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(e)}`,this.private&&a.searchParams.set("private","true");let c={method:"POST",headers:o,body:i?r:JSON.stringify(r)},l=await this._fetchWithTimeout(a.toString(),c,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(l.status===202)return{success:!0};if(l.status===404)return Promise.reject(new Error("httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. See https://github.com/supabase/supabase-js/blob/master/packages/core/realtime-js/migrations/httpsend-server-version.md"));let u=l.statusText;try{let h=await l.json();u=h.error||h.message||u}catch{}return Promise.reject(new Error(u))}async send(e,r={}){var s,n;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){let i="Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.";this.socket.hasLogger()?this.socket.log("channel",i):console.warn(i);let{event:o,payload:a}=e,c={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(c.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:c,body:JSON.stringify({messages:[{topic:this.subTopic,event:o,payload:a,private:this.private}]})};try{let u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u instanceof Error&&u.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,c;let l=this.channelAdapter.push(e.type,e,r.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)&&i("ok"),l.receive("ok",()=>i("ok")),l.receive("error",()=>i("error")),l.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(i),o}_on(e,r,s){var n;let i=e.toLocaleLowerCase(),o=r?.filter;if((o instanceof Me||typeof o=="object"&&o!==null&&typeof o.build=="function")&&(r=Object.assign(Object.assign({},r),{filter:o.build()})),i===fe.POSTGRES_CHANGES&&((n=this.bindings[i])===null||n===void 0?void 0:n.find(u=>t.isSamePostgresFilter(u.filter,r))))return this.socket.log("error",`duplicate \`postgres_changes\` binding for ${this.topic} ignored`,r),this;let a=this.channelAdapter.on(e,s),c={type:i,filter:r,callback:s,ref:a};return this.bindings[i]?this.bindings[i].push(c):this.bindings[i]=[c],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,s)=>{var n,i,o,a,c,l,u;let h=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,s))return!1;let f=(n=this.bindings[h])===null||n===void 0?void 0:n.find(d=>d.ref===e.ref);if(!f)return!0;if(["broadcast","presence","postgres_changes"].includes(h))if("id"in f){let d=f.id,p=(i=f.filter)===null||i===void 0?void 0:i.event;return d&&((o=r.ids)===null||o===void 0?void 0:o.includes(d))&&(p==="*"||p?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let d=(l=(c=f?.filter)===null||c===void 0?void 0:c.event)===null||l===void 0?void 0:l.toLocaleLowerCase();return d==="*"||d===((u=r?.event)===null||u===void 0?void 0:u.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===h})}_notThisChannelEvent(e,r){let{close:s,error:n,leave:i,join:o}=It;return r&&[s,n,i,o].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,s)=>{if(typeof r=="object"&&"ids"in r){let n=r.data,{schema:i,table:o,commit_timestamp:a,type:c,errors:l}=n;return Object.assign(Object.assign({},{schema:i,table:o,commit_timestamp:a,eventType:c,new:{},old:{},errors:l}),this._getPayloadRecords(n))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(let r in e.bindings)for(let s of e.bindings[r])this._on(s.type,s.filter,s.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}static isSamePostgresFilter(e,r){var s,n,i,o;let a=(n=(s=e?.select)===null||s===void 0?void 0:s.join())!==null&&n!==void 0?n:void 0,c=(o=(i=r?.select)===null||i===void 0?void 0:i.join())!==null&&o!==void 0?o:void 0;return e?.event===r?.event&&t.isFilterValueEqual(e?.schema,r?.schema)&&t.isFilterValueEqual(e?.table,r?.table)&&t.isFilterValueEqual(e?.filter,r?.filter)&&a===c}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=pr(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=pr(e.columns,e.old_record)),r}};var ct=class{constructor(e,r){this.socket=new Cs(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,s,n=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),n),this.socket.disconnect(()=>{e(),i("ok")},r,s)})}push(e){this.socket.push(e)}log(e,r,s){this.socket.log(e,r,s)}hasLogger(){return this.socket.hasLogger()}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==st.connecting}isDisconnecting(){return this.socket.connectionState()==st.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var Ps={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Gi=[1e3,2e3,5e3,1e4],zi=1e4;function Ji(){let t=new Map;return{get length(){return t.size},clear(){t.clear()},getItem(e){return t.has(e)?t.get(e):null},key(e){var r;return(r=Array.from(t.keys())[e])!==null&&r!==void 0?r:null},removeItem(e){t.delete(e)},setItem(e,r){t.set(e,String(r))}}}function Xi(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return Ji()}var Yi=`
8
+ addEventListener("message", (e) => {
9
+ if (e.data.event === "start") {
10
+ setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
11
+ }
12
+ });`,Be=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var s;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new nt,this._manuallySetToken=!1,this._authPromise=null,this._authGeneration=0,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=i=>i?(...o)=>i(...o):(...o)=>fetch(...o),!(!((s=r?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let n=this._initializeOptions(r);this.socketAdapter=new ct(e,n),this.httpEndpoint=xt(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let r=e.message;throw new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),r}async removeAllChannels(){let e=this.channels.map(async s=>{let n=await s.unsubscribe();return s.teardown(),n}),r=await Promise.all(e);return await this.disconnect(),r}log(e,r,s){this.socketAdapter.log(e,r,s)}hasLogger(){return this.socketAdapter.hasLogger()}connectionState(){return this.socketAdapter.connectionState()||st.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let s=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===s);if(n)return n;{let i=new qe(`realtime:${e}`,r,this);return this._cancelPendingDisconnect(),this.channels.push(i),i}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){let r=++this._authGeneration,s=this._performAuth(e,r);r===this._authGeneration&&(this._authPromise=s);try{await s}finally{this._authPromise===s&&(this._authPromise=null)}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e,r){let s,n=!1;if(e)s=e,n=!0;else if(this.accessToken)try{s=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),s=this.accessTokenValue}else s=this.accessTokenValue;r===this._authGeneration&&(this.accessToken?this._manuallySetToken=!1:n&&(this._manuallySetToken=!0),this.accessTokenValue!=s&&(this.accessTokenValue=s,this.channels.forEach(i=>{let o={access_token:s,version:vs};i.updateJoinPayload(o),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(It.access_token,{access_token:s})})))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,s)=>{r!=="disconnected"&&(r=="sent"&&this._setAuthSafely(),e&&e(r,s))}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{let s=new Blob([Yi],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(e){var r,s,n,i,o,a,c,l,u,h,f,d;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=e?.accessToken)!==null&&s!==void 0?s:null;let p={};p.timeout=(n=e?.timeout)!==null&&n!==void 0?n:_s,p.heartbeatIntervalMs=(i=e?.heartbeatIntervalMs)!==null&&i!==void 0?i:Ps.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(o=e?.disconnectOnEmptyChannelsAfterMs)!==null&&o!==void 0?o:2*((a=e?.heartbeatIntervalMs)!==null&&a!==void 0?a:Ps.HEARTBEAT_INTERVAL),p.transport=(c=e?.transport)!==null&&c!==void 0?c:hr.getWebSocketConstructor(),p.params=e?.params,p.logger=e?.logger,p.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),p.sessionStorage=(l=e?.sessionStorage)!==null&&l!==void 0?l:Xi(),p.reconnectAfterMs=(u=e?.reconnectAfterMs)!==null&&u!==void 0?u:(_=>Gi[_-1]||zi);let g,m,w=(h=e?.vsn)!==null&&h!==void 0?h:bs;switch(w){case ws:g=(_,b)=>b(JSON.stringify(_)),m=(_,b)=>b(JSON.parse(_));break;case dr:g=this.serializer.encode.bind(this.serializer),m=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${p.vsn}`)}if(p.vsn=w,p.encode=(f=e?.encode)!==null&&f!==void 0?f:g,p.decode=(d=e?.decode)!==null&&d!==void 0?d:m,p.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,p.params=Object.assign(Object.assign({},p.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,p.autoSendHeartbeat=!this.worker}return p}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}};var lt=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Qi(t,e,r){let s=new URL(e,t);if(r)for(let[n,i]of Object.entries(r))i!==void 0&&s.searchParams.set(n,i);return s.toString()}async function Zi(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function eo(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:o}){let a=Qi(t.baseUrl,s,n),c=await Zi(t.auth),l=await e(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...c,...o},body:i?JSON.stringify(i):void 0}),u=await l.text(),h=(l.headers.get("content-type")||"").includes("application/json"),f=h&&u?JSON.parse(u):u;if(!l.ok){let d=h?f:void 0,p=d?.error;throw new lt(p?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:p?.type,icebergCode:p?.code,details:d})}return{status:l.status,headers:l.headers,data:f}}}}function jt(t){return t.join("")}var to=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:jt(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${jt(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${jt(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${jt(t.namespace)}`}),!0}catch(e){if(e instanceof lt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof lt&&r.status===409)return;throw r}}};function He(t){return t.join("")}var ro=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${He(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${He(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${He(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${He(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${He(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${He(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof lt&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof lt&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Ns=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=eo({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new to(this.client,e),this.tableOps=new ro(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};function ht(t){"@babel/helpers - typeof";return ht=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ht(t)}function so(t,e){if(ht(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(ht(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function no(t){var e=so(t,"string");return ht(e)=="symbol"?e:e+""}function io(t,e,r){return(e=no(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Us(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function E(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Us(Object(r),!0).forEach(function(s){io(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Us(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Mt=class extends Error{constructor(t,e="storage",r,s){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function qt(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Lt=class extends Mt{constructor(t,e,r,s="storage",n){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r,this.code=n}toJSON(){return E(E({},super.toJSON()),{},{code:this.code})}},$s=class extends Mt{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function $t(t,e,r){let s=E({},t),n=e.toLowerCase();for(let i of Object.keys(s))i.toLowerCase()===n&&delete s[i];return s[n]=r,s}function oo(t){let e={};for(let[r,s]of Object.entries(t))e[r.toLowerCase()]=s;return e}var ao=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),co=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},br=t=>{if(Array.isArray(t))return t.map(r=>br(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,s])=>{let n=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[n]=br(s)}),e},lo=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),_r=t=>t.split("/").map(encodeURIComponent).join("/"),js=t=>{if(typeof t=="object"&&t!==null){let e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){let r=e.error;if(typeof r.message=="string")return r.message}}return JSON.stringify(t)},uo=async(t,e,r,s)=>{if(t!==null&&typeof t=="object"&&"json"in t&&typeof t.json=="function"){let n=t,i=parseInt(String(n.status),10);Number.isFinite(i)||(i=500),n.json().then(o=>{let a=o?.statusCode||o?.code||i+"";e(new Lt(js(o),i,a,s,o?.code))}).catch(()=>{let o=i+"";e(new Lt(n.statusText||`HTTP ${i} error`,i,o,s))})}else e(new $s(js(t),t,s))},ho=(t,e,r,s)=>{let n={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!s)return E(E({},n),r);if(co(s)){var i;let o=e?.headers||{},a;for(let[c,l]of Object.entries(o))c.toLowerCase()==="content-type"&&(a=l);n.headers=$t(o,"Content-Type",(i=a)!==null&&i!==void 0?i:"application/json"),n.body=JSON.stringify(s)}else n.body=s;return e?.duplex&&(n.duplex=e.duplex),E(E({},n),r)};async function ut(t,e,r,s,n,i,o){return new Promise((a,c)=>{t(r,ho(e,s,n,i)).then(l=>{if(!l.ok)throw l;if(s?.noResolveJson)return l;if(o==="vectors"){let u=l.headers.get("content-type");if(l.headers.get("content-length")==="0"||l.status===204)return{};if(!u||!u.includes("application/json"))return{}}return l.json()}).then(l=>a(l)).catch(l=>uo(l,c,s,o))})}function Ds(t="storage"){return{get:async(e,r,s,n)=>ut(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>ut(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>ut(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>ut(e,"HEAD",r,E(E({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>ut(e,"DELETE",r,n,i,s,t)}}var fo=Ds("storage"),{get:Fe,post:X,put:Dt,head:po,remove:Ke}=fo,W=Ds("vectors"),We=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=oo(e),this.fetch=ao(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=$t(this.headers,t,e),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(qt(r))return{data:null,error:r};throw r}}},Ms;Ms=Symbol.toStringTag;var go=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Ms]="StreamDownloadBuilder",this.promise=null}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(qt(e))return{data:null,error:e};throw e}}},qs;qs=Symbol.toStringTag;var mo=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[qs]="BlobDownloadBuilder",this.promise=null}asStream(){return new go(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(qt(e))return{data:null,error:e};throw e}}},wr={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ls={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},yo=class extends We{constructor(t,e={},r,s){super(t,e,s,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,s){var n=this;return n.handleOperation(async()=>{let i,o=E(E({},Ls),s),a=E(E({},n.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),c=o.metadata;if(typeof Blob<"u"&&r instanceof Blob||typeof FormData<"u"&&r instanceof FormData?i=n.prepareUploadFormData(r,o):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,o.contentEncoding&&(a["content-encoding"]=o.contentEncoding),c&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(c))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),s?.headers)for(let[f,d]of Object.entries(s.headers))a=$t(a,f,d);let l=n._removeEmptyFolders(e),u=n._getFinalPath(l),h=await(t=="PUT"?Dt:X)(n.fetch,`${n.url}/object/${u}`,i,E({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{path:l,id:h.Id,fullPath:h.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var n=this;let i=n._removeEmptyFolders(t),o=n._getFinalPath(i),a=new URL(n.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let c,l=E(E({},Ls),s),u=E(E({},n.headers),{"x-upsert":String(l.upsert)}),h=l.metadata;if(typeof Blob<"u"&&r instanceof Blob||typeof FormData<"u"&&r instanceof FormData?c=n.prepareUploadFormData(r,l):(c=r,u["cache-control"]=`max-age=${l.cacheControl}`,u["content-type"]=l.contentType,l.contentEncoding&&(u["content-encoding"]=l.contentEncoding),h&&(u["x-metadata"]=n.toBase64(n.encodeMetadata(h))),(typeof ReadableStream<"u"&&c instanceof ReadableStream||c&&typeof c=="object"&&"pipe"in c&&typeof c.pipe=="function")&&!l.duplex&&(l.duplex="half")),s?.headers)for(let[f,d]of Object.entries(s.headers))u=$t(u,f,d);return{path:i,fullPath:(await Dt(n.fetch,a.toString(),c,E({headers:u},l?.duplex?{duplex:l.duplex}:{}))).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t),n=E({},r.headers);e?.upsert&&(n["x-upsert"]="true");let i=await X(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new Mt("No token returned by API");return{signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var s=this;return s.handleOperation(async()=>await X(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket,sourceVersionId:r?.sourceVersionId},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>{let n=r;return{path:(await X(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket,sourceVersionId:r?.sourceVersionId,copyMetadata:typeof n?.copyMetadata=="boolean"?n.copyMetadata:void 0,metadata:n?.copyMetadata===!1?n.metadata:void 0},{headers:s.headers})).Key}})}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t),i=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,o=await X(s.fetch,`${s.url}/object/sign/${n}`,E(E({expiresIn:e},i?{transform:r.transform}:{}),r?.versionId!=null?{versionId:r.versionId}:{}),{headers:s.headers}),a=new URLSearchParams;r?.download&&a.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&a.set("cacheNonce",String(r.cacheNonce));let c=a.toString();return{signedUrl:encodeURI(`${s.url}${o.signedURL}${c?`&${c}`:""}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{let n=await X(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),i=new URLSearchParams;r?.download&&i.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&i.set("cacheNonce",String(r.cacheNonce));let o=i.toString();return n.map(a=>E(E({},a),{},{signedUrl:a.signedURL?encodeURI(`${s.url}${a.signedURL}${o?`&${o}`:""}`):null}))})}download(t,e,r){let s=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",n=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce)),e?.versionId!=null&&n.set("versionId",String(e.versionId));let i=n.toString(),o=this._getFinalPath(t),a=()=>Fe(this.fetch,`${this.url}/${s}/${o}${i?`?${i}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new mo(a,this.shouldThrowOnError)}async info(t,e){var r=this;let s=r._getFinalPath(t),n=new URLSearchParams;e?.versionId!=null&&n.set("versionId",String(e.versionId));let i=n.toString();return r.handleOperation(async()=>br(await Fe(r.fetch,`${r.url}/object/info/${s}${i?`?${i}`:""}`,{headers:r.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await po(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(qt(n)){var s;let i=n instanceof Lt?n.status:n instanceof $s?(s=n.originalError)===null||s===void 0?void 0:s.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),s=new URLSearchParams;e?.download&&s.set("download",e.download===!0?"":e.download),e?.transform&&this.applyTransformOptsToQuery(s,e.transform),e?.cacheNonce!=null&&s.set("cacheNonce",String(e.cacheNonce)),e?.versionId!=null&&s.set("versionId",String(e.versionId));let n=s.toString(),i=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}`)+(n?`?${n}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await Ke(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async purgeCache(t,e,r){var s=this;return s.handleOperation(async()=>{let n=_r(s._getFinalPath(t)),i=new URLSearchParams;e?.transformations&&i.set("transformations","true");let o=i.toString();return await Ke(s.fetch,`${s.url}/cdn/${n}${o?`?${o}`:""}`,{},{headers:s.headers},r)})}async list(t,e,r){var s=this;return s.handleOperation(async()=>{let n=e?.sortBy?E(E({},wr.sortBy),e.sortBy):wr.sortBy,i=E(E(E({},wr),e),{},{sortBy:n,prefix:t||""});return await X(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let s=E({},t);return await X(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},e)})}prepareUploadFormData(t,e){let r=new FormData,s=[];t instanceof FormData?t.forEach((n,i)=>{typeof n=="string"?r.append(i,n):s.push([i,n])}):s.push(["",t]),r.has("cacheControl")||r.append("cacheControl",e.cacheControl),e.metadata&&!r.has("metadata")&&r.append("metadata",this.encodeMetadata(e.metadata)),e.contentEncoding&&!r.has("contentEncoding")&&r.append("contentEncoding",e.contentEncoding);for(let[n,i]of s)r.append(n,i);return r}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}},vo="2.118.0",dt={"X-Client-Info":`storage-js/${vo}`},wo=class extends We{constructor(t,e={},r,s){let n=new URL(t);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let i=n.href.replace(/\/$/,""),o=E(E({},dt),e);super(i,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await Fe(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Fe(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await X(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes,versioning_status:e.versioningStatus},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await Dt(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes,versioning_status:e.versioningStatus},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await X(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ke(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}async getBucketLifecycle(t){var e=this;return e.handleOperation(async()=>await Fe(e.fetch,e.bucketLifecycleUrl(t),{headers:e.headers}))}async updateBucketLifecycle(t,e){var r=this;return r.handleOperation(async()=>await Dt(r.fetch,r.bucketLifecycleUrl(t),e,{headers:r.headers}))}async deleteBucketLifecycle(t){var e=this;return e.handleOperation(async()=>await Ke(e.fetch,e.bucketLifecycleUrl(t),{},{headers:e.headers}))}async purgeBucketCache(t,e,r){var s=this;return s.handleOperation(async()=>{let n=new URLSearchParams;e?.transformations&&n.set("transformations","true");let i=n.toString();return await Ke(s.fetch,`${s.url}/cdn/${_r(t)}${i?`?${i}`:""}`,{},{headers:s.headers},r)})}bucketLifecycleUrl(t){return`${this.url}/bucket/${_r(t)}/lifecycle`}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},bo=class extends We{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=E(E({},dt),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await X(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await Fe(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ke(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!lo(t))throw new Mt("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new Ns({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,i){let o=n[i];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(n,a),error:null}}catch(c){if(s)throw c;return{data:null,error:c}}}}})}},_o=class extends We{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=E(E({},dt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await W.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await W.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await W.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await W.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Eo=class extends We{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=E(E({},dt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await W.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await W.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await W.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await W.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await W.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},So=class extends We{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=E(E({},dt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await W.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await W.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await W.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await W.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},To=class extends So{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new ko(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},ko=class extends _o{constructor(t,e,r,s){super(t,e,s),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new Ao(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Ao=class extends Eo{constructor(t,e,r,s,n){super(t,e,n),this.vectorBucketName=r,this.indexName=s}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},Bs=class extends wo{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new yo(this.url,this.headers,t,this.fetch)}get vectors(){return new To(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new bo(this.url+"/iceberg",this.headers,this.fetch)}};var Bt="2.118.0";var re=30*1e3,Ve=3,Ht=Ve*re,Hs=2*re,Fs="http://localhost:9999",Ks="supabase.auth.token";var Ws={"X-Client-Info":`gotrue-js/${Bt}`};var ft="X-Supabase-Api-Version",Er={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Vs=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,ue="sb_flow_id",Gs=5,zs=600*1e3;var pe=class extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}};function y(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var Ft=class extends pe{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}};function Sr(t){return y(t)&&t.name==="AuthApiError"}var q=class extends pe{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},G=class extends pe{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}},P=class extends G{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function yt(t){return y(t)&&t.name==="AuthSessionMissingError"}var he=class extends G{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Ee=class extends G{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Se=class extends G{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};function Js(t){return y(t)&&t.name==="AuthImplicitGrantRedirectError"}var pt=class extends G{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},Kt=class extends G{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}};var Te=class extends G{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function vt(t){return y(t)&&t.name==="AuthRetryableFetchError"}var gt=class extends G{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}};function Tr(t){return y(t)&&t.name==="AuthRefreshDiscardedError"}var mt=class extends G{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}};var ge=class extends G{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var Wt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Xs=`
13
+ \r=`.split(""),Ro=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Xs.length;e+=1)t[Xs[e].charCodeAt(0)]=-2;for(let e=0;e<Wt.length;e+=1)t[Wt[e].charCodeAt(0)]=e;return t})();function Ys(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let s=e.queue>>e.queuedBits-6&63;r(Wt[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let s=e.queue>>e.queuedBits-6&63;r(Wt[s]),e.queuedBits-=6}}function Qs(t,e,r){let s=Ro[t];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function kr(t){let e=[],r=o=>{e.push(String.fromCodePoint(o))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=o=>{xo(o,s,r)};for(let o=0;o<t.length;o+=1)Qs(t.charCodeAt(o),n,i);return e.join("")}function Co(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Io(t,e){for(let r=0;r<t.length;r+=1){let s=t.charCodeAt(r);if(s>55295&&s<=56319){let n=(s-55296)*1024&65535;s=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}Co(s,e)}}function xo(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let s=1;s<6;s+=1)if((t>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function me(t){let e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)Qs(t.charCodeAt(n),r,s);return new Uint8Array(e)}function Zs(t){let e=[];return Io(t,r=>e.push(r)),new Uint8Array(e)}function de(t){let e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>Ys(n,r,s)),Ys(null,r,s),e.join("")}function Vt(t){return Math.round(Date.now()/1e3)+t}function en(){return Symbol("auth-callback")}var j=()=>typeof window<"u"&&typeof document<"u",ke={tested:!1,writable:!1},Gt=()=>{if(!j())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ke.tested)return ke.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),ke.tested=!0,ke.writable=!0}catch{ke.tested=!0,ke.writable=!1}return ke.writable};function Ar(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return r.searchParams.forEach((s,n)=>{e[n]=s}),e}var zt=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),tn=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",se=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},D=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return null}},H=async(t,e)=>{await t.removeItem(e)},wt=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};wt.promiseConstructor=Promise;function _t(t){let e=t.split(".");if(e.length!==3)throw new ge("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Vs.test(e[s]))throw new ge("JWT not in base64url format");return{header:JSON.parse(kr(e[0])),payload:JSON.parse(kr(e[1])),signature:me(e[2]),raw:{header:e[0],payload:e[1]}}}async function rn(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function sn(t,e){return new Promise((s,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await t(i);if(!e(i,null,o)){s(o);return}}catch(o){if(!e(i,o)){n(o);return}}})()})}function nn(t){return("0"+t.toString(16)).substr(-2)}function Oo(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=r.length,n="";for(let i=0;i<56;i++)n+=r.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,nn).join("")}async function Po(t){let r=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(s);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function No(t){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."),t;let r=await Po(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Uo=/^[a-zA-Z0-9_-]{8,64}$/;function Et(t){return typeof t=="string"&&Uo.test(t)?t:null}function jo(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,nn).join("")}let t="";for(let e=0;e<32;e++)t+=Math.floor(Math.random()*16).toString(16);return t}var Ae=(t,e)=>`${t}-flow-${e}-code-verifier`,bt=t=>`${t}-flows-code-verifier`;async function Rr(t,e){let r=await D(t,bt(e));return Array.isArray(r)?r.filter(s=>Et(s)!==null):[]}async function Lo(t,e,r,s,n){await se(t,Ae(e,r),s);let i=(await Rr(t,e)).filter(o=>o!==r);for(i.push(r);i.length>Gs;){let o=i.shift();await H(t,Ae(e,o)),n?.(o)}await se(t,bt(e),i),await se(t,`${e}-code-verifier`,s)}async function on(t,e,r){if(r){let n=await D(t,Ae(e,r));return{verifier:typeof n=="string"?n:null,flowId:r}}let s=await D(t,`${e}-code-verifier`);return{verifier:typeof s=="string"?s:null,flowId:null}}async function z(t,e,r){let s=`${e}-code-verifier`;if(!r){await H(t,s);return}let n=Ae(e,r),i=await D(t,n);await H(t,n);let o=await Rr(t,e),a=o.filter(c=>c!==r);a.length!==o.length&&(a.length>0?await se(t,bt(e),a):await H(t,bt(e))),i!=null&&i===await D(t,s)&&await H(t,s)}async function an(t,e){let r=await Rr(t,e);for(let s of r)await H(t,Ae(e,s));await H(t,bt(e)),await H(t,`${e}-code-verifier`)}function cn(t,e){let r=t.indexOf("#"),s=r===-1?t:t.slice(0,r),n=r===-1?"":t.slice(r),i=s.indexOf("?");if(i!==-1){let a=s.slice(0,i),c=s.slice(i+1).split("&").filter(l=>l!==""&&l!==ue&&!l.startsWith(`${ue}=`));s=c.length>0?`${a}?${c.join("&")}`:a}let o=s.includes("?")?"&":"?";return`${s}${o}${ue}=${encodeURIComponent(e)}${n}`}async function ln(t,e,r=!1,s){let n=Oo(),i=n;r&&(i+="/recovery");let o=jo();await Lo(t,e,o,i,s);let a=await No(n);return[a,n===a?"plain":"s256",o]}var $o=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function un(t){let e=t.headers.get(ft);if(!e||!e.match($o))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function hn(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function dn(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var Do=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ne(t){if(!Do.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ge(t){if(!t.recoveryCodes)throw new Error("@supabase/auth-js: the MFA recovery codes API is experimental and disabled by default. Enable it by passing `auth: { experimental: { recoveryCodes: true } }` to createClient (or to the GoTrueClient constructor).")}function Jt(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let s=r.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function fn(t,e){return new Proxy(t,{get:(r,s,n)=>{if(s==="__isInsecureUserWarningProxy")return!0;if(typeof s=="symbol"){let i=s.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,s,n)}return!e.value&&typeof s=="string"&&(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 may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,s,n)}})}function Cr(t){return JSON.parse(JSON.stringify(t))}var Re=t=>{if(typeof t=="object"&&t!==null){let e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(t)},pn=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function gn(t){var e;if(!tn(t))throw new Te(Re(t),0);let r;try{r=await t.json()}catch(i){throw pn.includes(t.status)?new Te(t.statusText||`HTTP ${t.status}`,t.status):new q(Re(i),i)}if(pn.includes(t.status))throw new Te(Re(r),t.status);let s,n=un(t);if(n&&n.getTime()>=Er["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?s=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(s=r.error_code),s){if(s==="weak_password")throw new mt(Re(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new P}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new mt(Re(r),t.status,r.weak_password.reasons);throw new Ft(Re(r),t.status||500,s)}var Mo=(t,e,r,s)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))};async function v(t,e,r,s){var n;let i=Object.assign({},s?.headers);i[ft]||(i[ft]=Er["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);let o=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await qo(t,e,r+a,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function qo(t,e,r,s,n,i){let o=Mo(e,s,n,i),a;try{a=await t(r,Object.assign({},o))}catch(c){throw new Te(Re(c),0)}if(a.ok||await gn(a),s?.noResolveJson)return a;try{return await a.json()}catch(c){await gn(c)}}function V(t){var e;let r=null;Bo(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Vt(t.expires_in)));let s=(e=t.user)!==null&&e!==void 0?e:typeof t?.id=="string"?t:null;return{data:{session:r,user:s},error:null}}function Ir(t){let e=V(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function ie(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function mn(t){return{data:t,error:null}}function yn(t){let{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,o=we(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},c=Object.assign({},o);return{data:{properties:a,user:c},error:null}}function xr(t){return t}function Bo(t){return!!t.access_token&&!!t.refresh_token&&!!t.expires_in}var Xt=["global","local","others"];var Ce=class{constructor({url:e="",headers:r={},fetch:s,experimental:n}){this.url=e,this.headers=r,this.fetch=zt(s),this.experimental=n??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,r=Xt[0]){if(Xt.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Xt.join(", ")}`);try{return await v(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(y(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await v(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:ie})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:r}=e,s=we(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await v(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:yn,redirectTo:r?.redirectTo})}catch(r){if(y(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await v(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ie})}catch(r){if(y(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,i,o,a,c;try{let l={nextPage:null,lastPage:0,total:0},u=await v(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:xr});if(u.error)throw u.error;let h=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,d=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return d.length>0&&(d.forEach(p=>{let g=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(p.split(";")[1].split("=")[1]);l[`${m}Page`]=g}),l.total=parseInt(f)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(l){if(y(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){ne(e);try{return await v(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ie})}catch(r){if(y(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){ne(e);try{return await v(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:ie})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){ne(e);try{return await v(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:ie})}catch(s){if(y(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){ne(e.userId);try{let{data:r,error:s}=await v(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:s}}catch(r){if(y(r))return{data:null,error:r};throw r}}async _deleteFactor(e){ne(e.userId),ne(e.id);try{return{data:await v(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(y(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,i,o,a,c;try{let l={nextPage:null,lastPage:0,total:0},u=await v(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:xr});if(u.error)throw u.error;let h=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,d=(c=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&c!==void 0?c:[];return d.length>0&&(d.forEach(p=>{let g=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(p.split(";")[1].split("=")[1]);l[`${m}Page`]=g}),l.total=parseInt(f)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(l){if(y(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(e){try{return await v(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(y(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await v(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(y(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await v(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(y(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await v(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(y(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await v(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(y(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await v(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var n;return{data:{providers:(n=s?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(y(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await v(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(y(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await v(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(y(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await v(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(y(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await v(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(y(r))return{data:null,error:r};throw r}}async _adminListPasskeys(e){ne(e.userId);try{return await v(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(y(r))return{data:null,error:r};throw r}}async _adminDeletePasskey(e){ne(e.userId),ne(e.passkeyId);try{return await v(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(y(r))return{data:null,error:r};throw r}}};function Or(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var Ho={debug:!!(globalThis&&Gt()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Yt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};function vn(){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)}}function Pr(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function wn(t){return parseInt(t,16)}function bn(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function _n(t){var e;let{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:c,resources:l,scheme:u,uri:h,version:f}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
14
+ `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let d=Pr(t.address),p=u?`${u}://${s}`:s,g=t.statement?`${t.statement}
15
+ `:"",m=`${p} wants you to sign in with your Ethereum account:
16
+ ${d}
17
+
18
+ ${g}`,w=`URI: ${h}
19
+ Version: ${f}
20
+ Chain ID: ${r}${o?`
21
+ Nonce: ${o}`:""}
22
+ Issued At: ${i.toISOString()}`;if(n&&(w+=`
23
+ Expiration Time: ${n.toISOString()}`),a&&(w+=`
24
+ Not Before: ${a.toISOString()}`),c&&(w+=`
25
+ Request ID: ${c}`),l){let _=`
26
+ Resources:`;for(let b of l){if(!b||typeof b!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${b}`);_+=`
27
+ - ${b}`}w+=_}return`${m}
28
+ ${w}`}var O=class extends Error{constructor({message:e,code:r,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}},Ie=class extends O{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function En({error:t,options:e}){var r,s,n;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new O({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new O({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new O({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new O({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new O({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new O({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new O({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new O({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(Nr(o)){if(i.rp.id!==o)return new O({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new O({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new O({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new O({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new O({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Sn({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new O({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new O({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let s=window.location.hostname;if(Nr(s)){if(r.rpId!==s)return new O({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new O({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new O({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new O({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var Ur=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},er=new Ur;function jr(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:s}=t,n=we(t,["challenge","user","excludeCredentials"]),i=me(e).buffer,o=Object.assign(Object.assign({},r),{id:me(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:i,user:o});if(s&&s.length>0){a.excludeCredentials=new Array(s.length);for(let c=0;c<s.length;c++){let l=s[c];a.excludeCredentials[c]=Object.assign(Object.assign({},l),{id:me(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return a}function Lr(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,s=we(t,["challenge","allowCredentials"]),n=me(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];i.allowCredentials[o]=Object.assign(Object.assign({},a),{id:me(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return i}function $r(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return{id:t.id,rawId:t.id,response:{attestationObject:de(new Uint8Array(t.response.attestationObject)),clientDataJSON:de(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Dr(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,s=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:de(new Uint8Array(n.authenticatorData)),clientDataJSON:de(new Uint8Array(n.clientDataJSON)),signature:de(new Uint8Array(n.signature)),userHandle:n.userHandle?de(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Nr(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function St(){var t,e;return!!(j()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Mr(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ie("Browser returned unexpected credential type",e)}:{data:null,error:new Ie("Empty credential response",e)}}catch(e){return{data:null,error:En({error:e,options:t})}}}async function qr(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ie("Browser returned unexpected credential type",e)}:{data:null,error:new Ie("Empty credential response",e)}}catch(e){return{data:null,error:Sn({error:e,options:t})}}}var Fo={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Ko={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Qt(...t){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(let n of t)if(n)for(let i in n){let o=n[i];if(o!==void 0)if(Array.isArray(o))s[i]=o;else if(r(o))s[i]=o;else if(e(o)){let a=s[i];e(a)?s[i]=Qt(a,o):s[i]=Qt(o)}else s[i]=o}return s}function Wo(t,e){return Qt(Fo,t,e||{})}function Vo(t,e){return Qt(Ko,t,e||{})}var Zt=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:s,signal:n},i){var o;try{let{data:a,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:c};let l=n??er.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){let h=s;if(h)u.name=`${u.id}:${h}`;else{let d=(await this.client.getUser()).data.user,p=((o=d?.user_metadata)===null||o===void 0?void 0:o.name)||d?.email||d?.id||"User";u.name=`${u.id}:${p}`}}u.displayName||(u.displayName=u.name)}switch(a.webauthn.type){case"create":{let u=Wo(a.webauthn.credential_options.publicKey,i?.create),{data:h,error:f}=await Mr({publicKey:u,signal:l});return h?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:h}},error:null}:{data:null,error:f}}case"request":{let u=Vo(a.webauthn.credential_options.publicKey,i?.request),{data:h,error:f}=await qr(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:l}));return h?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:h}},error:null}:{data:null,error:f}}}}catch(a){return y(a)?{data:null,error:a}:{data:null,error:new q("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new pe("rpId is required for WebAuthn authentication")};try{if(!St())return{data:null,error:new q("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!o)return{data:null,error:a};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:r,rpOrigins:s,credential_response:c.credential_response}})}catch(o){return y(o)?{data:null,error:o}:{data:null,error:new q("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new pe("rpId is required for WebAuthn registration")};try{if(!St())return{data:null,error:new q("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var h;return(h=u.data)===null||h===void 0?void 0:h.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status==="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:a};let{data:c,error:l}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:r,rpOrigins:s,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:l}}catch(o){return y(o)?{data:null,error:o}:{data:null,error:new q("Unexpected error in register",o)}}}};vn();var Go={url:Fs,storageKey:Ks,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ws,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var ze={},Tn=!1,tr=class t{get jwks(){var e,r;return(r=(e=ze[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){ze[this.storageKey]=Object.assign(Object.assign({},ze[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=ze[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){ze[this.storageKey]=Object.assign(Object.assign({},ze[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},Go),e);if(this.storageKey=i.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&j()){let o=`${this._logPrefix()} 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.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(s=i.experimental)!==null&&s!==void 0?s:{},this.admin=new Ce({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=zt(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock,Tn||(Tn=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),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),webauthn:new Zt(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(this)}},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:Gt()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Or(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Or(this.memoryStorage)),j()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Bt}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let r=await this.initializePromise,s=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let n of s)await this._notifyAllSubscribers(n.event,n.session,n.broadcast);return r}async _initialize(){var e;try{let r={},s="none";if(j()&&(r=Ar(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),j()&&this.detectSessionInUrl&&s!=="none"){let{data:n,error:i}=await this._getSessionFromURL(r,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Js(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:a}=n;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return y(r)?this._returnResult({error:r}):this._returnResult({error:new q("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{let i=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:V}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(i){if(y(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;let i=null;try{let o;if("email"in e){let{email:h,password:f,options:d}=e,p=null,g=null;this.flowType==="pkce"&&([p,g,i]=await this._getCodeChallengeAndMethod()),o=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(d?.emailRedirectTo,i),body:{email:h,password:f,data:(r=d?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:p,code_challenge_method:g},xform:V})}else if("phone"in e){let{phone:h,password:f,options:d}=e;o=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:f,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(n=d?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:V})}else throw new Ee("You must provide either an email or phone number and a password");let{data:a,error:c}=o;if(c||!a)return await z(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});let l=a.session,u=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(o){if(await z(this.storage,this.storageKey,i),y(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(e){try{let r;if("email"in e){let{email:i,password:o,options:a}=e;r=await v(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ir})}else if("phone"in e){let{phone:i,password:o,options:a}=e;r=await v(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ir})}else throw new Ee("You must provide either an email or phone number and a password");let{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){let i=new he;return this._returnResult({data:{user:null,session:null},error:i})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(r){if(y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e,r){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,r)):this._exchangeCodeForSession(e,r)}async signInWithWeb3(e){let{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,o,a,c,l,u,h,f;let d,p;if("message"in e)d=e.message,p=e.signature;else{let{chain:g,wallet:m,statement:w,options:_}=e,b;if(j())if(typeof m=="object")b=m;else{let ce=window;if("ethereum"in ce&&typeof ce.ethereum=="object"&&"request"in ce.ethereum&&typeof ce.ethereum.request=="function")b=ce.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof m!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=m}let A=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href),B=await b.request({method:"eth_requestAccounts"}).then(ce=>ce).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!B||B.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let C=Pr(B[0]),x=(s=_?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!x){let ce=await b.request({method:"eth_chainId"});x=wn(ce)}let Qe={domain:A.host,address:C,statement:w,uri:A.href,version:"1",chainId:x,nonce:(n=_?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(o=(i=_?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=_?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(c=_?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(l=_?.signInWithEthereum)===null||l===void 0?void 0:l.requestId,resources:(u=_?.signInWithEthereum)===null||u===void 0?void 0:u.resources};d=_n(Qe),p=await b.request({method:"personal_sign",params:[bn(d),C]})}try{let{data:g,error:m}=await v(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:p},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:V});if(m)throw m;if(!g||!g.session||!g.user){let w=new he;return this._returnResult({data:{user:null,session:null},error:w})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:m})}catch(g){if(y(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,s,n,i,o,a,c,l,u,h,f,d;let p,g;if("message"in e)p=e.message,g=e.signature;else{let{chain:m,wallet:w,statement:_,options:b}=e,A;if(j())if(typeof w=="object")A=w;else{let C=window;if("solana"in C&&typeof C.solana=="object"&&("signIn"in C.solana&&typeof C.solana.signIn=="function"||"signMessage"in C.solana&&typeof C.solana.signMessage=="function"))A=C.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof w!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");A=w}let B=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in A&&A.signIn){let C=await A.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},b?.signInWithSolana),{version:"1",domain:B.host,uri:B.href}),_?{statement:_}:null)),x;if(Array.isArray(C)&&C[0]&&typeof C[0]=="object")x=C[0];else if(C&&typeof C=="object"&&"signedMessage"in C&&"signature"in C)x=C;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in x&&"signature"in x&&(typeof x.signedMessage=="string"||x.signedMessage instanceof Uint8Array)&&x.signature instanceof Uint8Array)p=typeof x.signedMessage=="string"?x.signedMessage:new TextDecoder().decode(x.signedMessage),g=x.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in A)||typeof A.signMessage!="function"||!("publicKey"in A)||typeof A!="object"||!A.publicKey||!("toBase58"in A.publicKey)||typeof A.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${B.host} wants you to sign in with your Solana account:`,A.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${B.href}`,`Issued At: ${(n=(s=b?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=b?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${b.signInWithSolana.notBefore}`]:[],...!((o=b?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${b.signInWithSolana.expirationTime}`]:[],...!((a=b?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${b.signInWithSolana.chainId}`]:[],...!((c=b?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${b.signInWithSolana.nonce}`]:[],...!((l=b?.signInWithSolana)===null||l===void 0)&&l.requestId?[`Request ID: ${b.signInWithSolana.requestId}`]:[],...!((h=(u=b?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||h===void 0)&&h.length?["Resources",...b.signInWithSolana.resources.map(x=>`- ${x}`)]:[]].join(`
29
+ `);let C=await A.signMessage(new TextEncoder().encode(p),"utf8");if(!C||!(C instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=C}}try{let{data:m,error:w}=await v(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:de(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(d=e.options)===null||d===void 0?void 0:d.captchaToken}}:null),xform:V});if(w)throw w;if(!m||!m.session||!m.user){let _=new he;return this._returnResult({data:{user:null,session:null},error:_})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:w})}catch(m){if(y(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async _exchangeCodeForSession(e,r){let s=r?.flowId!=null,n=s?Et(r?.flowId):j()?Et(Ar(window.location.href)[ue]):null;s&&!n&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",r?.flowId);let{verifier:i,flowId:o}=s&&!n?{verifier:null,flowId:null}:await on(this.storage,this.storageKey,n),[a,c]=(i??"").split("/");try{if(!a&&this.flowType==="pkce")throw new Kt;let{data:l,error:u}=await v(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:a},xform:V});if(await z(this.storage,this.storageKey,o),u)throw u;if(!l||!l.session||!l.user){let h=new he;return this._returnResult({data:{user:null,session:null,redirectType:null},error:h})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l.session)),this._returnResult({data:Object.assign(Object.assign({},l),{redirectType:c??null}),error:u})}catch(l){if(await z(this.storage,this.storageKey,o),y(l))return this._returnResult({data:{user:null,session:null,redirectType:null},error:l});throw l}}async signInWithIdToken(e){try{let{options:r,provider:s,token:n,access_token:i,nonce:o}=e,a=await v(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:V}),{data:c,error:l}=a;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!c||!c.session||!c.user){let u=new he;return this._returnResult({data:{user:null,session:null},error:u})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:l})}catch(r){if(y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,o;let a=null;try{if("email"in e){let{email:c,options:l}=e,u=null,h=null;this.flowType==="pkce"&&([u,h,a]=await this._getCodeChallengeAndMethod());let{error:f}=await v(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:h},redirectTo:this._maybeAppendFlowIdToRedirect(l?.emailRedirectTo,a)});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in e){let{phone:c,options:l}=e,{data:u,error:h}=await v(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:h})}throw new Ee("You must provide either an email or phone number.")}catch(c){if(await z(this.storage,this.storageKey,a),y(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await v(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:V});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let c=o.session,l=o.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(n){if(y(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i;let o=null;try{let a=null,c=null;this.flowType==="pkce"&&([a,c,o]=await this._getCodeChallengeAndMethod());let l=await v(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:this._maybeAppendFlowIdToRedirect((r=e.options)===null||r===void 0?void 0:r.redirectTo,o)}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:c}),headers:this.headers,xform:mn});return!((n=l.data)===null||n===void 0)&&n.url&&j()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(a){if(await z(this.storage,this.storageKey,o),y(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new P;let{error:n}=await v(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(y(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let r=null;try{let s=`${this.url}/resend`;if("email"in e){let{email:n,type:i,options:o}=e,a=null,c=null;this.flowType==="pkce"&&([a,c,r]=await this._getCodeChallengeAndMethod());let{error:l}=await v(this.fetch,"POST",s,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:a,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,r)});return l&&await z(this.storage,this.storageKey,r),this._returnResult({data:{user:null,session:null},error:l})}else if("phone"in e){let{phone:n,type:i,options:o}=e,{data:a,error:c}=await v(this.fetch,"POST",s,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a?.message_id},error:c})}throw new Ee("You must provide either an email or phone number and a type")}catch(s){if(await z(this.storage,this.storageKey,r),y(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}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=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.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 r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await D(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(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*1e3-Date.now()<Ht:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s)return{data:{session:await this._hydrateSessionUser(e)},error:null};let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i){let o=await D(this.storage,this.storageKey);return o&&this._isValidSession(o)&&o.expires_at&&o.expires_at*1e3>Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(o)},error:null}):this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(e){if(this.userStorage){let r=await D(this.userStorage,this.storageKey+"-user");e.user=r?.user?r.user:Jt()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let r={value:this.suppressGetSessionWarning};e.user=fn(e.user,r),r.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r;return this.lock!=null?r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):r=await this._getUser(),r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await v(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ie}):await this._useSession(async r=>{var s,n,i;let{data:o,error:a}=r;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new P}:await v(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:ie})})}catch(r){if(y(r))return yt(r)&&await this._removeSession(),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r)):await this._updateUser(e,r)}async _updateUser(e,r={}){let s=null;try{return await this._useSession(async n=>{let{data:i,error:o}=n;if(o)throw o;if(!i.session)throw new P;let a=i.session,c=null,l=null;this.flowType==="pkce"&&e.email!=null&&([c,l,s]=await this._getCodeChallengeAndMethod());let{data:u,error:h}=await v(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r?.emailRedirectTo,s),body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:l}),jwt:a.access_token,xform:ie});if(h)throw h;return a.user=u.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(n){if(await z(this.storage,this.storageKey,s),y(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new P;let r=Date.now()/1e3,s=r,n=!0,i=null,{payload:o}=_t(e.access_token);if(o.exp&&(s=o.exp,n=s<=r),n){let{data:a,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!a)return{data:{user:null,session:null},error:null};i=a}else{let{data:a,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(y(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new P;let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(y(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!j())throw new Se("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Se(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new pt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Se("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new pt("No code detected.");let{data:b,error:A}=await this._exchangeCodeForSession(e.code,{flowId:e[ue]});if(A)throw A;let B=new URL(window.location.href);return B.searchParams.delete("code"),B.searchParams.delete(ue),window.history.replaceState(window.history.state,"",B.toString()),{data:{session:b.session,redirectType:(s=b.redirectType)!==null&&s!==void 0?s:null},error:null}}let{provider_token:n,provider_refresh_token:i,access_token:o,refresh_token:a,expires_in:c,expires_at:l,token_type:u}=e;if(!o||!c||!a||!u)throw new Se("No session defined in URL");let h=Math.round(Date.now()/1e3),f=parseInt(c),d=h+f;l&&(d=parseInt(l));let p=d-h;p*1e3<=re&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${f}s`);let g=d-f;h-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,d,h):h-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,d,h);let{data:m,error:w}=await this._getUser(o);if(w)throw w;let _={provider_token:n,provider_refresh_token:i,access_token:o,expires_in:f,expires_at:d,refresh_token:a,token_type:u,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:_,redirectType:e.type},error:null})}catch(n){if(y(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let r=Et(e[ue]);return r&&await D(this.storage,Ae(this.storageKey,r))?!0:!!await D(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;let n=async()=>{await this._removeSession()},{data:i,error:o}=r;if(o&&!yt(o))return this._returnResult({error:o});let a=(s=i.session)===null||s===void 0?void 0:s.access_token;if(a){let{error:c}=await this.admin.signOut(a,e);if(c&&!(Sr(c)&&(c.status===404||c.status===401||c.status===403)||yt(c)))return e!=="others"&&await n(),this._returnResult({error:c})}return e!=="others"&&await n(),this._returnResult({error:null})})}onAuthStateChange(e){let r=en(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)}):await this._emitInitialSession(r)))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{let{data:{session:i},error:o}=r;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){if(await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),Tr(i))return;yt(i)||vt(i)||Sr(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null,i=null;this.flowType==="pkce"&&([s,n,i]=await this._getCodeChallengeAndMethod(!0));try{return await v(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(r.redirectTo,i)})}catch(o){if(await z(this.storage,this.storageKey,i),y(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var e;try{let{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;let s=null;try{let{data:n,error:i}=await this._useSession(async o=>{var a,c,l,u,h;let{data:f,error:d}=o;if(d)throw d;let{url:p,flowId:g}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return s=g,await v(this.fetch,"GET",p,{headers:this.headers,jwt:(h=(u=f.session)===null||u===void 0?void 0:u.access_token)!==null&&h!==void 0?h:void 0})});if(i)throw i;return j()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url,flowId:s},error:null})}catch(n){if(y(n))return this._returnResult({data:{provider:e.provider,url:null,flowId:s},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{let{error:n,data:{session:i}}=r;if(n)throw n;let{options:o,provider:a,token:c,access_token:l,nonce:u}=e,h=await v(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:a,id_token:c,access_token:l,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:V}),{data:f,error:d}=h;return d?this._returnResult({data:{user:null,session:null},error:d}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new he}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:d}))}catch(n){if(await z(this.storage,this.storageKey,null),y(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;let{data:i,error:o}=r;if(o)throw o;return await v(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r="#_refreshAccessToken()";this._debug(r,"begin");try{let s=Date.now();return await sn(async n=>(n>0&&await rn(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await v(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:V})),(n,i)=>{let o=200*Math.pow(2,n);return i&&vt(i)&&Date.now()+o-s<re})}catch(s){if(this._debug(r,"error",s),y(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let{url:s,flowId:n}=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),j()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s,flowId:n},error:null}}async _recoverAndRefresh(){var e,r;let s="#_recoverAndRefresh()";this._debug(s,"begin");try{let n=await D(this.storage,this.storageKey);if(n&&this.userStorage){let o=await D(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:n.user},await se(this.userStorage,this.storageKey+"-user",o)),n.user=(e=o?.user)!==null&&e!==void 0?e:Jt()}else if(n&&!n.user&&!n.user){let o=await D(this.storage,this.storageKey+"-user");o&&o?.user?(n.user=o.user,await H(this.storage,this.storageKey+"-user"),await se(this.storage,this.storageKey,n)):n.user=Jt()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}let i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Ht;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${Ht}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:o}=await this._callRefreshToken(n.refresh_token);o&&(Tr(o)?this._debug(s,"refresh discarded by commit guard",o):this._debug(s,"refresh failed",o))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(n.access_token);!a&&o?.user?(n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(s,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),vt(n)?console.warn(n):console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new P;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===e&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning cached failure (cooldown active)"),this.lastRefreshFailure.result;let n="#_callRefreshToken()";this._debug(n,"begin");try{this.refreshingDeferred=new wt,this.refreshingDeferred.promise.then(void 0,()=>{});let i=await D(this.storage,this.storageKey),{data:o,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!o.session)throw new P;let c=await D(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(n,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});let f={data:null,error:new gt};return this.refreshingDeferred.resolve(f),f}let u=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==u){this._debug(n,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await H(this.storage,this.storageKey),this.userStorage&&await H(this.userStorage,this.storageKey+"-user");let f={data:null,error:new gt};return this.refreshingDeferred.resolve(f),f}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let h={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(h),h}catch(i){if(this._debug(n,"error",i),y(i)){let o={data:null,error:i};if(!vt(i)){let a=await D(this.storage,this.storageKey);!!(a?.expires_at&&a.expires_at*1e3>Date.now())?this._debug(n,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+Hs},(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){if(this._pendingInitNotifications!==null&&s){this._pendingInitNotifications.push({event:e,session:r,broadcast:s});return}let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;let r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await se(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let i=Cr(n);await se(this.storage,this.storageKey,i)}else{let n=Cr(r);await se(this.storage,this.storageKey,n)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await H(this.storage,this.storageKey),await an(this.storage,this.storageKey),await H(this.storage,this.storageKey+"-user"),this.userStorage&&await H(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&j()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),re);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/re);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${re}ms, refresh threshold is ${Ve} ticks`),n<=Ve&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof Yt)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async r=>{let{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/re);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${re}ms, refresh threshold is ${Ve} ticks`),n<=Ve&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!j()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;if(this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(r,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){let n=s?.redirectTo,i=null,o=null,a=null;this.flowType==="pkce"&&([i,o,a]=await this._getCodeChallengeAndMethod(),n=this._maybeAppendFlowIdToRedirect(n,a));let c=[`provider=${encodeURIComponent(r)}`];if(n&&c.push(`redirect_to=${encodeURIComponent(n)}`),s?.scopes&&c.push(`scopes=${encodeURIComponent(s.scopes)}`),i!=null&&o!=null){let l=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(l.toString())}if(s?.queryParams){let l=new URLSearchParams(s.queryParams);c.push(l.toString())}return s?.skipBrowserRedirect&&c.push(`skip_http_redirect=${s.skipBrowserRedirect}`),{url:`${e}?${c.join("&")}`,flowId:a}}_maybeAppendFlowIdToRedirect(e,r){return!e||!r||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:cn(e,r)}async _getCodeChallengeAndMethod(e=!1){return ln(this.storage,this.storageKey,e,r=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",r))}async _unenroll(e){try{return await this._useSession(async r=>{var s;let{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await v(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:l}=await v(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return l?this._returnResult({data:null,error:l}):(e.factorType==="totp"&&c.type==="totp"&&(!((n=c?.totp)===null||n===void 0)&&n.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){let r=async()=>{try{return await this._useSession(async s=>{var n;let{data:i,error:o}=s;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?$r(e.webauthn.credential_response):Dr(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:l}=await v(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:l}))})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challenge(e){let r=async()=>{try{return await this._useSession(async s=>{var n;let{data:i,error:o}=s;if(o)return this._returnResult({data:null,error:o});let a=await v(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(a.error)return a;let{data:c}=a;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:jr(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:Lr(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challengeAndVerify(e){let{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};let n={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let i of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&i.factor_type in n&&Array.isArray(n[i.factor_type])&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{let{payload:d}=_t(e),p=null;d.aal&&(p=d.aal);let g=p,{data:{user:m},error:w}=await this.getUser(e);if(w)return this._returnResult({data:null,error:w});((s=(r=m?.factors)===null||r===void 0?void 0:r.filter(A=>A.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(g="aal2");let b=d.amr||[];return{data:{currentLevel:p,nextLevel:g,currentAuthenticationMethods:b},error:null}}catch(d){if(y(d))return this._returnResult({data:null,error:d});throw d}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=_t(o.access_token),l=null;c.aal&&(l=c.aal);let u=l;((i=(n=o.user.factors)===null||n===void 0?void 0:n.filter(d=>d.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");let f=c.amr||[];return{data:{currentLevel:l,nextLevel:u,currentAuthenticationMethods:f},error:null}}async _getRecoveryCodesStatus(){Ge(this.experimental);try{return await this._useSession(async e=>{var r;let{data:s,error:n}=e;if(n)return this._returnResult({data:null,error:n});let{data:i,error:o}=await v(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){Ge(this.experimental);try{return await this._useSession(async r=>{var s;let{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});let{data:o,error:a}=await v(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return a?this._returnResult({data:null,error:a}):this._returnResult({data:o,error:null})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _verifyRecoveryCode(e){Ge(this.experimental);let r=async()=>{try{return await this._useSession(async s=>{var n;let{data:i,error:o}=s;if(o)return this._returnResult({data:null,error:o});let{data:a,error:c}=await v(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(c)return this._returnResult({data:null,error:c});let l=Object.assign({expires_at:Vt(a.expires_in)},a);return await this._saveSession(l),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:a,error:null})})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _regenerateRecoveryCodes(){Ge(this.experimental);try{return await this._useSession(async e=>{var r;let{data:s,error:n}=e;if(n)return this._returnResult({data:null,error:n});let{data:i,error:o}=await v(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){Ge(this.experimental);try{return await this._useSession(async e=>{var r;let{data:s,error:n}=e;if(n)return this._returnResult({data:null,error:n});let{data:i,error:o}=await v(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await v(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new P})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new P});let o=await v(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&j()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new P});let o=await v(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&j()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await v(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new P})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await v(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new P})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(a=>a.kid===e);if(s)return s;let n=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+zs>n)return s;let{data:i,error:o}=await v(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){let{data:d,error:p}=await this.getSession();if(p||!d.session)return this._returnResult({data:null,error:p});s=d.session.access_token}let{header:n,payload:i,signature:o,raw:{header:a,payload:c}}=_t(s);if(!r?.allowExpired)try{hn(i.exp)}catch(d){throw new ge(d instanceof Error?d.message:"JWT validation failed")}let l=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!l){let{error:d}=await this.getUser(s);if(d)throw d;return{data:{claims:i,header:n,signature:o},error:null}}let u=dn(n.alg),h=await crypto.subtle.importKey("jwk",l,u,!0,["verify"]);if(!await crypto.subtle.verify(u,h,o,Zs(`${a}.${c}`)))throw new ge("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n,i;try{if(!St())return this._returnResult({data:null,error:new q("Browser does not support WebAuthn",null)});let{data:o,error:a}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}});if(a||!o)return this._returnResult({data:null,error:a});let c=Lr(o.options),l=(n=(s=e?.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:er.createNewAbortSignal(),{data:u,error:h}=await qr({publicKey:c,signal:l,mediation:(i=e?.options)===null||i===void 0?void 0:i.mediation});if(h||!u)return this._returnResult({data:null,error:h??new q("WebAuthn ceremony failed",null)});let f=Dr(u);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:f})}catch(o){if(y(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(e){var r,s;try{if(!St())return this._returnResult({data:null,error:new q("Browser does not support WebAuthn",null)});let{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});let o=jr(n.options),a=(s=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:er.createNewAbortSignal(),{data:c,error:l}=await Mr({publicKey:o,signal:a});if(l||!c)return this._returnResult({data:null,error:l??new q("WebAuthn ceremony failed",null)});let u=$r(c);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:u})}catch(n){if(y(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new P});let{data:n,error:i}=await v(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});let{data:i,error:o}=await v(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;try{let{data:s,error:n}=await v(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})}catch(s){if(y(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){try{let{data:r,error:s}=await v(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:V});return s?this._returnResult({data:null,error:s}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new P});let{data:n,error:i}=await v(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});let{data:i,error:o}=await v(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new P});let{error:i}=await v(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}};tr.nextInstanceID={};var Br=tr;var zo=Br,Hr=zo;var Jo="2.118.0",Tt="",nr;if(typeof Deno<"u")Tt="deno",nr=(rr=Deno.version)===null||rr===void 0?void 0:rr.deno;else if(typeof document<"u")Tt="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")Tt="react-native";else{Tt="node";let t=globalThis.process;nr=t==null||(sr=t.version)===null||sr===void 0?void 0:sr.replace(/^v/,"")}var rr,sr,Pn=[`runtime=${Tt}`];nr&&Pn.push(`runtime-version=${nr}`);var Xo={"X-Client-Info":`supabase-js/${Jo}; ${Pn.join("; ")}`},Yo={headers:Xo},Qo={schema:"public"},Zo={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ea={},ta={enabled:!1,respectSamplingDecision:!0};function ra(t){if(!t||typeof t!="string")return null;let e=t.split("-");if(e.length!==4)return null;let[r,s,n,i]=e;if(r.length!==2||s.length!==32||n.length!==16||i.length!==2)return null;let o=/^[0-9a-f]+$/i;return!o.test(r)||!o.test(s)||!o.test(n)||!o.test(i)||s==="00000000000000000000000000000000"||n==="0000000000000000"?null:{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function sa(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(let s of e)try{if(typeof s=="string"){if(na(r.hostname,s))return!0}else if(s instanceof RegExp){if(s.test(r.hostname))return!0}else if(typeof s=="function"&&s(r))return!0}catch{continue}return!1}function na(t,e){if(e===t)return!0;if(e.startsWith("*.")){let r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function ia(t){let e=[];try{let r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function kt(t){"@babel/helpers - typeof";return kt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},kt(t)}function oa(t,e){if(kt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(kt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function aa(t){var e=oa(t,"string");return kt(e)=="symbol"?e:e+""}function ca(t,e,r){return(e=aa(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function kn(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function N(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?kn(Object(r),!0).forEach(function(s){ca(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):kn(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var la=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),ua=()=>Headers,Nn=t=>t.startsWith("sb_publishable_")||t.startsWith("sb_secret_"),ha="sb_temp_",An=new Set,da=t=>{var e,r;if(!t.startsWith("sb_")||Nn(t)||t.startsWith(ha))return;let s=(e=(r=t.match(/^sb_[a-zA-Z0-9]+_/))===null||r===void 0?void 0:r[0])!==null&&e!==void 0?e:"unknown";An.has(s)||(An.add(s),console.warn("@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is; if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type."))},Rn=(t,e,r,s,n,i)=>{let o=la(s),a=ua(),c=n?.enabled===!0,l=n?.respectSamplingDecision!==!1,u=c?ia(e):null,h=!(i?.omitApiKeyAsBearer&&Nn(t));return async(f,d)=>{let p=await r(),g=new a(d?.headers);if(g.has("apikey")||g.set("apikey",t),!g.has("Authorization")){let m=p??(h?t:null);m&&g.set("Authorization",`Bearer ${m}`)}if(u){let m=fa(f,u,l);m&&(m.traceparent&&!g.has("traceparent")&&g.set("traceparent",m.traceparent),m.tracestate&&!g.has("tracestate")&&g.set("tracestate",m.tracestate),m.baggage&&!g.has("baggage")&&g.set("baggage",m.baggage))}return o(f,N(N({},d),{},{headers:g}))}},Cn=!1,In=!1;function fa(t,e,r){let s=ns();if(!s)return Cn||(Cn=!0,console.warn("@supabase/supabase-js: tracePropagation is enabled but the tracing runtime is not loaded, so trace headers will not be attached. Add `import '@supabase/supabase-js/tracing'` at your application entry point (requires the OpenTelemetry API package to be installed). The CDN/UMD build does not support trace propagation.")),null;if(!sa(typeof t=="string"||t instanceof URL?t:t.url,e))return null;let n=s();if(!n||!n.traceparent){var i;if(!(n==null||(i=n.carrierKeys)===null||i===void 0)&&i.length&&!In){In=!0;let o=n.carrierKeys.includes("sentry-trace")?" Sentry detected: set `propagateTraceparent: true` in Sentry.init() to emit it.":" Configure your tracing SDK to emit W3C trace context on outgoing requests.";console.warn(`@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its propagator wrote [${n.carrierKeys.join(", ")}] and no W3C traceparent header, so trace headers will not be attached.`+o)}return null}if(r){let o=ra(n.traceparent);if(o&&!o.isSampled)return{traceparent:n.traceparent}}return n}function xn(t){return typeof t=="boolean"?{enabled:t}:t}function pa(t){return t.endsWith("/")?t:t+"/"}var On=!1;function ga(t){On||typeof t!="object"||t===null||!("schema"in t)||t.schema===void 0||(On=!0,console.warn(`@supabase/supabase-js: The "schema" option must be nested under "db", e.g. createClient(url, key, { db: { schema: 'myschema' } }). A top-level "schema" is ignored and queries go to the default schema.`))}function ma(t,e){var r,s,n,i,o,a;let{db:c,auth:l,realtime:u,global:h}=t,{db:f,auth:d,realtime:p,global:g}=e,m=xn(t.tracePropagation),w=xn(e.tracePropagation),_={db:N(N({},f),c),auth:N(N({},d),l),realtime:N(N({},p),u),storage:{},global:N(N(N({},g),h),{},{headers:N(N({},(r=g?.headers)!==null&&r!==void 0?r:{}),(s=h?.headers)!==null&&s!==void 0?s:{})}),tracePropagation:{enabled:(n=(i=m?.enabled)!==null&&i!==void 0?i:w?.enabled)!==null&&n!==void 0?n:!1,respectSamplingDecision:(o=(a=m?.respectSamplingDecision)!==null&&a!==void 0?a:w?.respectSamplingDecision)!==null&&o!==void 0?o:!0},accessToken:async()=>""};return t.accessToken?_.accessToken=t.accessToken:delete _.accessToken,_}function ya(t){let e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(pa(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var va=class extends Hr{constructor(t){super(t)}},wa=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;let i=ya(t);if(!e)throw new Error("supabaseKey is required.");da(e),ga(r),this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);let o=`sb-${i.hostname.split(".")[0]}-auth-token`,a={db:Qo,realtime:ea,auth:N(N({},Zo),{},{storageKey:o}),global:Yo,tracePropagation:ta},c=ma(r??{},a);if(this.settings=c,this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(u,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var l;this.auth=this._initSupabaseAuthClient((l=c.auth)!==null&&l!==void 0?l:{},this.headers,c.global.fetch)}this.fetch=Rn(e,t,this._getSessionToken.bind(this),c.global.fetch,c.tracePropagation),this.functionsFetch=Rn(e,t,this._getSessionToken.bind(this),c.global.fetch,c.tracePropagation,{omitApiKeyAsBearer:!0}),this.realtime=this._initRealtimeClient(N({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new gs(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit,retry:c.db.retry}),this.storage=new Bs(this.storageUrl.href,this.headers,this.fetch,r?.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new tt(this.functionsUrl.href,{headers:this.headers,customFetch:this.functionsFetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}getOpenApiSpec(){return this.rest.getOpenApiSpec()}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getSessionToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:null}async _getAccessToken(){var t=this,e;return(e=await t._getSessionToken())!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:o,lock:a,debug:c,throwOnError:l,experimental:u,lockAcquireTimeout:h,skipAutoInitialize:f},d,p){let g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new va({url:this.authUrl.href,headers:N(N({},g),d),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:o,lock:a,debug:c,throwOnError:l,experimental:u,fetch:p,lockAcquireTimeout:h,skipAutoInitialize:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Be(this.realtimeUrl.href,N(N({},t),{},{params:N(N({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN"||t==="INITIAL_SESSION")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},Un=(t,e,r)=>new wa(t,e,r);function ba(){if(typeof window<"u"||globalThis.Deno!==void 0)return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=20:!1}ba()&&console.warn("\u26A0\uFE0F Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");var M=[];for(let t=0;t<256;++t)M.push((t+256).toString(16).slice(1));function jn(t,e=0){return(M[t[e+0]]+M[t[e+1]]+M[t[e+2]]+M[t[e+3]]+"-"+M[t[e+4]]+M[t[e+5]]+"-"+M[t[e+6]]+M[t[e+7]]+"-"+M[t[e+8]]+M[t[e+9]]+"-"+M[t[e+10]]+M[t[e+11]]+M[t[e+12]]+M[t[e+13]]+M[t[e+14]]+M[t[e+15]]).toLowerCase()}var Fr,_a=new Uint8Array(16);function Kr(){if(!Fr){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Fr=crypto.getRandomValues.bind(crypto)}return Fr(_a)}var Ea=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Wr={randomUUID:Ea};function Sa(t,e,r){if(Wr.randomUUID&&!e&&!t)return Wr.randomUUID();t=t||{};let s=t.random??t.rng?.()??Kr();if(s.length<16)throw new Error("Random bytes length must be >= 16");if(s[6]=s[6]&15|64,s[8]=s[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let n=0;n<16;++n)e[r+n]=s[n];return e}return jn(s)}var Vr=Sa;var Ta="https://api.convokit.app",S=class extends Error{constructor(e,r={}){super(e,r.cause===void 0?void 0:{cause:r.cause});R(this,"status");R(this,"responseBody");R(this,"code");this.name="ConvoKitError",this.status=r.status,this.responseBody=r.responseBody,this.code=r.code}};function ka(t){let e=t.trim().replace(/\/+$/,"");if(!e)throw new S("backendUrl is required",{code:"INVALID_CONFIG"});return e}function Ln(t,e){if(typeof e=="object"&&e!==null){let r=e;if(typeof r.error=="string")return r.error;if(typeof r.message=="string")return r.message}return typeof e=="string"&&e.trim()?e:`ConvoKit request failed with status ${t}`}function $n(t){if(typeof t=="object"&&t!==null){let e=t.code;if(typeof e=="string"&&e.trim())return e}return"HTTP_ERROR"}async function Dn(t){if(t.status===204)return;let e=await t.text();if(!e)return;if((t.headers.get("content-type")??"").includes("application/json"))try{return JSON.parse(e)}catch{return e}return e}var Aa=class{constructor(t){R(this,"backendUrl");R(this,"clientId");R(this,"fetchImplementation");R(this,"headersProvider");if(this.backendUrl=ka(t.backendUrl),this.clientId=t.clientId.trim(),!this.clientId)throw new S("clientId is required",{code:"INVALID_CONFIG"});let e=t.fetchImplementation??globalThis.fetch;if(typeof e!="function")throw new S("A Fetch API implementation is required",{code:"FETCH_UNAVAILABLE"});this.fetchImplementation=e.bind(globalThis),this.headersProvider=t.headersProvider}async request(t,e={}){let r=new URL(`${this.backendUrl}${t}`);for(let[a,c]of Object.entries(e.query??{}))c!=null&&r.searchParams.set(a,String(c));let s={"x-client-id":this.clientId,...e.authenticated===!1?{}:this.headersProvider(),...e.headers},n;e.body!==void 0&&(typeof e.body=="string"||e.body instanceof ArrayBuffer||ArrayBuffer.isView(e.body)||typeof Blob<"u"&&e.body instanceof Blob?n=e.body:(s["Content-Type"]??(s["Content-Type"]="application/json"),n=JSON.stringify(e.body)));let i;try{i=await this.fetchImplementation(r,{method:e.method??"GET",headers:s,...n===void 0?{}:{body:n}})}catch(a){throw new S("Could not reach the ConvoKit backend",{code:"NETWORK_ERROR",cause:a})}let o=await Dn(i);if(!i.ok)throw new S(Ln(i.status,o),{status:i.status,responseBody:o,code:$n(o)});return o}async requestRaw(t,e={}){let r=new URL(`${this.backendUrl}${t}`);for(let[n,i]of Object.entries(e.query??{}))i!=null&&r.searchParams.set(n,String(i));let s;try{s=await this.fetchImplementation(r,{method:e.method??"GET",headers:{"x-client-id":this.clientId,...e.authenticated===!1?{}:this.headersProvider(),...e.headers}})}catch(n){throw new S("Could not reach the ConvoKit backend",{code:"NETWORK_ERROR",cause:n})}if(!s.ok){let n=await Dn(s);throw new S(Ln(s.status,n),{status:s.status,responseBody:n,code:$n(n)})}return s}};function Xr(){return Vr()}var Mn=2147483647;function Ra(t,e){if(!Number.isInteger(t)||t<0||t>Mn)throw new S(`${e} must be an integer between 0 and ${Mn}`,{code:"INVALID_ARGUMENT"});return t}function qn(t){let e=U(L(t).data);if(typeof e.messageId!="string"||typeof e.emoji!="string"||typeof e.changed!="boolean")throw new TypeError("Invalid ConvoKit reaction mutation");return{messageId:e.messageId,emoji:e.emoji,changed:e.changed}}function Ca(t){let e=L(t).data;if(!Array.isArray(e))throw new TypeError("Invalid ConvoKit reaction summaries");return e.map(r=>{let s=U(r);if(typeof s.messageId!="string"||!Array.isArray(s.reactions)||typeof s.hasMore!="boolean")throw new TypeError("Invalid ConvoKit reaction summary");return{messageId:s.messageId,hasMore:s.hasMore,reactions:s.reactions.map(n=>{let i=U(n);if(typeof i.emoji!="string"||typeof i.count!="number"||!Number.isInteger(i.count)||i.count<1||typeof i.reactedByMe!="boolean")throw new TypeError("Invalid ConvoKit reaction count");return{emoji:i.emoji,count:i.count,reactedByMe:i.reactedByMe}})}})}function Ia(t){let e=U(t);if(!Array.isArray(e.data)||e.nextCursor!==null&&typeof e.nextCursor!="string")throw new TypeError("Invalid ConvoKit reaction users page");return{data:e.data.map(r=>{let s=U(r);if(typeof s.userId!="string")throw new TypeError("Invalid ConvoKit reaction user");return{userId:s.userId,name:Y(s.name),imageUrl:Y(s.imageUrl),reactedAt:ve(s.reactedAt)}}),nextCursor:e.nextCursor}}function U(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:t}function $(t,e=""){return typeof t=="string"?t:e}function Y(t){return typeof t=="string"?t:null}function ve(t){let e=new Date($(t));if(Number.isNaN(e.getTime()))throw new TypeError(`Invalid ConvoKit date: ${String(t)}`);return e}function ae(t){return t==null?null:ve(t)}function oe(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()!==""){let e=Number(t);if(Number.isFinite(e))return e}}function Bn(t){let e=U(t);return{id:$(e.id),appId:$(e.appId??e.app_id),name:Y(e.name??e.display_name),imageUrl:Y(e.imageUrl??e.image_url),lastSeenAt:ae(e.lastSeenAt??e.last_seen_at),createdAt:ae(e.createdAt??e.created_at),updatedAt:ae(e.updatedAt??e.updated_at)}}function ar(t){if(t==null)return null;let e=U(t),r=e.messageId??e.message_id;if(typeof r!="string"||!r.trim())throw new TypeError("Invalid ConvoKit read position: missing messageId");return{messageId:r,createdAt:ve(e.createdAt??e.created_at)}}function xa(t){let e=U(t),r=$(e.id);return{id:r,appUserId:$(e.appUserId??e.app_user_id,r),name:$(e.name??e.display_name),imageUrl:Y(e.imageUrl??e.image_url),role:$(e.role,"READ_WRITE"),lastReadAt:ae(e.lastReadAt??e.last_read_at),readPosition:ar(e.readPosition??e.read_position)}}function At(t){let e=U(t),r=Y(e.title),s=e.participants??e.members,n=Array.isArray(s)?s.map(xa):[];return{id:$(e.id),title:r,imageUrl:Y(e.imageUrl??e.image_url),appId:$(e.appId??e.app_id),displayTitle:$(e.displayTitle??e.display_title,r??"Conversation"),description:Y(e.description),participants:n,createdAt:ve(e.createdAt??e.created_at),updatedAt:ve(e.updatedAt??e.updated_at)}}function Yr(t){if(t==null)return 0;let e=oe(t);if(e===void 0||!Number.isInteger(e)||e<0)throw new TypeError(`Invalid ConvoKit private state version: ${String(t)}`);return e}function Oa(t){if(t==null)return null;let e=U(t);return{role:$(e.role,"READ_WRITE"),lastReadAt:ae(e.lastReadAt??e.last_read_at),readPosition:ar(e.readPosition??e.read_position),unreadMarkedAt:ae(e.unreadMarkedAt??e.unread_marked_at),privateStateVersion:Yr(e.privateStateVersion??e.private_state_version)}}function Jn(t){let e=U(t),r=e.conversationId??e.conversation_id;if(typeof r!="string"||!r.trim())throw new TypeError("Invalid ConvoKit private state: missing conversationId");return{conversationId:r,unreadMarkedAt:ae(e.unreadMarkedAt??e.unread_marked_at),privateStateVersion:Yr(e.privateStateVersion??e.private_state_version)}}function Pa(t){return{...Jn(t),cleared:or(U(t).cleared,"cleared")}}function Na(t){let e=U(t),r=$(e.type),s={...typeof e.id=="string"?{id:e.id}:{},...typeof e.name=="string"?{name:e.name}:{},...oe(e.sortOrder??e.sort_order)!==void 0?{sortOrder:oe(e.sortOrder??e.sort_order)}:{}};if(r==="image"||r==="file")return{...s,type:r,url:$(e.url),...oe(e.size)!==void 0?{size:oe(e.size)}:{},...typeof e.metadata=="object"&&e.metadata!==null?{metadata:e.metadata}:{}};let n=U(e.metadata);if(r==="location")return{...s,type:r,metadata:{...n,lat:oe(n.lat)??Number.NaN,lng:oe(n.lng)??Number.NaN}};if(r==="contact")return{...s,type:r,metadata:{...n,...typeof n.phone=="string"?{phone:n.phone}:{},...typeof n.email=="string"?{email:n.email}:{}}};throw new TypeError(`Unsupported ConvoKit media type: ${r||"(missing)"}`)}function Xn(t){if(t==null)return 0;let e=oe(t);if(e===void 0||!Number.isInteger(e)||e<0)throw new TypeError(`Invalid ConvoKit message revision: ${String(t)}`);return e}function ye(t){let e=U(t);return{id:$(e.id),...e.clientMessageId===void 0?{}:{clientMessageId:Y(e.clientMessageId)},conversationId:$(e.conversationId??e.conversation_id),senderId:$(e.appUserId??e.app_user_id??e.senderId),text:Y(e.text??e.content),media:Array.isArray(e.media)?e.media.map(Na):[],createdAt:ve(e.createdAt??e.created_at),updatedAt:ae(e.updatedAt??e.updated_at),revision:Xn(e.revision),...typeof e.replyToMessageId=="string"?{replyToMessageId:e.replyToMessageId}:{}}}function Ua(t){if(t==null)return 0;let e=oe(t);if(e===void 0||!Number.isInteger(e)||e<0)throw new TypeError(`Invalid ConvoKit media count: ${String(t)}`);return e}function ja(t){let e=U(t),r=e.id;if(typeof r!="string"||!r.trim())throw new TypeError("Invalid ConvoKit reply preview: missing id");return{id:r,conversationId:$(e.conversationId??e.conversation_id),senderId:$(e.appUserId??e.app_user_id??e.senderId),text:Y(e.text),textTruncated:or(e.textTruncated??e.text_truncated,"textTruncated"),createdAt:ve(e.createdAt??e.created_at),revision:Xn(e.revision),mediaCount:Ua(e.mediaCount??e.media_count)}}function La(t){let e=U(t);if(!Array.isArray(e.data))throw new TypeError("Invalid ConvoKit message context: missing data");return{messages:e.data.map(ye),olderCursor:Hn(e.olderCursor??e.older_cursor,"olderCursor"),newerCursor:Hn(e.newerCursor??e.newer_cursor,"newerCursor")}}function Hn(t,e){if(t!=null&&typeof t!="string")throw new TypeError(`Invalid ConvoKit message context: ${e} must be a string or null`);return typeof t=="string"?t:null}function $a(t){if(t==null)return 0;let e=oe(t);if(e===void 0||!Number.isInteger(e)||e<0)throw new TypeError(`Invalid ConvoKit unread count: ${String(t)}`);return e}function or(t,e){if(t==null)return!1;if(typeof t!="boolean")throw new TypeError(`Invalid ConvoKit ${e}: ${String(t)}`);return t}function Da(t){let e=U(t),r=e.latestMessage??e.latest_message,s=$a(e.unreadCount??e.unread_count),n=or(e.unreadCountCapped??e.unread_count_capped,"unreadCountCapped"),i=ae(e.unreadMarkedAt??e.unread_marked_at),o=e.isUnread??e.is_unread;return{conversation:At(e.conversation),latestMessage:r==null?null:ye(r),unreadCount:s,unreadCountCapped:n,readPosition:ar(e.readPosition??e.read_position),lastReadAt:ae(e.lastReadAt??e.last_read_at),isUnread:o==null?s>0||n||i!==null:or(o,"isUnread"),unreadMarkedAt:i,privateStateVersion:Yr(e.privateStateVersion??e.private_state_version),activityAt:ve(e.activityAt??e.activity_at)}}function Ma(t){let e=U(t);if(!Array.isArray(e.entries))throw new TypeError("Invalid ConvoKit inbox page: missing entries");let r=e.nextCursor??e.next_cursor;if(r!=null&&typeof r!="string")throw new TypeError("Invalid ConvoKit inbox page: nextCursor must be a string or null");return{entries:e.entries.map(Da),nextCursor:typeof r=="string"?r:null}}function qa(t){let e=U(t);if(!Array.isArray(e.data))throw new TypeError("Invalid ConvoKit message page: missing data");let r=e.nextCursor!==void 0?e.nextCursor:e.next_cursor;if(r!==null&&(typeof r!="string"||r.length===0))throw new TypeError("Invalid ConvoKit message page: nextCursor must be a non-empty string or null");return{messages:e.data.map(ye),nextCursor:r}}function L(t){return U(t)}function Gr(t){return typeof t=="function"?{onEvent:t}:t}function Ct(t){let e=L(t);return L(e.payload??e)}function Ba(t){let e=Ct(t);if(typeof e.userId!="string"||typeof e.isTyping!="boolean")throw new TypeError("typing payload is missing userId or isTyping");return{userId:e.userId,isTyping:e.isTyping}}function Ha(t){let e=Ct(t);if(typeof e.userId!="string"||typeof e.readAt!="string")throw new TypeError("read payload is missing userId or readAt");let r=new Date(e.readAt);if(Number.isNaN(r.getTime()))throw new TypeError("readAt is not a date");return{userId:e.userId,readAt:r,readPosition:ar(e.readPosition??e.read_position)}}function Fa(t){let e=Ct(t);if(typeof e.userId!="string"||typeof e.isOnline!="boolean"||typeof e.lastSeenAt!="string")throw new TypeError("presence payload is incomplete");let r=new Date(e.lastSeenAt);if(Number.isNaN(r.getTime()))throw new TypeError("lastSeenAt is not a date");return{userId:e.userId,isOnline:e.isOnline,lastSeenAt:r}}var Ye,zn,zr=(zn=class{constructor(t){R(this,"close");es(this,Ye,!1);this.close=t}get closed(){return lr(this,Ye)}async unsubscribe(){lr(this,Ye)||(ts(this,Ye,!0),await this.close())}},Ye=new WeakMap,zn),Ka=class{constructor(t,e,r,s){R(this,"supabase");R(this,"appUserIdValue");R(this,"resolveTopic");R(this,"defaultErrorHandler");R(this,"subscriptions",new Set);R(this,"broadcastHubs",new Map);R(this,"connectionListeners",new Map);R(this,"sequence",0);R(this,"disposed",!1);this.supabase=t,this.appUserIdValue=e,this.resolveTopic=r,this.defaultErrorHandler=s}get appUserId(){return this.appUserIdValue}onConnectionEvent(t){this.requireOpen();let e=new zr(async()=>{this.connectionListeners.delete(e),this.subscriptions.delete(e)});return this.connectionListeners.set(e,t),this.subscriptions.add(e),e}onMessage(t,e){this.requireOpen();let r=Gr(e),s,n=`messages:${t}`,i=this.supabase.channel(this.channelName(n),{config:{private:!0}});for(let o of["INSERT","UPDATE"])i.on("postgres_changes",{event:o,schema:"public",table:"Message",filter:`conversationId=eq.${t}`},a=>{if(!(this.disposed||s?.closed))try{let c=ye(a.new);if(!c.id.trim()||c.conversationId!==t)throw new TypeError("Invalid message identity");r.onEvent({type:o==="INSERT"?"insert":"update",message:c})}catch{this.reportError(r,"Could not parse or deliver a realtime message")}});return s=this.subscribeChannel(i,r,n),s}onMessageDeleted(t,e){return this.subscribeBroadcast(`conversation:${t}`,"message_deleted",e,r=>{let s=Ct(r);if(typeof s.id!="string"||!s.id.trim()||!t.trim()||s.conversationId!==t)throw new TypeError("Invalid message deletion");return{id:s.id,conversationId:t}})}onReactionChanged(t,e){return this.subscribeBroadcast(`conversation:${t}`,"reaction_changed",e,r=>{let s=Ct(r);if(typeof s.id!="string"||!s.id.trim()||!t.trim()||s.conversationId!==t)throw new TypeError("Invalid reaction invalidation");return{id:s.id,conversationId:t}})}onTyping(t,e){return this.subscribeBroadcast(`conversation:${t}`,"typing",e,Ba)}onReadReceipt(t,e){return this.subscribeBroadcast(`conversation:${t}`,"read",e,Ha)}onPresence(t,e){return this.subscribeBroadcast(`app:${t}`,"presence",e,Fa)}onInboxChanged(t,e){let r=Gr(e);return this.subscribeBroadcast(`app:${t}`,"inbox_changed",{...r,onStatus:s=>{if(s==="SUBSCRIBED")try{r.onEvent()}catch{this.reportError(r,"Could not deliver inbox invalidation")}r.onStatus?.(s)}},()=>{})}onInboxActivity(t,e){return this.subscribeBroadcast(`app:${t}`,"inbox_activity",e,()=>{})}async dispose(){if(this.disposed)return;this.disposed=!0;let t=[...this.subscriptions];for(let[e,r]of[...this.connectionListeners])if(!e.closed)try{r.onSessionEnded?.()}catch{this.reportError(r,"Could not notify a retired Realtime session")}await Promise.all(t.map(e=>e.unsubscribe()))}connection(t,e){if(!this.disposed){for(let[r,s]of[...this.connectionListeners])if(!r.closed)try{s.onEvent({topic:t,status:e})}catch{this.reportError(s,"Could not deliver Realtime connection state")}}}channelName(t){return this.sequence+=1,`${t}:${Date.now()}:${this.sequence}`}subscribeChannel(t,e,r){let s;return s=new zr(async()=>{this.subscriptions.delete(s),await this.supabase.removeChannel(t)}),this.subscriptions.add(s),t.subscribe(n=>{if(this.disposed||s.closed)return;let i=n;this.connection(r,i),!(this.disposed||s.closed)&&(e.onStatus?.(i),(i==="CHANNEL_ERROR"||i==="TIMED_OUT")&&this.reportError(e,`Realtime subscription ${i.toLowerCase()}`))}),s}subscribeBroadcast(t,e,r,s){this.requireOpen();let n=Gr(r),i=this.broadcastHubs.get(t),o=!1;i||(i={listeners:new Set,generation:0,failures:0},this.broadcastHubs.set(t,i),o=!0);let a={event:e,onPayload:u=>{try{n.onEvent(s(u))}catch{this.reportError(n,`Could not parse or deliver a realtime ${e} event`)}},...n.onStatus===void 0?{}:{onStatus:n.onStatus},...n.onError===void 0?{}:{onError:n.onError}};i.listeners.add(a);let c=i,l=new zr(async()=>{this.subscriptions.delete(l),c.listeners.delete(a),c.listeners.size===0&&(this.broadcastHubs.get(t)===c&&this.broadcastHubs.delete(t),c.generation+=1,clearTimeout(c.retry),c.channel&&await this.supabase.removeChannel(c.channel))});return this.subscriptions.add(l),o?this.resolveBroadcastHub(t,c):i.status&&n.onStatus?.(i.status),l}hubIsCurrent(t,e){return!this.disposed&&e.listeners.size>0&&this.broadcastHubs.get(t)===e}broadcastStatus(t,e,r){if(this.hubIsCurrent(t,e)){e.status=r,this.connection(t,r);for(let s of[...e.listeners]){if(!this.hubIsCurrent(t,e))return;if(e.listeners.has(s)){try{s.onStatus?.(r)}catch{}if(r==="CHANNEL_ERROR"||r==="TIMED_OUT")try{s.onError?.(new S(`Realtime subscription ${r.toLowerCase()}`,{code:"REALTIME_ERROR"}))}catch{}}}(r==="CHANNEL_ERROR"||r==="TIMED_OUT")&&this.reportError({},`Realtime subscription ${r.toLowerCase()}`)}}resolveBroadcastHub(t,e,r=!1){if(!this.hubIsCurrent(t,e))return;clearTimeout(e.retry);let s=++e.generation,n=()=>this.hubIsCurrent(t,e)&&e.generation===s,i=a=>{if(!n())return;let c=e.channel;delete e.channel,c&&this.supabase.removeChannel(c).catch(()=>{}),this.broadcastStatus(t,e,"CHANNEL_ERROR"),!(a instanceof S&&[401,403,404].includes(a.status??0))&&++e.failures<=3&&n()&&(e.retry=setTimeout(()=>this.resolveBroadcastHub(t,e),1e3*e.failures),e.retry.unref?.())},o=a=>{if(!n())return;if(!a.startsWith(`${t}:`)||!a.slice(t.length+1).trim()||a.slice(t.length+1).includes(":"))throw new TypeError("Invalid private topic");if(e.channel&&e.wireTopic===a){r&&(e.failures=0,this.broadcastStatus(t,e,"SUBSCRIBED"));return}let c=e.channel;delete e.channel,delete e.status,c&&this.supabase.removeChannel(c).catch(()=>{});let l=this.createBroadcastChannel(t,a);e.channel=l,e.wireTopic=a,l.on("broadcast",{event:"scope_changed"},()=>{this.hubIsCurrent(t,e)&&e.channel===l&&(delete e.channel,delete e.status,this.supabase.removeChannel(l).catch(()=>{}),this.resolveBroadcastHub(t,e))}),l.subscribe(u=>{if(!this.hubIsCurrent(t,e)||e.channel!==l)return;let h=u;h==="SUBSCRIBED"?this.resolveBroadcastHub(t,e,!0):(this.broadcastStatus(t,e,h),(h==="CHANNEL_ERROR"||h==="TIMED_OUT"||h==="CLOSED")&&(delete e.channel,this.supabase.removeChannel(l).catch(()=>{}),++e.failures<=3&&(clearTimeout(e.retry),e.retry=setTimeout(()=>this.resolveBroadcastHub(t,e),1e3*e.failures),e.retry.unref?.())))})};try{let a=this.resolveTopic(t);typeof a=="string"?o(a):a.then(o).catch(i)}catch(a){i(a)}}createBroadcastChannel(t,e){let r=this.supabase.channel(e,{config:{private:!0}});return t.startsWith("conversation:")?r.on("broadcast",{event:"typing"},s=>{this.dispatchBroadcast(t,r,"typing",s)}).on("broadcast",{event:"read"},s=>{this.dispatchBroadcast(t,r,"read",s)}).on("broadcast",{event:"message_deleted"},s=>{this.dispatchBroadcast(t,r,"message_deleted",s)}).on("broadcast",{event:"reaction_changed"},s=>{this.dispatchBroadcast(t,r,"reaction_changed",s)}):(r.on("broadcast",{event:"presence"},s=>{this.dispatchBroadcast(t,r,"presence",s)}),r.on("broadcast",{event:"inbox_changed"},s=>{this.dispatchBroadcast(t,r,"inbox_changed",s)}),r.on("broadcast",{event:"inbox_activity"},s=>{this.dispatchBroadcast(t,r,"inbox_activity",s)})),r}dispatchBroadcast(t,e,r,s){if(this.disposed)return;let n=this.broadcastHubs.get(t);if(!(!n||n.channel!==e))for(let i of[...n.listeners])n.listeners.has(i)&&i.event===r&&i.onPayload(s)}requireOpen(){if(this.disposed)throw new S("This Realtime session has been closed; use the connected client\u2019s current session",{code:"SESSION_CHANGED"})}reportError(t,e){let r=new S(e,{code:"REALTIME_ERROR"});for(let s of[t.onError,this.defaultErrorHandler])try{s?.(r)}catch{}}},Wa=2147483647;function Fn(t){try{let e=t.split(".")[1];if(!e)return 1/0;let r=e.replace(/-/g,"+").replace(/_/g,"/"),s=JSON.parse(atob(r.padEnd(Math.ceil(r.length/4)*4,"=")));return typeof s.exp=="number"&&Number.isSafeInteger(s.exp)?s.exp*1e3:1/0}catch{return 1/0}}function ir(t){let e=Math.min(Fn(t.userToken),Fn(t.realtimeToken));if(e<=Date.now())throw new S("Session token has expired",{code:"TOKEN_EXPIRED"});return e}var Va=class{constructor(t){R(this,"options");R(this,"generation",0);R(this,"sessionSequence",0);R(this,"active",null);R(this,"pending",null);R(this,"refreshTimer");R(this,"expirationTimer");R(this,"listeners",new Set);R(this,"snapshot",Object.freeze({status:"disconnected",currentUserId:null,previousUserId:null,sessionId:null,reason:null,requiresReauthentication:!1,errorCode:null}));this.options=t}get connected(){return this.active!==null}get state(){return this.snapshot}get userId(){return this.requireActive().userId}get tokens(){return this.requireActive().tokens}get resource(){return this.requireActive().resource}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}capture(){let t=this.requireActive();return()=>this.assertActive(t)}async connect(t){let e=++this.generation,r=++this.sessionSequence,s=Object.freeze({status:"connecting",currentUserId:null,requestedUserId:t,sessionId:r});try{await this.clear(s),this.assertGeneration(e);let n=await this.options.tokens(t,()=>this.assertGeneration(e));this.assertGeneration(e),ir(n);let i=!0,o;try{o=await this.options.create(t,n,()=>e===this.generation?this.active?.tokens.realtimeToken??(i?n.realtimeToken:null):null)}finally{i=!1}if(e!==this.generation)throw await o.close(),this.changed();try{let a={id:r,userId:t,tokens:n,resource:o,refreshAt:1/0,expiresAt:ir(n),failures:0};this.active=a,this.schedule(a),this.transition(Object.freeze({status:"connected",currentUserId:t,sessionId:r}))}catch(a){throw this.active?.resource===o&&(this.active=null,this.cancelTimers()),await o.close(),a}}catch(n){if(e===this.generation&&this.active===null){let i=this.endState(t,r,this.connectionFailure(n));this.transition(i)}throw n}}async disconnect(){this.generation+=1;let t=this.snapshot,e=this.active?.userId??(t.status==="connecting"?t.requestedUserId:null),r=this.active?.id??(t.status==="connecting"?t.sessionId:null);await this.clear(this.endState(e,r,{reason:"user-disconnected",requiresReauthentication:!1,errorCode:null}))}async request(t){let e=this.requireActive();Date.now()>=e.refreshAt&&await this.renew(e),this.assertActive(e);let r=e.tokens.userToken;try{let s=await t(r);return this.assertActive(e),s}catch(s){if(this.assertActive(e),!(s instanceof S)||s.status!==401)throw s;if(r===e.tokens.userToken)try{await this.renew(e)}catch{throw this.assertActive(e),s}this.assertActive(e);let n=await t(e.tokens.userToken);return this.assertActive(e),n}}renew(t){if(this.assertActive(t),this.pending?.session===t)return this.pending.promise;let e=this.performRenewal(t).finally(()=>{this.pending?.promise===e&&(this.pending=null)});return this.pending={session:t,promise:e},e}async performRenewal(t){try{let e=await this.options.tokens(t.userId,()=>this.assertActive(t));this.assertActive(t);let r=ir(e);if(Date.now()>=t.refreshAt&&r<=t.expiresAt)throw new S("The token provider did not extend the session lifetime",{code:"SESSION_TOKEN_NOT_RENEWED"});if(e.supabaseUrl!==t.tokens.supabaseUrl||e.supabaseKey!==t.tokens.supabaseKey)throw new S("Realtime configuration changed; reconnect the user",{code:"SESSION_CONFIGURATION_CHANGED"});try{await t.resource.setAuth(e.realtimeToken)}catch{throw new S("Could not authenticate the renewed Realtime session",{code:"SESSION_REALTIME_AUTH_FAILED"})}this.assertActive(t),t.tokens=e,t.failures=0,this.schedule(t)}catch(e){throw this.active===t&&(e instanceof S&&([401,403].includes(e.status??0)||["TOKEN_EXPIRED","SESSION_CONFIGURATION_CHANGED","SESSION_REALTIME_AUTH_FAILED"].includes(e.code??""))||t.expiresAt<=Date.now()?this.retire(t,this.renewalFailure(e,t.expiresAt<=Date.now())):(t.failures+=1,t.refreshAt=Math.min(t.expiresAt,Date.now()+Math.min(3e4,5e3*2**Math.min(t.failures-1,3))),this.armRefresh(t)),this.report("Session token renewal failed","SESSION_REFRESH_FAILED")),e}}schedule(t){this.cancelTimers(),t.expiresAt=ir(t.tokens);let e=t.expiresAt-Date.now();t.refreshAt=Number.isFinite(e)?Date.now()+e-Math.min(3e5,e*.2):1/0,this.armRefresh(t),this.armExpiration(t)}armRefresh(t){clearTimeout(this.refreshTimer),Number.isFinite(t.refreshAt)&&(this.refreshTimer=this.timer(t.refreshAt-Date.now(),()=>{if(this.active===t){if(Date.now()<t.refreshAt){this.armRefresh(t);return}this.renew(t).catch(()=>{})}}))}armExpiration(t){clearTimeout(this.expirationTimer),Number.isFinite(t.expiresAt)&&(this.expirationTimer=this.timer(t.expiresAt-Date.now(),()=>{if(this.active===t){if(Date.now()<t.expiresAt){this.armExpiration(t);return}this.retire(t,{reason:"token-expired",requiresReauthentication:!0,errorCode:"SESSION_EXPIRED"}),this.report("Session expired; reconnect the user","SESSION_EXPIRED")}}))}timer(t,e){let r=setTimeout(e,Math.max(0,Math.min(Wa,t)));return r.unref?.(),r}retire(t,e){this.active===t&&(this.generation+=1,this.clear(this.endState(t.userId,t.id,e)).catch(()=>this.report("Could not finish closing the session","SESSION_CLOSE_FAILED")))}clear(t){let e=this.active;return this.active=null,this.pending=null,this.cancelTimers(),this.transition(t),e?.resource.close()??Promise.resolve()}transition(t){if(this.snapshot!==t){this.snapshot=t;for(let e of[...this.listeners])try{e()}catch{}}}endState(t,e,r){return Object.freeze({status:"disconnected",currentUserId:null,previousUserId:t,sessionId:e,reason:r.reason,requiresReauthentication:r.requiresReauthentication,errorCode:r.errorCode})}connectionFailure(t){if(t instanceof S){if([401,403].includes(t.status??0))return{reason:"authentication-rejected",requiresReauthentication:!0,errorCode:"SESSION_AUTHENTICATION_REJECTED"};if(t.code==="TOKEN_EXPIRED")return{reason:"token-expired",requiresReauthentication:!0,errorCode:"TOKEN_EXPIRED"}}return{reason:"connection-failed",requiresReauthentication:!1,errorCode:"SESSION_CONNECT_FAILED"}}renewalFailure(t,e){if(e||t instanceof S&&t.code==="TOKEN_EXPIRED")return{reason:"token-expired",requiresReauthentication:!0,errorCode:"SESSION_EXPIRED"};if(t instanceof S){if([401,403].includes(t.status??0))return{reason:"authentication-rejected",requiresReauthentication:!0,errorCode:"SESSION_REFRESH_REJECTED"};if(t.code==="SESSION_CONFIGURATION_CHANGED")return{reason:"configuration-changed",requiresReauthentication:!1,errorCode:t.code};if(t.code==="SESSION_REALTIME_AUTH_FAILED")return{reason:"realtime-authentication-failed",requiresReauthentication:!1,errorCode:t.code}}return{reason:"token-expired",requiresReauthentication:!0,errorCode:"SESSION_EXPIRED"}}cancelTimers(){clearTimeout(this.refreshTimer),clearTimeout(this.expirationTimer),this.refreshTimer=void 0,this.expirationTimer=void 0}report(t,e){try{this.options.onError?.(new S(t,{code:e}))}catch{}}requireActive(){if(!this.active)throw new S("Call connectUser() first",{code:"NOT_CONNECTED"});return this.active}assertActive(t){if(this.active!==t)throw this.changed()}assertGeneration(t){if(t!==this.generation)throw this.changed()}changed(){return new S("The user session changed while the operation was pending",{code:"SESSION_CHANGED"})}};function T(t,e){let r=t.trim();if(!r)throw new S(`${e} is required`,{code:"INVALID_ARGUMENT"});return r}function Je(t,e){if(!Number.isInteger(t)||t<0)throw new S(`${e} must be a non-negative integer`,{code:"INVALID_ARGUMENT"});return t}function Rt(t,e,r,s){if(!Number.isInteger(t)||t<r||t>s)throw new S(`${e} must be an integer between ${r} and ${s}`,{code:"INVALID_ARGUMENT"});return t}var Ga=2147483647,Kn=64,Wn=50,Vn=50;function Jr(t){if(typeof t!="string"||t.length===0)throw new S("emoji is required",{code:"INVALID_ARGUMENT"});return t}function Xe(t,e){let r=typeof t=="string"?t.trim():"";if(!r)throw new S(`${e} must be a non-empty string`,{code:"INVALID_ARGUMENT"});if(r.length>Kn)throw new S(`${e} must be at most ${Kn} characters`,{code:"INVALID_ARGUMENT"});return r}function Gn(t,e){return Rt(t,e,0,Ga)}function za(t){if(t instanceof Blob||t instanceof ArrayBuffer)return t;if(ArrayBuffer.isView(t)){let e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),e.buffer}throw new S("bytes must be a Blob, ArrayBuffer, or typed array",{code:"INVALID_ARGUMENT"})}var Yn=class{constructor(t){R(this,"backendUrl");R(this,"clientId");R(this,"tokenProvider");R(this,"onRealtimeError");R(this,"fetchImplementation");R(this,"transport");R(this,"session");this.tokenProvider=t.tokenProvider,this.onRealtimeError=t.onRealtimeError,this.fetchImplementation=(t.fetch??globalThis.fetch).bind(globalThis),this.clientId=T(t.clientId,"clientId"),this.transport=new Aa({backendUrl:t.backendUrl??Ta,clientId:this.clientId,...t.fetch===void 0?{}:{fetchImplementation:t.fetch},headersProvider:()=>({})}),this.backendUrl=this.transport.backendUrl,this.session=new Va({tokens:async(e,r)=>{let s=T(await this.tokenProvider(e),"tokenProvider result");r();let n=await this.transport.request("/api/v1/realtime/token",{method:"POST",authenticated:!1,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:{appUserId:e}});return r(),{userToken:s,realtimeToken:T(n.data.token,"realtime token"),supabaseUrl:T(n.data.supabaseUrl,"supabaseUrl"),supabaseKey:T(n.data.supabaseKey,"supabaseKey")}},create:async(e,r,s)=>{let n=Un(r.supabaseUrl,r.supabaseKey,{auth:{autoRefreshToken:!1,persistSession:!1,detectSessionInUrl:!1},accessToken:async()=>s()});try{await n.realtime.setAuth(r.realtimeToken)}catch(o){throw n.realtime.disconnect(),o}let i=new Ka(n,e,async o=>{if(!s())throw new S("Realtime session ended",{code:"SESSION_CHANGED"});let a=this.session.capture(),c=await this.request("/api/v1/realtime/topic",{query:{topic:o}});if(a(),!s())throw new S("Realtime session ended",{code:"SESSION_CHANGED"});return T(c.data.topic,"private Realtime topic")},this.onRealtimeError);return{supabase:n,realtime:i,setAuth:o=>n.realtime.setAuth(o),close:async()=>{try{await i.dispose()}finally{n.realtime.disconnect()}}}},onError:this.onRealtimeError})}get connected(){return this.session.connected}get sessionState(){return this.session.state}subscribeSession(t){return this.session.subscribe(t)}get currentUserId(){return this.session.userId}get authHeaders(){return{"Content-Type":"application/json","x-client-id":this.clientId,Authorization:`Bearer ${this.requireUserToken()}`}}get lastToken(){return this.session.tokens.realtimeToken}get lastUserToken(){return this.requireUserToken()}get lastTokenClaims(){let t=this.lastToken.split(".");if(t.length!==3||t[1]===void 0)throw new S("Invalid JWT format",{code:"INVALID_TOKEN"});let e=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");try{let s=Uint8Array.from(atob(r),n=>n.charCodeAt(0));return JSON.parse(new TextDecoder().decode(s))}catch(s){throw new S("Could not decode realtime token",{code:"INVALID_TOKEN",cause:s})}}get supabase(){return this.session.resource.supabase}get realtime(){return this.session.resource.realtime}async connectUser(t){await this.session.connect(T(t,"appUserId"))}async disconnectUser(){await this.session.disconnect()}async getUsers(t={}){this.requireConnected();let e=Je(t.limit??50,"limit"),r=Je(t.offset??0,"offset"),s=await this.request("/api/v1/user",{query:{limit:e,offset:r}}),n=L(s),i=Array.isArray(n.data)?n.data:[];return{data:i.map(Bn),totalCount:typeof n.total_count=="number"?n.total_count:i.length}}async getUser(t){this.requireConnected();let e=await this.request(`/api/v1/user/${encodeURIComponent(T(t,"id"))}`);return Bn(L(e).data)}async getConversations(t={}){this.requireConnected();let e=Je(t.limit??50,"limit"),r=Je(t.offset??0,"offset"),s=await this.request("/api/v1/conversations",{query:{limit:e,offset:r,...t.archived===!0?{archived:!0}:{}}}),n=L(s).conversations;return Array.isArray(n)?n.map(At):[]}async listInbox(t={}){this.requireConnected();let e=Rt(t.limit??30,"limit",1,100),r=t.cursor??void 0;if(r!==void 0&&(typeof r!="string"||r.trim()===""))throw new S("cursor must be a non-empty string",{code:"INVALID_ARGUMENT"});let s=await this.request("/api/v1/inbox",{query:{limit:e,...r===void 0?{}:{cursor:r},...t.archived===!0?{archived:!0}:{}}});return Ma(s)}async getConversation(t){this.requireConnected();let e=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"id"))}`),r=L(e),s=Oa(r.membership);return{...At(r.conversation),...s===null?{}:{membership:s}}}async createConversation(t){this.requireConnected();let e=await this.request("/api/v1/conversations",{method:"POST",body:{participants:t.participants,...t.title===void 0?{}:{title:t.title},...t.description===void 0?{}:{description:t.description},...t.imageUrl===void 0?{}:{imageUrl:t.imageUrl}}});return At(L(e).conversation)}async markConversationRead(t,e={}){this.requireConnected();let r=e.throughMessageId;if(r!==void 0&&typeof r!="string")throw new S("throughMessageId must be a string",{code:"INVALID_ARGUMENT"});let s=e.privateStateVersion;await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"conversationId"))}/read`,{method:"POST",body:{...r===void 0?{}:{throughMessageId:T(r,"throughMessageId")},...s===void 0?{}:{privateStateVersion:Gn(s,"privateStateVersion")}}})}async markConversationUnread(t){this.requireConnected();let e=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"conversationId"))}/unread`,{method:"POST"});return Jn(e)}async clearConversationUnread(t,e={}){this.requireConnected();let r=e.ifVersion,s=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"conversationId"))}/unread`,{method:"DELETE",query:r===void 0?{}:{privateStateVersion:Gn(r,"ifVersion")}});return Pa(s)}async sendTyping(t){this.requireConnected(),await this.request(`/api/v1/conversations/${encodeURIComponent(T(t.conversationId,"conversationId"))}/typing`,{method:"POST",body:{isTyping:t.isTyping}})}async updatePresence(t){this.requireConnected(),await this.request("/api/v1/presence",{method:"POST",body:{isOnline:t.isOnline}})}async leaveConversation(t){return this.conversationAction(t,"leave","POST")}async archiveConversation(t){return this.conversationAction(t,"archive","POST")}async unarchiveConversation(t){return this.conversationAction(t,"archive","DELETE")}async updateConversationTitle(t){this.requireConnected();let e=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t.conversationId,"conversationId"))}/title`,{method:"PATCH",body:{title:t.title}});return At(L(e).conversation)}async getMessages(t){this.requireConnected();let e=Je(t.offset??0,"offset"),r=t.beforeCreatedAt!==void 0,s=t.beforeId!==void 0;if(r!==s||r&&e!==0)throw new S("Provide both cursor values without a nonzero offset",{code:"INVALID_ARGUMENT"});let n;if(r&&s){if(!(t.beforeCreatedAt instanceof Date)||!Number.isFinite(t.beforeCreatedAt.getTime()))throw new S("beforeCreatedAt must be a valid Date",{code:"INVALID_ARGUMENT"});n={beforeCreatedAt:t.beforeCreatedAt.toISOString(),beforeId:T(t.beforeId,"beforeId")}}let i=await this.request("/api/v1/messages",{query:{conversationId:T(t.conversationId,"conversationId"),limit:Je(t.limit??20,"limit"),offset:e,...n}}),o=L(i).data;return Array.isArray(o)?o.map(ye):[]}async listMessages(t){this.requireConnected();let e=Rt(t.limit??20,"limit",1,100),r=t.cursor??void 0;if(r!==void 0&&(typeof r!="string"||r.trim()===""))throw new S("cursor must be a non-empty string",{code:"INVALID_ARGUMENT"});let s=await this.request("/api/v1/messages",{query:{conversationId:T(t.conversationId,"conversationId"),limit:e,...r===void 0?{}:{cursor:r}}});return qa(s)}async getMessage(t){this.requireConnected();let e=await this.request(`/api/v1/messages/${encodeURIComponent(T(t,"id"))}`);return ye(L(e).data)}async sendMessage(t){this.requireConnected();let e=await this.request("/api/v1/messages",{method:"POST",body:{conversationId:T(t.conversationId,"conversationId"),clientMessageId:t.clientMessageId??Xr(),...t.text===void 0?{}:{text:t.text},...t.media===void 0||t.media.length===0?{}:{media:t.media},...t.replyToMessageId===void 0?{}:{replyToMessageId:T(t.replyToMessageId,"replyToMessageId")}}});return ye(L(e).data)}async editMessage(t,e){this.requireConnected();let r=T(t,"messageId"),s=e.text;if(s===void 0)throw new S("text is required",{code:"INVALID_ARGUMENT"});if(s!==null&&typeof s!="string")throw new S("text must be a string or null",{code:"INVALID_ARGUMENT"});let n=Ra(e.revision,"revision"),i=await this.request(`/api/v1/messages/${encodeURIComponent(r)}/own`,{method:"PATCH",body:{text:s,revision:n}});return ye(L(i).data)}async deleteMessage(t){this.requireConnected(),await this.request(`/api/v1/messages/${encodeURIComponent(T(t,"messageId"))}/own`,{method:"DELETE"})}async addReaction(t,e){this.requireConnected();let r=await this.request(`/api/v1/messages/${encodeURIComponent(Xe(t,"messageId"))}/reactions`,{method:"POST",body:{emoji:Jr(e)}});return qn(r)}async removeReaction(t,e){this.requireConnected();let r=await this.request(`/api/v1/messages/${encodeURIComponent(Xe(t,"messageId"))}/reactions`,{method:"DELETE",query:{emoji:Jr(e)}});return qn(r)}async getReactionSummaries(t,e){this.requireConnected();let r=this.session.capture(),s=T(t,"conversationId");if(!Array.isArray(e)||e.length===0)throw new S("messageIds must be a non-empty array",{code:"INVALID_ARGUMENT"});let n=Array.from(new Set(e.map(o=>Xe(o,"messageIds")))),i=[];for(let o=0;o<n.length;o+=Vn){r();let a=await this.request(`/api/v1/conversations/${encodeURIComponent(s)}/reactions`,{query:{ids:n.slice(o,o+Vn).join(",")}});i.push(...Ca(a))}return r(),i}async listReactionUsers(t,e,r={}){this.requireConnected();let s=Xe(t,"messageId"),n=Rt(r.limit??30,"limit",1,100),i=r.cursor===void 0?void 0:T(r.cursor,"cursor"),o=await this.request(`/api/v1/messages/${encodeURIComponent(s)}/reactions`,{query:{emoji:Jr(e),limit:n,...i===void 0?{}:{cursor:i}}});return Ia(o)}async getReplyPreviews(t,e){this.requireConnected();let r=this.session.capture(),s=T(t,"conversationId");if(!Array.isArray(e))throw new S("messageIds must be an array",{code:"INVALID_ARGUMENT"});if(e.length===0)throw new S("messageIds must not be empty",{code:"INVALID_ARGUMENT"});let n=[],i=new Set;for(let a of e){let c=Xe(a,"messageIds");i.has(c)||(i.add(c),n.push(c))}let o=[];for(let a=0;a<n.length;a+=Wn){r();let c=await this.request(`/api/v1/conversations/${encodeURIComponent(s)}/reply-previews`,{query:{ids:n.slice(a,a+Wn).join(",")}}),l=L(c).data;if(!Array.isArray(l))throw new TypeError("Invalid ConvoKit reply previews: missing data");for(let u of l)o.push(ja(u))}return o}async getMessageContext(t,e={}){this.requireConnected();let r=T(t,"conversationId"),s=Rt(e.limit??30,"limit",1,100),i=["messageId","olderCursor","newerCursor"].filter(c=>e[c]!==void 0);if(i.length!==1)throw new S("Use a message ID or a cursor, not both",{code:"INVALID_ARGUMENT"});let o={limit:s};if(e.messageId!==void 0)o.messageId=Xe(e.messageId,"messageId");else{let c=i[0],l=e[c];if(typeof l!="string"||l.trim()==="")throw new S(`${c} must be a non-empty string`,{code:"INVALID_ARGUMENT"});o[c]=l}let a=await this.request(`/api/v1/conversations/${encodeURIComponent(r)}/context`,{query:o});return La(a)}async uploadUserAvatar(t){this.requireConnected();let e=this.session.capture(),r=await this.upload({folder:"user_avatar",bytes:t.bytes,fileName:t.fileName,...t.contentType===void 0?{}:{contentType:t.contentType},userId:T(t.userId,"userId")});return e(),await this.request(`/api/v1/user/${encodeURIComponent(t.userId)}/avatar`,{method:"PATCH",body:{imageUrl:r}}),r}async uploadConversationImage(t){this.requireConnected();let e=this.session.capture(),r=T(t.conversationId,"conversationId"),s=await this.upload({folder:"conversation_image",bytes:t.bytes,fileName:t.fileName,...t.contentType===void 0?{}:{contentType:t.contentType},conversationId:r});return e(),await this.request(`/api/v1/conversations/${encodeURIComponent(r)}/image`,{method:"PATCH",body:{imageUrl:s}}),s}async uploadMessageMedia(t){return this.requireConnected(),this.upload({folder:"message_media",bytes:t.bytes,fileName:t.fileName,...t.contentType===void 0?{}:{contentType:t.contentType},conversationId:T(t.conversationId,"conversationId")})}async deleteUserAvatar(t){this.requireConnected(),await this.request(`/api/v1/user/${encodeURIComponent(T(t.userId,"userId"))}/avatar`,{method:"DELETE"})}async deleteConversationImage(t){this.requireConnected(),await this.request(`/api/v1/conversations/${encodeURIComponent(T(t.conversationId,"conversationId"))}/image`,{method:"DELETE"})}async downloadMedia(t){this.requireConnected();let e=this.session.capture(),s=await(await this.requestRaw("/api/v1/media/download",{query:{url:T(t,"url")}})).blob();return e(),s}requireConnected(){this.currentUserId}requireUserToken(){return this.session.tokens.userToken}request(t,e={}){return this.session.request(r=>this.transport.request(t,{...e,authenticated:!1,headers:{...e.headers,"Content-Type":"application/json",Authorization:`Bearer ${r}`}}))}requestRaw(t,e={}){return this.session.request(r=>this.transport.requestRaw(t,{...e,authenticated:!1,headers:{...e.headers,"Content-Type":"application/json",Authorization:`Bearer ${r}`}}))}async conversationAction(t,e,r){this.requireConnected();let s=await this.request(`/api/v1/conversations/${encodeURIComponent(T(t,"id"))}/${e}`,{method:r}),n=L(s).conversationId;return T(typeof n=="string"?n:"","conversationId response")}async upload(t){let e=this.session.capture(),r=await this.request("/api/v1/media/sign-upload",{method:"POST",query:{folder:t.folder,fileName:T(t.fileName,"fileName"),contentType:t.contentType,userId:t.userId,conversationId:t.conversationId}});e();let s=L(L(r).data),n=T(String(s.uploadUrl??""),"uploadUrl response"),i=T(String(s.fileUrl??""),"fileUrl response"),o=T(String(s.objectKey??""),"objectKey response"),a=typeof s.contentType=="string"?s.contentType:"application/octet-stream",c;try{c=await this.fetchImplementation(n,{method:"PUT",headers:{"Content-Type":a},body:za(t.bytes)})}catch(l){throw new S("Could not upload media to storage",{code:"UPLOAD_NETWORK_ERROR",cause:l})}if(!c.ok)throw new S(`Media upload failed with status ${c.status}`,{code:"UPLOAD_ERROR",status:c.status});return e(),await this.request("/api/v1/media/complete-upload",{method:"POST",body:{objectKey:o}}),i}};var xe=class extends Error{constructor(r,s,n){super(r);this.status=s;this.code=n}};function ti(t){try{return t==="SESSION"?window.sessionStorage:window.localStorage}catch{return null}}var ri=t=>`convokit-widget:${t}:guest`;function Ja(t){try{return ti(t.storageMode)?.getItem(ri(t.clientId))??null}catch{return null}}function Xa(t,e){try{ti(t.storageMode)?.setItem(ri(t.clientId),e)}catch{}}async function Qn(t,e,r){let s=await r(`${t.apiUrl}/api/v1/widget/session`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":t.clientId,"x-widget-key":t.widgetKey},body:JSON.stringify(e)}),n=await s.json().catch(()=>null);if(!s.ok||!n?.data?.token||!n.data.appUserId)throw new xe(n?.error??"Could not start the chat session",s.status,n?.code);return n.data}function Zn(t){let e={};return t.user?.name&&(e.name=t.user.name),t.user?.imageUrl&&(e.imageUrl=t.user.imageUrl),e}function ei(t,e){let r=t.token;return{appUserId:t.appUserId,tokenProvider:async s=>{if(r){let i=r;return r=null,i}let n=await e();if(n.appUserId!==s)throw new xe("The chat session belongs to a different user",401);return n.token}}}async function si(t,e=fetch){if(t.mode==="guest"){let s=()=>Qn(t,{mode:"guest",resumeToken:Ja(t),...Zn(t)},e).then(n=>(n.resumeToken&&Xa(t,n.resumeToken),n));return ei(await s(),s)}if(t.mode==="uid"){let s=()=>Qn(t,{mode:"uid",uid:t.uid,...Zn(t)},e);return ei(await s(),s)}let r=t.tokenProvider??(async s=>{let n=await e(t.tokenUrl,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({appUserId:s})}),i=await n.json().catch(()=>null),o=i?.token??i?.data?.token;if(!n.ok||!o)throw new xe("Your token endpoint did not return a token",n.status);return o});return{appUserId:t.userId,tokenProvider:r}}var ni=(t,e,r,s)=>`
30
+ :host { all: initial; --ck-primary: ${t}; --ck-bg: #ffffff; --ck-fg: #111827; --ck-muted: #6b7280; --ck-border: #e5e7eb; --ck-bubble: #f3f4f6; --ck-danger: #b91c1c;
31
+ font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; font-size: 14px; line-height: 1.4; color: var(--ck-fg); }
32
+ @media (prefers-color-scheme: dark) {
33
+ :host { --ck-bg: #111827; --ck-fg: #f9fafb; --ck-muted: #9ca3af; --ck-border: #374151; --ck-bubble: #1f2937; --ck-danger: #f87171; }
34
+ }
35
+ *, *::before, *::after { box-sizing: border-box; }
36
+ [hidden] { display: none !important; }
37
+ button { font: inherit; color: inherit; cursor: pointer; }
38
+ button:focus-visible, textarea:focus-visible { outline: 2px solid var(--ck-primary); outline-offset: 2px; }
39
+ .docked { position: fixed; bottom: 20px; ${s}: 20px; z-index: 2147483000; display: flex; flex-direction: column; align-items: ${s==="left"?"flex-start":"flex-end"}; gap: 12px; }
40
+ .launcher { position: relative; width: 56px; height: 56px; border-radius: 50%; border: 0; background: var(--ck-primary); color: #fff; box-shadow: 0 6px 20px rgb(0 0 0 / .2); display: grid; place-items: center; }
41
+ .launcher svg { width: 26px; height: 26px; }
42
+ .badge { position: absolute; top: -2px; ${s==="left"?"left":"right"}: -2px; min-width: 20px; height: 20px; padding: 0 6px; border-radius: 10px; background: #dc2626; color: #fff; font-size: 12px; font-weight: 600; display: grid; place-items: center; }
43
+ .panel { width: ${e}; height: ${r}; max-width: calc(100vw - 32px); max-height: calc(100vh - 110px); background: var(--ck-bg); border: 1px solid var(--ck-border); border-radius: 14px; box-shadow: 0 12px 40px rgb(0 0 0 / .18); display: flex; flex-direction: column; overflow: hidden; }
44
+ .inline .panel { max-height: none; max-width: 100%; box-shadow: none; }
45
+ header { display: flex; align-items: center; gap: 8px; padding: 12px 14px; background: var(--ck-primary); color: #fff; }
46
+ header h2 { flex: 1; margin: 0; font-size: 15px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
47
+ .icon { border: 0; background: transparent; color: inherit; padding: 4px; border-radius: 6px; display: grid; place-items: center; }
48
+ .icon svg { width: 18px; height: 18px; }
49
+ .body { flex: 1; min-height: 0; display: flex; flex-direction: column; }
50
+ .center { flex: 1; display: grid; place-items: center; padding: 24px; text-align: center; color: var(--ck-muted); gap: 12px; align-content: center; }
51
+ .error { color: var(--ck-danger); }
52
+ .primary { border: 0; border-radius: 8px; padding: 8px 14px; background: var(--ck-primary); color: #fff; font-weight: 600; }
53
+ .list { flex: 1; overflow-y: auto; margin: 0; padding: 0; list-style: none; }
54
+ .list button { width: 100%; text-align: left; border: 0; border-bottom: 1px solid var(--ck-border); background: transparent; padding: 12px 14px; display: grid; grid-template-columns: 1fr auto; gap: 2px 8px; }
55
+ .list button:hover { background: var(--ck-bubble); }
56
+ .list .name { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
57
+ .list .preview { grid-column: 1; color: var(--ck-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
58
+ .list .dot { grid-row: 1 / span 2; grid-column: 2; align-self: center; min-width: 20px; height: 20px; padding: 0 6px; border-radius: 10px; background: var(--ck-primary); color: #fff; font-size: 12px; display: grid; place-items: center; }
59
+ .messages { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 6px; }
60
+ .older { align-self: center; border: 1px solid var(--ck-border); background: transparent; border-radius: 999px; padding: 4px 12px; color: var(--ck-muted); font-size: 12px; }
61
+ .msg { max-width: 80%; display: flex; flex-direction: column; gap: 2px; }
62
+ .msg.mine { align-self: flex-end; align-items: flex-end; }
63
+ .msg .who { font-size: 12px; color: var(--ck-muted); }
64
+ .msg .bubble { padding: 8px 12px; border-radius: 14px; background: var(--ck-bubble); white-space: pre-wrap; overflow-wrap: anywhere; }
65
+ .msg.mine .bubble { background: var(--ck-primary); color: #fff; }
66
+ .msg .meta { font-size: 11px; color: var(--ck-muted); }
67
+ .msg.failed .meta { color: var(--ck-danger); }
68
+ .msg .attachment { font-size: 12px; color: var(--ck-muted); }
69
+ .empty { margin: auto; color: var(--ck-muted); }
70
+ form { display: flex; gap: 8px; padding: 10px; border-top: 1px solid var(--ck-border); align-items: flex-end; }
71
+ textarea { flex: 1; resize: none; max-height: 120px; min-height: 38px; border: 1px solid var(--ck-border); border-radius: 10px; padding: 8px 10px; font: inherit; color: var(--ck-fg); background: var(--ck-bg); }
72
+ form .primary { height: 38px; }
73
+ form .primary:disabled { opacity: .5; cursor: default; }
74
+ @media (max-width: 480px) {
75
+ .docked .panel { position: fixed; inset: 0; width: 100vw; height: 100dvh; max-width: none; max-height: none; border-radius: 0; }
76
+ }
77
+ `;var ai={chat:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',close:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg>',back:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg>'},ii={WIDGET_USER_LIMIT_REACHED:"Chat is busy right now. Please try again later.",PLAN_USER_LIMIT_REACHED:"Chat is busy right now. Please try again later.",PLAN_UPGRADE_REQUIRED:"Chat is currently unavailable.",RATE_LIMITED:"Too many attempts. Please wait a few minutes and try again.",ORIGIN_NOT_ALLOWED:"Chat is not enabled for this website.",WIDGET_DISABLED:"Chat is currently unavailable.",WIDGET_MODE_DISABLED:"Chat is currently unavailable.",SUBSCRIPTION_REQUIRED:"Chat is currently unavailable."},Ya={PLAN_UPGRADE_REQUIRED:'This ConvoKit plan only supports guest mode. Use mode: "guest", or upgrade to Starter for "uid" and "authToken".',PLAN_USER_LIMIT_REACHED:"This ConvoKit plan has reached its monthly active user limit. Upgrade the plan in the ConvoKit dashboard.",WIDGET_USER_LIMIT_REACHED:"The monthly limit of new widget users is reached. Raise it in the ConvoKit dashboard or upgrade the plan."},ci=t=>t instanceof xe||t instanceof S?t.code:void 0;function Qa(t){let e=ci(t);return e&&ii[e]?ii[e]:"Could not connect to chat. Check your connection and try again."}function k(t,e={},...r){let s=Object.assign(document.createElement(t),e);return s.append(...r),s}function oi(t,e,r){let s=k("button",{type:"button",className:"icon",onclick:r});return s.setAttribute("aria-label",e),s.innerHTML=ai[t],s}var cr=class{constructor(e,r={}){this.config=e;this.deps=r;this.launcher=null;this.badge=null;this.client=null;this.session=null;this.connecting=null;this.inbox=[];this.inboxSubscriptions=[];this.threadSubscriptions=[];this.thread=null;this.inboxRefresh=null;this.unsubscribeSession=null;this.destroyed=!1;let s=e.mount?document.querySelector(e.mount):null;s||(s=document.createElement("div"),e.mount?.startsWith("#")&&(s.id=e.mount.slice(1)),document.body.append(s)),this.host=s,this.root=s.shadowRoot??s.attachShadow({mode:"open"}),this.root.replaceChildren(k("style",{textContent:ni(e.primaryColor,e.width,e.height,e.dockedAlignment)})),this.heading=k("h2",{textContent:e.title}),this.backSlot=k("span"),this.headerActions=k("span"),this.body=k("div",{className:"body"}),this.panel=k("section",{className:"panel"},k("header",{},this.backSlot,this.heading,this.headerActions),this.body),this.panel.setAttribute("aria-label",e.title),this.isOpen=!e.isDocked,e.isDocked?(this.badge=k("span",{className:"badge",hidden:!0}),this.launcher=k("button",{type:"button",className:"launcher",onclick:()=>this.toggle()}),this.launcher.innerHTML=ai.chat,this.launcher.append(this.badge),this.headerActions.append(oi("close","Close chat",()=>this.close())),this.panel.hidden=!0,this.root.append(k("div",{className:"docked"},this.panel,this.launcher)),this.updateLauncher()):(this.root.append(k("div",{className:"inline"},this.panel)),this.connect())}open(){this.destroyed||(this.isOpen=!0,this.panel.hidden=!1,this.updateLauncher(),this.connect().then(()=>this.markThreadRead()))}close(){this.config.isDocked&&(this.isOpen=!1,this.panel.hidden=!0,this.updateLauncher(),this.launcher?.focus())}toggle(){this.isOpen?this.close():this.open()}async destroy(){this.destroyed=!0,this.inboxRefresh&&clearTimeout(this.inboxRefresh),this.unsubscribeSession?.(),await this.leaveThread(),await Promise.allSettled(this.inboxSubscriptions.map(e=>e.unsubscribe())),await this.client?.disconnectUser().catch(()=>{}),this.root.replaceChildren()}get chatClient(){return this.client}connect(){return this.client&&this.session?Promise.resolve():(this.connecting??(this.connecting=this.doConnect().finally(()=>{this.connecting=null})),this.connecting)}async doConnect(){this.showCenter("Connecting\u2026");try{let e=await si(this.config,this.deps.fetch),r={clientId:this.config.clientId,tokenProvider:e.tokenProvider,backendUrl:this.config.apiUrl},s=this.deps.createClient?this.deps.createClient(r):new Yn(r);if(await s.connectUser(e.appUserId),this.destroyed){await s.disconnectUser();return}this.client=s,this.session=e,this.unsubscribeSession=s.subscribeSession(()=>{let n=s.sessionState;n.status==="disconnected"&&n.requiresReauthentication&&this.reset("Your chat session ended.")}),this.watchInbox(),this.config.startConversationWith.length?await this.openConversation(await this.findOrCreateConversation()):await this.showInbox()}catch(e){let r=Ya[ci(e)??""];r&&console.warn(`[ConvoKitWidget] ${r}`),console.error("[ConvoKitWidget] could not start chat:",e),this.client=null,this.session=null,this.showCenter(Qa(e),!0)}}async reset(e){await this.leaveThread(),await Promise.allSettled(this.inboxSubscriptions.map(r=>r.unsubscribe())),this.inboxSubscriptions=[],this.unsubscribeSession?.(),this.unsubscribeSession=null,this.client=null,this.session=null,this.showCenter(e,!0)}get me(){return this.session.appUserId}watchInbox(){let e=this.client.realtime,r=()=>{this.inboxRefresh&&clearTimeout(this.inboxRefresh),this.inboxRefresh=setTimeout(()=>{this.loadInbox()},300)};this.inboxSubscriptions=[e.onInboxActivity(this.client.clientId,r),e.onInboxChanged(this.client.clientId,r)]}async loadInbox(){if(this.client)try{this.inbox=(await this.client.listInbox({limit:50})).entries,this.updateLauncher(),this.thread||this.renderInbox()}catch{}}async findOrCreateConversation(){let e=new Set([this.me,...this.config.startConversationWith]),r=await this.client.listInbox({limit:100});this.inbox=r.entries;let s=r.entries.find(n=>{let i=new Set(n.conversation.participants.map(o=>o.appUserId));return i.size===e.size&&[...e].every(o=>i.has(o))});return s?s.conversation:this.client.createConversation({participants:this.config.startConversationWith,...this.config.conversationTitle?{title:this.config.conversationTitle}:{}})}async showInbox(){await this.leaveThread(),this.heading.textContent=this.config.title,this.backSlot.replaceChildren(),this.showCenter("Loading\u2026"),await this.loadInbox(),this.renderInbox()}renderInbox(){if(!this.client||this.thread)return;if(this.inbox.length===0){let r=[k("p",{textContent:"No conversations yet."})];this.config.startConversationWith.length&&r.push(k("button",{type:"button",className:"primary",textContent:"Start a conversation",onclick:()=>{this.findOrCreateConversation().then(s=>this.openConversation(s))}})),this.body.replaceChildren(k("div",{className:"center"},...r));return}let e=k("ul",{className:"list"});for(let r of this.inbox){let s=r.latestMessage?r.latestMessage.text??"Attachment":"No messages yet",n=k("button",{type:"button",onclick:()=>{this.openConversation(r.conversation)}},k("span",{className:"name",textContent:r.conversation.displayTitle}),k("span",{className:"preview",textContent:s}));r.isUnread&&n.append(k("span",{className:"dot",textContent:r.unreadCount?String(r.unreadCount):""})),e.append(k("li",{},n))}this.body.replaceChildren(e)}updateLauncher(){if(!this.launcher||!this.badge)return;let e=this.inbox.reduce((r,s)=>r+(s.isUnread?Math.max(1,s.unreadCount):0),0);this.badge.textContent=e>99?"99+":String(e),this.badge.hidden=e===0||this.isOpen,this.launcher.setAttribute("aria-label",this.isOpen?"Close chat":e?`Open chat, ${e} unread`:"Open chat"),this.launcher.setAttribute("aria-expanded",String(this.isOpen))}async leaveThread(){let e=this.threadSubscriptions;this.threadSubscriptions=[],this.thread=null,await Promise.allSettled(e.map(r=>r.unsubscribe()))}async openConversation(e){await this.leaveThread();let r=this.client,s=k("div",{className:"messages"});s.setAttribute("role","log"),s.setAttribute("aria-live","polite");let n=new Map(e.participants.map(a=>[a.appUserId,a.name])),i={conversation:e,messages:new Map,pending:[],nextCursor:null,list:s,names:n};this.thread=i,this.heading.textContent=e.displayTitle||this.config.title,this.backSlot.replaceChildren(oi("back","All conversations",()=>{this.showInbox()})),this.body.replaceChildren(s,this.composer());let o=r.realtime;this.threadSubscriptions=[o.onMessage(e.id,a=>{this.thread===i&&(i.pending=i.pending.filter(c=>c.clientMessageId!==a.message.clientMessageId),i.messages.set(a.message.id,a.message),this.renderMessages(!0),this.markThreadRead())}),o.onMessageDeleted(e.id,a=>{this.thread===i&&(i.messages.delete(a.id),this.renderMessages(!1))})],await this.loadOlder(i),this.markThreadRead()}async loadOlder(e){let r=await this.client.listMessages({conversationId:e.conversation.id,limit:30,cursor:e.nextCursor});if(this.thread!==e)return;for(let i of r.messages)e.messages.has(i.id)||e.messages.set(i.id,i);e.nextCursor=r.nextCursor;let s=e.list.childElementCount===0,n=e.list.scrollHeight;this.renderMessages(s),s||(e.list.scrollTop=e.list.scrollHeight-n)}renderMessages(e){let r=this.thread;if(!r)return;let{list:s}=r,n=s.scrollHeight-s.scrollTop-s.clientHeight<80,i=[...r.messages.values()].sort((c,l)=>c.createdAt.getTime()-l.createdAt.getTime()||c.id.localeCompare(l.id)),o=[];r.nextCursor&&o.push(k("button",{type:"button",className:"older",textContent:"Load earlier messages",onclick:()=>{this.loadOlder(r)}})),i.length===0&&r.pending.length===0&&o.push(k("p",{className:"empty",textContent:"Say hello \u{1F44B}"}));let a=null;for(let c of i){let l=c.senderId===this.me,u=k("div",{className:l?"msg mine":"msg"});!l&&c.senderId!==a&&u.append(k("span",{className:"who",textContent:r.names.get(c.senderId)??c.senderId})),c.text&&u.append(k("div",{className:"bubble",textContent:c.text})),c.media.length&&u.append(k("span",{className:"attachment",textContent:`\u{1F4CE} ${c.media.length===1?"1 attachment":`${c.media.length} attachments`}`}));let h=c.createdAt.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});u.append(k("span",{className:"meta",textContent:c.revision>0?`${h} \xB7 edited`:h})),o.push(u),a=c.senderId}for(let c of r.pending){let l=k("div",{className:c.failed?"msg mine failed":"msg mine"},k("div",{className:"bubble",textContent:c.text}));l.append(c.failed?k("button",{type:"button",className:"older",textContent:"Not sent. Tap to retry",onclick:()=>{this.send(c)}}):k("span",{className:"meta",textContent:"Sending\u2026"})),o.push(l)}s.replaceChildren(...o),(e||n)&&(s.scrollTop=s.scrollHeight)}composer(){let e=k("textarea",{rows:1,placeholder:"Write a message\u2026",maxLength:4e3});e.setAttribute("aria-label","Message");let r=k("button",{type:"submit",className:"primary",textContent:"Send",disabled:!0});e.oninput=()=>{r.disabled=!e.value.trim(),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,120)}px`};let s=k("form",{},e,r),n=()=>{let i=e.value.trim();!i||!this.thread||(e.value="",e.oninput?.(new Event("input")),this.send({clientMessageId:Xr(),text:i,failed:!1}))};return s.onsubmit=i=>{i.preventDefault(),n()},e.onkeydown=i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&(i.preventDefault(),n())},s}async send(e){let r=this.thread;if(!(!r||!this.client)){e.failed=!1,r.pending.includes(e)||r.pending.push(e),this.renderMessages(!0);try{let s=await this.client.sendMessage({conversationId:r.conversation.id,text:e.text,clientMessageId:e.clientMessageId});if(this.thread!==r)return;r.pending=r.pending.filter(n=>n!==e),r.messages.set(s.id,s)}catch{e.failed=!0}this.renderMessages(!0)}}markThreadRead(){let e=this.thread;if(!e||!this.client||!this.isOpen)return;this.client.markConversationRead(e.conversation.id).catch(()=>{});let r=this.inbox.find(s=>s.conversation.id===e.conversation.id);r&&(r.isUnread=!1,r.unreadCount=0,this.updateLauncher())}showCenter(e,r=!1){let s=[k("p",{className:r?"error":"",textContent:e})];r&&s.push(k("button",{type:"button",className:"primary",textContent:"Try again",onclick:()=>{this.connect()}}));let n=k("div",{className:"center"},...s);n.setAttribute("role",r?"alert":"status"),this.body.replaceChildren(n)}};function li(t,e){if(typeof document>"u")throw new TypeError("ConvoKitWidget: start() must run in a browser");let r=ss(t),s=()=>new cr(r,e);return document.body?s():new Promise(n=>document.addEventListener("DOMContentLoaded",()=>n(s()),{once:!0}))}window.ConvoKitWidget={start:li};})();