PageSourceSearch

https://pulsebrand.io/assets/client-DhnN2Pqr.js

js pulsebrand.io collected 2026-10-06 18:34:57 UTC 168,054 bytes, 43 lines download raw bytes

1import{c as m,t as fr,a as Pe}from"./tslib.es6-Ds0fHAFP.js";import{aF as gr}from"./index-B3qwBxOP.js";function pr(i,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in i)){const n=Object.getOwnPropertyDescriptor(r,s);n&&Object.defineProperty(i,s,n.get?n:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}))}const vr=i=>i?(...e)=>i(...e):(...e)=>fetch(...e);class Qe extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class _r extends Qe{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class at extends Qe{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class lt extends Qe{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var qe;(function(i){i.Any="any",i.ApNortheast1="ap-northeast-1",i.ApNortheast2="ap-northeast-2",i.ApSouth1="ap-south-1",i.ApSoutheast1="ap-southeast-1",i.ApSoutheast2="ap-southeast-2",i.CaCentral1="ca-central-1",i.EuCentral1="eu-central-1",i.EuWest1="eu-west-1",i.EuWest2="eu-west-2",i.EuWest3="eu-west-3",i.SaEast1="sa-east-1",i.UsEast1="us-east-1",i.UsWest1="us-west-1",i.UsWest2="us-west-2"})(qe||(qe={}));class wr{constructor(e,{headers:t={},customFetch:r,region:s=qe.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=vr(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return m(this,arguments,void 0,function*(t,r={}){var s;let n,o;try{const{headers:a,method:l,body:u,signal:c,timeout:f}=r;let d={},{region:h}=r;h||(h=this.region);const p=new URL(`${this.url}/${t}`);h&&h!=="any"&&(d["x-region"]=h,p.searchParams.set("forceFunctionRegion",h));let v;u&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(d["Content-Type"]="application/octet-stream",v=u):typeof u=="string"?(d["Content-Type"]="text/plain",v=u):typeof FormData<"u"&&u instanceof FormData?v=u:(d["Content-Type"]="application/json",v=JSON.stringify(u)):v=u;let g=c;f&&(o=new AbortController,n=setTimeout(()=>o.abort(),f),c?(g=o.signal,c.addEventListener("abort",()=>o.abort())):g=o.signal);const b=yield this.fetch(p.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),a),body:v,signal:g}).catch(T=>{throw new _r(T)}),w=b.headers.get("x-relay-error");if(w&&w==="true")throw new at(b);if(!b.ok)throw new lt(b);let _=((s=b.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),S;return _==="application/json"?S=yield b.json():_==="application/octet-stream"||_==="application/pdf"?S=yield b.blob():_==="text/event-stream"?S=b:_==="multipart/form-data"?S=yield b.formData():S=yield b.text(),{data:S,error:null,response:b}}catch(a){return{data:null,error:a,response:a instanceof lt||a instanceof at?a.context:void 0}}finally{n&&clearTimeout(n)}})}}var C={};const ae=gr(fr);var _e={},we={},ye={},me={},be={},Ee={},ut;function Ut(){if(ut)return Ee;ut=1,Object.defineProperty(Ee,"__esModule",{value:!0});class i extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.co
1de=t.code}}return Ee.default=i,Ee}var ct;function xt(){if(ct)return be;ct=1,Object.defineProperty(be,"__esModule",{value:!0});const e=ae.__importDefault(Ut());class t{constructor(s){var n,o;this.shouldThrowOnError=!1,this.method=s.method,this.url=s.url,this.headers=new Headers(s.headers),this.schema=s.schema,this.body=s.body,this.shouldThrowOnError=(n=s.shouldThrowOnError)!==null&&n!==void 0?n:!1,this.signal=s.signal,this.isMaybeSingle=(o=s.isMaybeSingle)!==null&&o!==void 0?o:!1,s.fetch?this.fetch=s.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,n){return this.headers=new Headers(this.headers),this.headers.set(s,n),this}then(s,n){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");const o=this.fetch;let a=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async l=>{var u,c,f,d;let h=null,p=null,v=null,g=l.status,b=l.statusText;if(l.ok){if(this.method!=="HEAD"){const T=await l.text();T===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((u=this.headers.get("Accept"))===null||u===void 0)&&u.includes("application/vnd.pgrst.plan+text"))?p=T:p=JSON.parse(T))}const _=(c=this.headers.get("Prefer"))===null||c===void 0?void 0:c.match(/count=(exact|planned|estimated)/),S=(f=l.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");_&&S&&S.length>1&&(v=parseInt(S[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(p)&&(p.length>1?(h={code:"PGRST116",details:`Results contain ${p.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},p=null,v=null,g=406,b="Not Acceptable"):p.length===1?p=p[0]:p=null)}else{const _=await l.text();try{h=JSON.parse(_),Array.isArray(h)&&l.status===404&&(p=[],h=null,g=200,b="OK")}catch{l.status===404&&_===""?(g=204,b="No Content"):h={message:_}}if(h&&this.isMaybeSingle&&(!((d=h==null?void 0:h.details)===null||d===void 0)&&d.includes("0 rows"))&&(h=null,g=200,b="OK"),h&&this.shouldThrowOnError)throw new e.default(h)}return{error:h,data:p,count:v,status:g,statusText:b}});return this.shouldThrowOnError||(a=a.catch(l=>{var u,c,f,d,h,p;let v="";const g=l==null?void 0:l.cause;if(g){const b=(u=g==null?void 0:g.message)!==null&&u!==void 0?u:"",w=(c=g==null?void 0:g.code)!==null&&c!==void 0?c:"";v=`${(f=l==null?void 0:l.name)!==null&&f!==void 0?f:"FetchError"}: ${l==null?void 0:l.message}`,v+=`
2
3Caused by: ${(d=g==null?void 0:g.name)!==null&&d!==void 0?d:"Error"}: ${b}`,w&&(v+=` (${w})`),g!=null&&g.stack&&(v+=`
4${g.stack}`)}else v=(h=l==null?void 0:l.stack)!==null&&h!==void 0?h:"";return{error:{message:`${(p=l==null?void 0:l.name)!==null&&p!==void 0?p:"FetchError"}: ${l==null?void 0:l.message}`,details:v,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),a.then(s,n)}returns(){return this}overrideTypes(){return this}}return be.default=t,be}var ht;function Nt(){if(ht)return me;ht=1,Object.defineProperty(me,"__esModule",{value:!0});const e=ae.__importDefault(xt());class t extends e.default{select(s){let n=!1;const o=(s??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:n=!0,nullsFirst:o,foreignTable:a,referencedTable:l=a}={}){const u=l?`${l}.order`:"order",c=this.url.searchParams.get(u);return this.url.searchParams.set(u,`${c?`${c},`:""}${s}.${n?"asc":"desc"}${o===void 0?"":o?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:n,referencedTable:o=n}={}){const a=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(a,`${s}`),this}range(s,n,{foreignTable:o,referencedTable:a=o}={}){const l=typeof a>"u"?"offset":`${a}.offset`,u=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(l,`${s}`),this.url.searchParams.set(u,`${n-s+1}`),this}abortSignal(s){return this.signal=s,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}
4explain({analyze:s=!1,verbose:n=!1,settings:o=!1,buffers:a=!1,wal:l=!1,format:u="text"}={}){var c;const f=[s?"analyze":null,n?"verbose":null,o?"settings":null,a?"buffers":null,l?"wal":null].filter(Boolean).join("|"),d=(c=this.headers.get("Accept"))!==null&&c!==void 0?c:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${u}; for="${d}"; options=${f};`),u==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}}return me.default=t,me}var dt;function Xe(){if(dt)return ye;dt=1,Object.defineProperty(ye,"__esModule",{value:!0});const e=ae.__importDefault(Nt()),t=new RegExp("[,()]");class r extends e.default{eq(n,o){return this.url.searchParams.append(n,`eq.${o}`),this}neq(n,o){return this.url.searchParams.append(n,`neq.${o}`),this}gt(n,o){return this.url.searchParams.append(n,`gt.${o}`),this}gte(n,o){return this.url.searchParams.append(n,`gte.${o}`),this}lt(n,o){return this.url.searchParams.append(n,`lt.${o}`),this}lte(n,o){return this.url.searchParams.append(n,`lte.${o}`),this}like(n,o){return this.url.searchParams.append(n,`like.${o}`),this}likeAllOf(n,o){return this.url.searchParams.append(n,`like(all).{${o.join(",")}}`),this}likeAnyOf(n,o){return this.url.searchParams.append(n,`like(any).{${o.join(",")}}`),this}ilike(n,o){return this.url.searchParams.append(n,`ilike.${o}`),this}ilikeAllOf(n,o){return this.url.searchParams.append(n,`ilike(all).{${o.join(",")}}`),this}ilikeAnyOf(n,o){return this.url.searchParams.append(n,`ilike(any).{${o.join(",")}}`),this}regexMatch(n,o){return this.url.searchParams.append(n,`match.${o}`),this}regexIMatch(n,o){return this.url.searchParams.append(n,`imatch.${o}`),this}is(n,o){return this.url.searchParams.append(n,`is.${o}`),this}isDistinct(n,o){return this.url.searchParams.append(n,`isdistinct.${o}`),this}in(n,o){const a=Array.from(new Set(o)).map(l=>typeof l=="string"&&t.test(l)?`"${l}"`:`${l}`).join(",");return this.url.searchParams.append(n,`in.(${a})`),this}contains(n,o){return typeof o=="string"?this.url.searchParams.append(n,`cs.${o}`):Array.isArray(o)?this.url.searchParams.append(n,`cs.{${o.join(",")}}`):this.url.searchParams.append(n,`cs.${JSON.stringify(o)}`),this}containedBy(n,o){return typeof o=="string"?this.url.searchParams.append(n,`cd.${o}`):Array.isArray(o)?this.url.searchParams.append(n,`cd.{${o.join(",")}}`):this.url.searchParams.append(n,`cd.${JSON.stringify(o)}`),this}rangeGt(n,o){return this.url.searchParams.append(n,`sr.${o}`),this}rangeGte(n,o){return this.url.searchParams.append(n,`nxl.${o}`),this}rangeLt(n,o){return this.url.searchParams.append(n,`sl.${o}`),this}rangeLte(n,o){return this.url.searchParams.append(n,`nxr.${o}`),this}rangeAdjacent(n,o){return this.url.searchParams.append(n,`adj.${o}`),this}overlaps(n,o){return typeof o=="string"?this.url.searchParams.append(n,`ov.${o}`):this.url.searchParams.append(n,`ov.{${o.join(",")}}`),this}textSearch(n,o,{config:a,type:l}={}){let u="";l==="plain"?u="pl":l==="phrase"?u="ph":l==="websearch"&&(u="w");const c=a===void 0?"":`(${a})`;return this.url.searchParams.append(n,`${u}fts${c}.${o}`),this}match(n){return Object.entries(n).forEach(([o,a])=>{this.url.searchParams.append(o,`eq.${a}`)}),this}not(n,o,a){return this.url.searchParams.append(n,`not.${o}.${a}`),this}or(n,{foreignTable:o,referencedTable:a=o}={}){const l=a?`${a}.or`:"or";return this.url.searchParams.append(l,`(${n})`),this}filter(n,o,a){return this.url.searchParams.append(n,`${o}.${a}`),this}}return ye.default=r,ye}var ft;function Dt(){if(ft)return we;ft=1,Object.defineProperty(we,"__esModule",{value:!0});const e=ae.__importDefault(Xe());class t{constructor(s,{headers:n={},schema:o,fetch:a}){this.url=s,this.headers=new Headers(n),this.schema=o,this.fetch=a}select(s,n){const{head:o=!1,count:a}=n??{},l=o?"HEAD":"GET";let u=!1;const c=(s??"*").split("").map(f=>/\s/.test(f)&&!u?"":(f==='"'&&(u=!u),f)).join("");return this.url.searchParams.set("select",c),a&&this.headers.append("Prefer",`count=${a}`),new e.default({method:l,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(s,{count:n,defaultToNull:o=!0}={}){var a;const l="POST";if(n&&this.headers.append("Prefer",`count=${n}`),o||this.headers.append("Prefer","missing=default"),Array.isArray(s)){const u=s.reduce((c,f)=>c.concat(Object.keys(f)),[]);if(u.length>0){const c=[...new Set(u)].map(f=>`"${f}"`);this.url.searchParams.set("columns",c.join(","))}}return new e.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}upsert(s,{onConflict:n,ignoreDuplicates:o=!1,count:a,defaultToNull:l=!0}={}){var u;const c="POST";if(this.headers.append("Prefer",`resolution=${o?"ignore":"merge"}-duplicates`),n!==void 0&&this.url.searchParams.set("on_conflict",n),a&&this.headers.append("Prefer",`count=${a}`),l||this.headers.append("Prefer","missing=default"),Array.isArray(s)){const f=s.reduce((d,h)=>d.concat(Object.keys(h)),[]);if(f.length>0){const d=[...new Set(f)].map(h=>`"${h}"`);this.url.searchParams.set("columns",d.join(","))}}return new e.default({method:c,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:(u=this.fetch)!==null&&u!==void 0?u:fetch})}update(s,{count:n}={}){var o;const a="PATCH";return n&&this.headers.append("Prefer",`count=${n}`),new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:s,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}delete({count:s}={}){var n;const o="DELETE";return s&&this.headers.append("Prefer",`count=${s}`),new e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch})}}return we.default=t,we}var gt;function yr(){if(gt)return _e;
4gt=1,Object.defineProperty(_e,"__esModule",{value:!0});const i=ae,e=i.__importDefault(Dt()),t=i.__importDefault(Xe());class r{constructor(n,{headers:o={},schema:a,fetch:l}={}){this.url=n,this.headers=new Headers(o),this.schemaName=a,this.fetch=l}from(n){if(!n||typeof n!="string"||n.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");const o=new URL(`${this.url}/${n}`);return new e.default(o,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(n){return new r(this.url,{headers:this.headers,schema:n,fetch:this.fetch})}rpc(n,o={},{head:a=!1,get:l=!1,count:u}={}){var c;let f;const d=new URL(`${this.url}/rpc/${n}`);let h;a||l?(f=a?"HEAD":"GET",Object.entries(o).filter(([v,g])=>g!==void 0).map(([v,g])=>[v,Array.isArray(g)?`{${g.join(",")}}`:`${g}`]).forEach(([v,g])=>{d.searchParams.append(v,g)})):(f="POST",h=o);const p=new Headers(this.headers);return u&&p.set("Prefer",`count=${u}`),new t.default({method:f,url:d,headers:p,schema:this.schemaName,body:h,fetch:(c=this.fetch)!==null&&c!==void 0?c:fetch})}}return _e.default=r,_e}Object.defineProperty(C,"__esModule",{value:!0});var Lt=C.PostgrestError=zt=C.PostgrestBuilder=Ht=C.PostgrestTransformBuilder=Ft=C.PostgrestFilterBuilder=Wt=C.PostgrestQueryBuilder=qt=C.PostgrestClient=void 0;const le=ae,Bt=le.__importDefault(yr());var qt=C.PostgrestClient=Bt.default;const Mt=le.__importDefault(Dt());var Wt=C.PostgrestQueryBuilder=Mt.default;const Vt=le.__importDefault(Xe());var Ft=C.PostgrestFilterBuilder=Vt.default;const Kt=le.__importDefault(Nt());var Ht=C.PostgrestTransformBuilder=Kt.default;const Jt=le.__importDefault(xt());var zt=C.PostgrestBuilder=Jt.default;const Gt=le.__importDefault(Ut());Lt=C.PostgrestError=Gt.default;var Yt=C.default={PostgrestClient:Bt.default,PostgrestQueryBuilder:Mt.default,PostgrestFilterBuilder:Vt.default,PostgrestTransformBuilder:Kt.default,PostgrestBuilder:Jt.default,PostgrestError:Gt.default};const mr=pr({__proto__:null,get PostgrestBuilder(){return zt},get PostgrestClient(){return qt},get PostgrestError(){return Lt},get PostgrestFilterBuilder(){return Ft},get PostgrestQueryBuilder(){return Wt},get PostgrestTransformBuilder(){return Ht},default:Yt},[C]),{PostgrestClient:br,PostgrestQueryBuilder:Ni,PostgrestFilterBuilder:Di,PostgrestTransformBuilder:Li,PostgrestBuilder:Bi,PostgrestError:qi}=Yt||mr;class Er{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.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"&&globalThis.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."};if(typeof process<"u"){const t=process.versions;if(t&&t.node){const r=t.node,s=parseInt(r.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
5import ws from "ws"
6new RealtimeClient(url, { transport: ws })`}}}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(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`
7
8Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){const r=this.getWebSocketConstructor();return new r(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const Sr="2.84.0",kr=`realtime-js/${Sr}`,Qt="1.0.0",Or="2.0.0",pt=Qt,Me=1e4,Tr=1e3,Rr=100;var z;(function(i){i[i.connecting=0]="connecting",i[i.open=1]="open",i[i.closing=2]="closing",i[i.closed=3]="closed"})(z||(z={}));var j;(function(i){i.closed="closed",i.errored="errored",i.joined="joined",i.joining="joining",i.leaving="leaving"})(j||(j={}));var q;(function(i){i.close="phx_close",i.error="phx_error",i.join="phx_join",i.reply="phx_reply",i.leave="phx_leave",i.access_token="access_token"})(q||(q={}));var We;(function(i){i.websocket="websocket"})(We||(We={}));var G;(function(i){i.Connecting="connecting",i.Open="open",i.Closing="closing",i.Closed="closed"})(G||(G={}));class Ar{constructor(){this.HEADER_LENGTH=1,this.META_LENGTH=4,this.USER_BROADCAST_PUSH_META_LENGTH=5,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast"}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer((t=e.payload)===null||t===void 0?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r,s,n;const o=e.topic,a=(t=e.ref)!==null&&t!==void 0?t:"",l=(r=e.join_ref)!==null&&r!==void 0?r:"",u=e.payload.event,c=(n=(s=e.payload)===null||s===void 0?void 0:s.payload)!==null&&n!==void 0?n:new ArrayBuffer(0),f=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+u.length,d=new ArrayBuffer(this.HEADER_LENGTH+f);let h=new DataView(d),p=0;h.setUint8(p++,this.KINDS.userBroadcastPush),h.setUint8(p++,l.length),h.setUint8(p++,a.length),h.setUint8(p++,o.length),h.setUint8(p++,u.length),h.setUint8(p++,this.BINARY_ENCODING),Array.from(l,g=>h.setUint8(p++,g.charCodeAt(0))),Array.from(a,g=>h.setUint8(p++,g.charCodeAt(0))),Array.from(o,g=>h.setUint8(p++,g.charCodeAt(0))),Array.from(u,g=>h.setUint8(p++,g.charCodeAt(0)));var v=new Uint8Array(d.byteLength+c.byteLength);return v.set(new Uint8Array(d),0),v.set(new Uint8Array(c),d.byteLength),v.buffer}_encodeJsonUserBroadcastPush(e){var t,r,s,n;const o=e.topic,a=(t=e.ref)!==null&&t!==void 0?t:"",l=(r=e.join_ref)!==null&&r!==void 0?r:"",u=e.payload.event,c=(n=(s=e.payload)===null||s===void 0?void 0:s.payload)!==null&&n!==void 0?n:{},d=new TextEncoder().encode(JSON.stringify(c)).buffer,h=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+u.length,p=new ArrayBuffer(this.HEADER_LENGTH+h);let v=new DataView(p),g=0;v.setUint8(g++,this.KINDS.userBroadcastPush),v.setUint8(g++,l.length),v.setUint8(g++,a.length),v.setUint8(g++,o.length),v.setUint8(g++,u.length),v.setUint8(g++,this.JSON_ENCODING),Array.from(l,w=>
8v.setUint8(g++,w.charCodeAt(0))),Array.from(a,w=>v.setUint8(g++,w.charCodeAt(0))),Array.from(o,w=>v.setUint8(g++,w.charCodeAt(0))),Array.from(u,w=>v.setUint8(g++,w.charCodeAt(0)));var b=new Uint8Array(p.byteLength+d.byteLength);return b.set(new Uint8Array(p),0),b.set(new Uint8Array(d),p.byteLength),b.buffer}decode(e,t){if(this._isArrayBuffer(e)){let r=this._binaryDecode(e);return t(r)}if(typeof e=="string"){const r=JSON.parse(e),[s,n,o,a,l]=r;return t({join_ref:s,ref:n,topic:o,event:a,payload:l})}return t({})}_binaryDecode(e){const t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,t,s)}}_decodeUserBroadcast(e,t,r){const s=t.getUint8(1),n=t.getUint8(2),o=t.getUint8(3),a=t.getUint8(4);let l=this.HEADER_LENGTH+4;const u=r.decode(e.slice(l,l+s));l=l+s;const c=r.decode(e.slice(l,l+n));l=l+n;const f=r.decode(e.slice(l,l+o));l=l+o;const d=e.slice(l,e.byteLength),h=a===this.JSON_ENCODING?JSON.parse(r.decode(d)):d,p={type:this.BROADCAST_EVENT,event:c,payload:h};return o>0&&(p.meta=JSON.parse(f)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||((t=e==null?void 0:e.constructor)===null||t===void 0?void 0:t.name)==="ArrayBuffer"}}class Xt{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var O;(function(i){i.abstime="abstime",i.bool="bool",i.date="date",i.daterange="daterange",i.float4="float4",i.float8="float8",i.int2="int2",i.int4="int4",i.int4range="int4range",i.int8="int8",i.int8range="int8range",i.json="json",i.jsonb="jsonb",i.money="money",i.numeric="numeric",i.oid="oid",i.reltime="reltime",i.text="text",i.time="time",i.timestamp="timestamp",i.timestamptz="timestamptz",i.timetz="timetz",i.tsrange="tsrange",i.tstzrange="tstzrange"})(O||(O={}));const vt=(i,e,t={})=>{var r;const s=(r=t.skipTypes)!==null&&r!==void 0?r:[];return e?Object.keys(e).reduce((n,o)=>(n[o]=Pr(o,i,e,s),n),{}):{}},Pr=(i,e,t,r)=>{const s=e.find(a=>a.name===i),n=s==null?void 0:s.type,o=t[i];return n&&!r.includes(n)?Zt(n,o):Ve(o)},Zt=(i,e)=>{if(i.charAt(0)==="_"){const t=i.slice(1,i.length);return $r(e,t)}switch(i){case O.bool:return jr(e);case O.float4:case O.float8:case O.int2:case O.int4:case O.int8:case O.numeric:case O.oid:return Ir(e);case O.json:case O.jsonb:return Cr(e);case O.timestamp:return Ur(e);case O.abstime:case O.date:case O.daterange:case O.int4range:case O.int8range:case O.money:case O.reltime:case O.text:case O.time:case O.timestamptz:case O.timetz:case O.tsrange:case O.tstzrange:return Ve(e);default:return Ve(e)}},Ve=i=>i,jr=i=>{switch(i){case"t":return!0;case"f":return!1;default:return i}},Ir=i=>{if(typeof i=="string"){const e=parseFloat(i);if(!Number.isNaN(e))return e}return i},Cr=i=>{if(typeof i=="string")try{return JSON.parse(i)}catch(e){return console.log(`JSON parse error: ${e}`),i}return i},$r=(i,e)=>{if(typeof i!="string")return i;const t=i.length-1,r=i[t];if(i[0]==="{"&&r==="}"){let n;const o=i.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>Zt(e,a))}return i},Ur=i=>typeof i=="string"?i.replace(" ","T"):i,er=i=>{const e=new URL(i);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};class Ie{constructor(e,t,r={},s=Me){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,j
8oin_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var _t;(function(i){i.SYNC="sync",i.JOIN="join",i.LEAVE="leave"})(_t||(_t={}));class ce{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(t==null?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},s=>{const{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=ce.syncState(this.state,s,n,o),this.pendingDiffs.forEach(l=>{this.state=ce.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},s=>{const{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=ce.syncDiff(this.state,s,n,o),a())}),this.onJoin((s,n,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:n,newPresences:o})}),this.onLeave((s,n,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){const n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(u,c)=>{o[u]||(l[u]=c)}),this.map(o,(u,c)=>{const f=n[u];if(f){const d=c.map(g=>g.presence_ref),h=f.map(g=>g.presence_ref),p=c.filter(g=>h.indexOf(g.presence_ref)<0),v=f.filter(g=>d.indexOf(g.presence_ref)<0);p.length>0&&(a[u]=p),v.length>0&&(l[u]=v)}else a[u]=c}),this.syncDiff(n,{joins:a,leaves:l},r,s)}static syncDiff(e,t,r,s){const{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(n,(a,l)=>{var u;const c=(u=e[a])!==null&&u!==void 0?u:[];if(e[a]=this.cloneDeep(l),c.length>0){const f=e[a].map(h=>h.presence_ref),d=c.filter(h=>f.indexOf(h.presence_ref)<0);e[a].unshift(...d)}r(a,c,l)}),this.map(o,(a,l)=>{let u=e[a];if(!u)return;const c=l.map(f=>f.presence_ref);u=u.filter(f=>c.indexOf(f.presence_ref)<0),e[a]=u,s(a,u,l),u.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const s=e[r];return"metas"in s?t[r]=s.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var wt;(function(i){i.ALL="*",i.INSERT="INSERT",i.UPDATE="UPDATE",i.DELETE="DELETE"})(wt||(wt={}));var he;(function(i){i.BROADCAST="broadcast",i.PRESENCE="presence",i.POSTGRES_CHANGES="postgres_changes",i.SYSTEM="system"})(he||(he={}));var M;(function(i){i.SUBSCRIBED="SUBSCRIBED",i.TIMED_OUT="TIMED_OUT",i.CLOSED="CLOSED",i.CHANNEL_ERROR="CHANNEL_ERROR"})(M||(M={}));class Ze{constructor(e,t={config:{}},r){var s,n;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=j.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new Ie(this,q.join,this.params,this.timeout),this.rejoinTimer=new Xt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=j.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=j.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=j.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=j.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=j.errored,this.rejoinTimer.scheduleTimeout())}),this._on(q.reply,{},(o,a)=>{this._trigger(this._replyEventName(a),o)}),this.presence=new ce(this),this.broadcastEndpointURL=er(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((n=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||n===void 0)&&n.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,s,n;if(this.socket.isConnected()||this.socket.connect(),this.state==j.closed){const{config:{broadcast:o,presence:a,private:l}}=this.params,u=(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(h=>h.filter))!==null&&s!==void 0?s:[],c=!!this.bindings[he.PRESENCE]&&this.bindings[he.PRESENCE].length>0||((n=this.params.config.presence)===null||n===void 0?void 0:n.enabled)===!0,f={},d={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this._onError(h=>e==null?void 0:e(M.CHANNEL_ERROR,h)),this._onClose(()=>e==null?void 0:e(M.CLOSED)),this.updateJoinPayload(Object.assign({config:d},f)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:h})=>{var p;if(this.socket.setAuth(),h===void 0){e==null||e(M.SUBSCRIBED);return}else{const v=this.bindings.postgres_changes,g=(p=v==null?void 0:v.length)!==null&&p!==void 0?p:0,b=[];for(let w=0;w<g;w++){const _=v[w],{filter:{event:S,schema:T,table:k,filter:A}}=_,D=h&&h[w];if(D&&D.event===S&&D.schema===T&&D.table===k&&D.filter===A)b.push(Object.assign(Object.assign({},_),{id:D.id}));else{this.unsubscribe(),this.state=j.errored,e==null||e(M.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=b,e&&e(M.SUBSCRIBED);return}}).receive("error",h=>{this.state=j.errored,e==null||e(M.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(M.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===j.joined&&e===he.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,t,r)}async httpSend(e,t,r={}){var s;const n=this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"";if(t==null)return Promise.reject("Payload is required for httpSend()");const o={method:"POST",headers:{Authorization:n,apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;
8try{const u=await a.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(e,t={}){var r,s;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:n,payload:o}=e,l={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((s=u.body)===null||s===void 0?void 0:s.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;const u=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),u.receive("ok",()=>n("ok")),u.receive("error",()=>n("error")),u.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=j.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(q.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{r=new Ie(this,q.leave,{},e),r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{r==null||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=j.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const s=new AbortController,n=setTimeout(()=>s.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new Ie(this,e,t,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>Rr){const t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,n;const o=e.toLocaleLowerCase(),{close:a,error:l,leave:u,join:c}=q;if(r&&[a,l,u,c].indexOf(o)>=0&&r!==this._joinRef())return;let d=this._onMessage(o,t,r);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(h=>{var p,v,g;return((p=h.filter)===null||p===void 0?void 0:p.event)==="*"||((g=(v=h.filter)===null||v===void 0?void 0:v.event)===null||g===void 0?void 0:g.toLocaleLowerCase())===o}).map(h=>h.callback(d,r)):(n=this.bindings[o])===null||n===void 0||n.filter(h=>{var p,v,g,b,w,_;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in h){const S=h.id,T=(p=h.filter)===null||p===void 0?void 0:p.event;return S&&((v=t.ids)===null||v===void 0?void 0:v.includes(S))&&(T==="*"||(T==null?void 0:T.toLocaleLowerCase())===((g=t.data)===null||g===void 0?void 0:g.type.toLocaleLowerCase()))}else{const S=(w=(b=h==null?void 0:h.filter)===null||b===void 0?void 0:b.event)===null||w===void 0?void 0:w.toLocaleLowerCase();return S==="*"||S===((_=t==null?void 0:t.event)===null||_===void 0?void 0:_.toLocaleLowerCase())}else return h.type.toLocaleLowerCase()===o}).map(h=>{if(typeof d=="object"&&"ids"in d){const p=d.data,{schema:v,table:g,commit_timestamp:b,type:w,errors:_}=p;d=Object.assign(Object.assign({},{schema:v,table:g,commit_timestamp:b,eventType:w,new:{},old:{},errors:_}),this._getPayloadRecords(p))}h.callback(d,r)})}_isClosed(){return this.state===j.closed}_isJoined(){return this.state===j.joined}_isJoining(){return this.state===j.joining}_isLeaving(){return this.state===j.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const s=e.toLocaleLowerCase(),n={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(n):this.bindings[s]=[n],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(s=>{var n;return!(((n=s.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&Ze.isEqual(s.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(q.close,{},e)}_onError(e){this._on(q.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=j.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=vt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=vt(e.columns,e.old_record)),t}}const Ce=()=>{},Se={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},xr=[1e3,2e3,5e3,1e4],Nr=1e4,Dr=`
9  addEventListener("message", (e) => {
10    if (e.data.event === "start") {
11      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
12    }
13  });`;class Lr{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=Me,this.transport=null,this.heartbeatIntervalMs=Se.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Ce,this.ref=0,this.reconnectTimer=null,this.vsn=pt,this.logger=Ce,this.conn=null,this.sendBuffer=[],this.serializer
13=new Ar,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=s=>s?(...n)=>s(...n):(...n)=>fetch(...n),!(!((r=t==null?void 0:t.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${We.websocket}`,this.httpEndpoint=er(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t==null?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=Er.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t}
14
15To use Realtime in Node.js, you need to provide a WebSocket implementation:
16
17Option 1: Use Node.js 22+ which has native WebSocket support
18Option 2: Install and provide the "ws" package:
19
20  npm install ws
21
22  import ws from "ws"
23  const client = new RealtimeClient(url, {
24    ...options,
25    transport: ws
26  })`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,t??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case z.connecting:return G.Connecting;case z.open:return G.Open;case z.closing:return G.Closing;default:return G.Closed}}isConnected(){return this.connectionState()===G.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){const r=`realtime:${e}`,s=this.getChannels().find(n=>n.topic===r);if(s)return s;{const n=new Ze(`realtime:${e}`,t,this);return this.channels.push(n),n}}push(e){const{topic:t,event:r,payload:s,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${r} (${n})`,s),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,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._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(Tr,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},Se.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),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._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>
260&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply")try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error")}catch(u){this.log("error","error in heartbeat callback",u)}t.ref&&t.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:r,event:s,payload:n,ref:o}=t,a=o?`(${o})`:"",l=n.status||"";this.log("receive",`${l} ${r} ${s} ${a}`.trim(),n),this.channels.filter(u=>u._isMember(r)).forEach(u=>u._trigger(s,n,o)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){if(this.conn){if(this.conn.readyState===z.open||this.conn.readyState===z.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(t=>{this.log("error","error waiting for auth on connect",t),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(q.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const r=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${r}${s}`}_workerObjectUrl(e){let t;if(e)t=e;else{const r=new Blob([Dr],{type:"application/javascript"});t=URL.createObjectURL(r)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;e?t=e:this.accessToken?t=await this.accessToken():t=this.accessTokenValue,this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(r=>{const s={access_token:t,version:kr};t&&r.updateJoinPayload(s),r.joinedOnce&&r._isJoined()&&r._push(q.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this.setAuth().catch(t=>{this.log("error",`error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(t)}catch(s){this.log("error",`error in ${e} callback`,s)}})}catch(r){this.log("error",`error triggering ${e} callbacks`,r)}}_setupReconnectionTimer(){this.reconnectTimer=new Xt(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Se.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,s,n,o,a,l,u,c,f,d,h;switch(this.transport=(t=e==null?void 0:e.transport)!==null&&t!==void 0?t:null,this.timeout=(r=e==null?void 0:e.timeout)!==null&&r!==void 0?r:Me,this.heartbeatIntervalMs=(s=e==null?void 0:e.heartbeatIntervalMs)!==null&&s!==void 0?s:Se.HEARTBEAT_INTERVAL,this.worker=(n=e==null?void 0:e.worker)!==null&&n!==void 0?n:!1,this.accessToken=(o=e==null?void 0:e.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=e==null?void 0:e.heartbeatCallback)!==null&&a!==void 0?a:Ce,this.vsn=(l=e==null?void 0:e.vsn)!==null&&l!==void 0?l:pt,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(u=e==null?void 0:e.reconnectAfterMs)!==null&&u!==void 0?u:p=>xr[p-1]||Nr,this.vsn){case Qt:this.encode=(c=e==null?void 0:e.encode)!==null&&c!==void 0?c:(p,v)=>v(JSON.stringify(p)),this.decode=(f=e==null?void 0:e.decode)!==null&&f!==void 0?f:(p,v)=>v(JSON.parse(p));break;case Or:this.encode=(d=e==null?void 0:e.encode)!==null&&d!==void 0?d:this.serializer.encode.bind(this.serializer),this.decode=(h=e==null?void 0:e.decode)!==null&&h!==void 0?h:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}}
26class et extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function R(i){return typeof i=="object"&&i!==null&&"__isStorageError"in i}class Br extends et{constructor(e,t,r){super(e),this.name="StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class Fe extends et{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}const tt=i=>i?(...e)=>i(...e):(...e)=>fetch(...e),qr=()=>Response,Ke=i=>{if(Array.isArray(i))return i.map(t=>Ke(t));if(typeof i=="function"||i!==Object(i))return i;const e={};return Object.entries(i).forEach(([t,r])=>{const s=t.replace(/([-_][a-z])/gi,n=>n.toUpperCase().replace(/[-_]/g,""));e[s]=Ke(r)}),e},Mr=i=>{if(typeof i!="object"||i===null)return!1;const e=Object.getPrototypeOf(i);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in i)&&!(Symbol.iterator in i)},$e=i=>{var e;return i.msg||i.message||i.error_description||(typeof i.error=="string"?i.error:(e=i.error)===null||e===void 0?void 0:e.message)||JSON.stringify(i)},Wr=(i,e,t)=>m(void 0,void 0,void 0,function*(){const r=yield qr();i instanceof r&&!(t!=null&&t.noResolveJson)?i.json().then(s=>{const n=i.status||500,o=(s==null?void 0:s.statusCode)||n+"";e(new Br($e(s),n,o))}).catch(s=>{e(new Fe($e(s),s))}):e(new Fe($e(i),i))}),Vr=(i,e,t,r)=>{const s={method:i,headers:(e==null?void 0:e.headers)||{}};return i==="GET"||!r?s:(Mr(r)?(s.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),s.body=JSON.stringify(r)):s.body=r,e!=null&&e.duplex&&(s.duplex=e.duplex),Object.assign(Object.assign({},s),t))};function pe(i,e,t,r,s,n){return m(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,Vr(e,r,s,n)).then(l=>{if(!l.ok)throw l;return r!=null&&r.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Wr(l,a,r))})})}function de(i,e,t,r){return m(this,void 0,void 0,function*(){return pe(i,"GET",e,t,r)})}function B(i,e,t,r,s){return m(this,void 0,void 0,function*(){return pe(i,"POST",e,r,s,t)})}function He(i,e,t,r,s){return m(this,void 0,void 0,function*(){return pe(i,"PUT",e,r,s,t)})}function Fr(i,e,t,r){return m(this,void 0,void 0,function*(){return pe(i,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),r)})}function rt(i,e,t,r,s){return m(this,void 0,void 0,function*(){return pe(i,"DELETE",e,r,s,t)})}class Kr{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return m(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(R(e))return{data:null,error:e};throw e}})}}var tr;class Hr{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[tr]="BlobDownloadBuilder",this.promise=null}asStream(){return new Kr(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}execute(){return m(this,void 0,void 0,function*(){try{return{data:yield(yield this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(R(e))return{data:null,error:e};throw e}})}}tr=Symbol.toStringTag;const Jr={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},yt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class zr{constructor(e,t={},r,s){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=tt(s)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,r,s){return m(this,void 0,void 0,function*(){try{let n;const o=Object.assign(Object.assign({},yt),s);let a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),l&&n.append("metadata",this.encodeMetadata(l)),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.has("cacheControl")||n.append("cacheControl",o.cacheControl),l&&!n.has("metadata")&&n.append("metadata",this.encodeMetadata(l))):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(l))),(typeof ReadableStream<"u"&&n instanceof ReadableStream||n&&typeof n=="object"&&"pipe"in n&&typeof n.pipe=="function")&&!o.duplex&&(o.duplex="half")),s!=null&&s.headers&&(a=Object.assign(Object.assign({},a),s.headers));const u=this._removeEmptyFolders(t),c=this._getFinalPath(u),f=yield(e=="PUT"?He:B)(this.fetch,`${this.url}/object/${c}`,n,Object.assign({headers:a},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{data:{path:u,id:f.Id,fullPath:f.Key},error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(R(n))return{data:null,error:n};throw n}})}upload(e,t,r){return m(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,s){return m(this,void 0,void 0,function*(){const n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l;const u=Object.assign({upsert:yt.upsert},s),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(u.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",u.cacheControl)):(l=r,c["cac
26he-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType);const f=yield He(this.fetch,a.toString(),l,{headers:c});return{data:{path:n,fullPath:f.Key},error:null}}catch(l){if(this.shouldThrowOnError)throw l;if(R(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return m(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e);const s=Object.assign({},this.headers);t!=null&&t.upsert&&(s["x-upsert"]="true");const n=yield B(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:s}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new et("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(R(r))return{data:null,error:r};throw r}})}update(e,t,r){return m(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return m(this,void 0,void 0,function*(){try{return{data:yield B(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,de
26stinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(R(s))return{data:null,error:s};throw s}})}copy(e,t,r){return m(this,void 0,void 0,function*(){try{return{data:{path:(yield B(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers})).Key},error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(R(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,r){return m(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),n=yield B(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(R(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,r){return m(this,void 0,void 0,function*(){try{const s=yield B(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:s.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(R(s))return{data:null,error:s};throw s}})}download(e,t){const s=typeof(t==null?void 0:t.transform)<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),o=n?`?${n}`:"",a=this._getFinalPath(e),l=()=>de(this.fetch,`${this.url}/${s}/${a}${o}`,{headers:this.headers,noResolveJson:!0});return new Hr(l,this.shouldThrowOnError)}info(e){return m(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const r=yield de(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:Ke(r),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(R(r))return{data:null,error:r};throw r}})}exists(e){return m(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield Fr(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(R(r)&&r instanceof Fe){const s=r.originalError;if([400,404].includes(s==null?void 0:s.status))return{data:!1,error:r}}throw r}})}getPublicUrl(e,t){const r=this._getFinalPath(e),s=[],n=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&s.push(n);const a=typeof(t==null?void 0:t.transform)<"u"?"render/image":"object",l=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});l!==""&&s.push(l);let u=s.join("&");return u!==""&&(u=`?${u}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${u}`)}}}remove(e){return m(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(R(t))return{data:null,error:t};throw t}})}list(e,t,r){return m(this,void 0,void 0,function*(){try{const s=Object.assign(Object.assign(Object.assign({},Jr),t),{prefix:e||""});return{data:yield B(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(R(s))return{data:null,error:s};throw s}})}listV2(e,t){return m(this,void 0,void 0,function*(){try{const r=Object.assign({},e);return{data:yield B(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,r,{headers:this.headers},t),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(R(r))return{data:null,error:r};throw r}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const rr="2.84.0",sr={"X-Client-Info":`storage-js/${rr}`};class Gr{constructor(e,t={},r,s){this.shouldThrowOnError=!1;const n=new URL(e);s!=null&&s.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase.")),this.url=n.href.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},sr),t),this.fetch=tt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(e){return m(this,void 0,void 0,function*(){try{const t=this.listBucketOptionsToQueryString(e);return{data:yield de(this.fetch,`${this.url}/bucket${t}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;
26if(R(t))return{data:null,error:t};throw t}})}getBucket(e){return m(this,void 0,void 0,function*(){try{return{data:yield de(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(R(t))return{data:null,error:t};throw t}})}createBucket(e){return m(this,arguments,void 0,function*(t,r={public:!1}){try{return{data:yield B(this.fetch,`${this.url}/bucket`,{id:t,name:t,type:r.type,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(R(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return m(this,void 0,void 0,function*(){try{return{data:yield He(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(R(r))return{data:null,error:r};throw r}})}emptyBucket(e){return m(this,void 0,void 0,function*(){try{return{data:yield B(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(R(t))return{data:null,error:t};throw t}})}deleteBucket(e){return m(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(R(t))return{data:null,error:t};throw t}})}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}}class Yr{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},sr),t),this.fetch=tt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return m(this,void 0,void 0,function*(){try{return{data:yield B(this.fetch,`${this.url}/bucket`,{name:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(R(t))return{data:null,error:t};throw t}})}listBuckets(e){return m(this,void 0,void 0,function*(){try{const t=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&t.set("limit",e.limit.toString()),(e==null?void 0:e.offset)!==void 0&&t.set("offset",e.offset.toString()),e!=null&&e.sortColumn&&t.set("sortColumn",e.sortColumn),e!=null&&e.sortOrder&&t.set("sortOrder",e.sortOrder),e!=null&&e.search&&t.set("search",e.search);const r=t.toString(),s=r?`${this.url}/bucket?${r}`:`${this.url}/bucket`;return{data:yield de(this.fetch,s,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(R(t))return{data:null,error:t};throw t}})}deleteBucket(e){return m(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(R(t))return{data:null,error:t};throw t}})}}const st={"X-Client-Info":`storage-js/${rr}`,"Content-Type":"application/json"};class ir extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}}function U(i){return typeof i=="object"&&i!==null&&"__isStorageVectorsError"in i}class Ue extends ir{constructor(e,t,r){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class Qr extends ir{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}}var mt;(function(i){i.InternalError="InternalError",i.S3VectorConflictException="S3VectorConflictException",i.S3VectorNotFoundException="S3VectorNotFoundException",i.S3VectorBucketNotEmpty="S3VectorBucketNotEmpty",i.S3VectorMaxBucketsExceeded="S3VectorMaxBucketsExceeded",i.S3VectorMaxIndexesExceeded="S3VectorMaxIndexesExceeded"})(mt||(mt={}));const it=i=>i?(...e)=>i(...e):(...e)=>fetch(...e),Xr=i=>{if(typeof i!="object"||i===null)return!1;const e=Object.getPrototypeOf(i);
26return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in i)&&!(Symbol.iterator in i)},bt=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Zr=(i,e,t)=>m(void 0,void 0,void 0,function*(){if(i&&typeof i=="object"&&"status"in i&&"ok"in i&&typeof i.status=="number"&&!(t!=null&&t.noResolveJson)){const s=i.status||500,n=i;if(typeof n.json=="function")n.json().then(o=>{const a=(o==null?void 0:o.statusCode)||(o==null?void 0:o.code)||s+"";e(new Ue(bt(o),s,a))}).catch(()=>{const o=s+"",a=n.statusText||`HTTP ${s} error`;e(new Ue(a,s,o))});else{const o=s+"",a=n.statusText||`HTTP ${s} error`;e(new Ue(a,s,o))}}else e(new Qr(bt(i),i))}),es=(i,e,t,r)=>{const s={method:i,headers:(e==null?void 0:e.headers)||{}};return r?(Xr(r)?(s.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),s.body=JSON.stringify(r)):s.body=r,Object.assign(Object.assign({},s),t)):s};function ts(i,e,t,r,s,n){return m(this,void 0,void 0,function*(){return new Promise((o,a)=>{i(t,es(e,r,s,n)).then(l=>{if(!l.ok)throw l;if(r!=null&&r.noResolveJson)return l;const u=l.headers.get("content-type");return!u||!u.includes("application/json")?{}:l.json()}).then(l=>o(l)).catch(l=>Zr(l,a,r))})})}function x(i,e,t,r,s){return m(this,void 0,void 0,function*(){return ts(i,"POST",e,r,s,t)})}class rs{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},st),t),this.fetch=it(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createIndex(e){return m(this,void 0,void 0,function*(){try{return{data:(yield x(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}getIndex(e,t){return m(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(U(r))return{data:null,error:r};throw r}})}listIndexes(e){return m(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}deleteIndex(e,t){return m(this,void 0,void 0,function*(){try{return{data:(yield x(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(U(r))return{data:null,error:r};throw r}})}}class ss{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},st),t),this.fetch=it(r)}throwOnError(){return this.shouldThrowOnError=!0,this}putVectors(e){return m(this,void 0,void 0,function*(){try{if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:(yield x(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}getVectors(e){return m(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/GetVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}listVectors(e){return m(this,void 0,void 0,function*(){try{if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return{data:yield x(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}queryVectors(e){return m(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/QueryVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}deleteVectors(e){return m(this,void 0,void 0,function*(){try{if(e.keys.length<1||e.keys.length>
26500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:(yield x(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}}class is{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},st),t),this.fetch=it(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return m(this,void 0,void 0,function*(){try{return{data:(yield x(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}getBucket(e){return m(this,void 0,void 0,function*(){try{return{data:yield x(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}listBuckets(){return m(this,arguments,void 0,function*(e={}){try{return{data:yield x(this.fetch,`${this.url}/ListVectorBuckets`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}deleteBucket(e){return m(this,void 0,void 0,function*(){try{return{data:(yield x(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}}class ns extends is{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new os(this.url,this.headers,e,this.fetch)}}class os extends rs{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}createIndex(e){const t=Object.create(null,{createIndex:{get:()=>super.createIndex}});return m(this,void 0,void 0,function*(){return t.createIndex.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName}))})}listIndexes(){const e=Object.create(null,{listIndexes:{get:()=>super.listIndexes}});return m(this,arguments,void 0,function*(t={}){return e.listIndexes.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName}))})}getIndex(e){const t=Object.create(null,{getIndex:{get:()=>super.getIndex}});return m(this,void 0,void 0,function*(){return t.getIndex.call(this,this.vectorBucketName,e)})}deleteIndex(e){const t=Object.create(null,{deleteIndex:{get:()=>super.deleteIndex}});return m(this,void 0,void 0,function*(){return t.deleteIndex.call(this,this.vectorBucketName,e)})}index(e){return new as(this.url,this.headers,this.vectorBucketName,e,this.fetch)}}class as extends ss{constructor(e,t,r,s,n){super(e,t,n),this.vectorBucketName=r,this.indexName=s}putVectors(e){const t=Object.create(null,{putVectors:{get:()=>super.putVectors}});return m(this,void 0,void 0,function*(){return t.putVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}getVectors(e){const t=Object.create(null,{getVectors:{get:()=>super.getVectors}});return m(this,void 0,void 0,function*(){return t.getVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}listVectors(){const e=Object.create(null,{listVectors:{get:()=>super.listVectors}});return m(this,arguments,void 0,function*(t={}){return e.listVectors.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}queryVectors(e){const t=Object.create(null,{queryVectors:{get:()=>super.queryVectors}});return m(this,void 0,void 0,function*(){return t.queryVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}deleteVectors(e){const t=Object.create(null,{deleteVectors:{get:()=>super.deleteVectors}});return m(this,void 0,void 0,function*(){return t.deleteVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}}class ls extends Gr{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new zr(this.url,this.headers,e,this.fetch)}get vectors(){return new ns(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Yr(this.url+"/iceberg",this.headers,this.fetch)}}const us="2.84.0";let ue="";typeof Deno<"u"?ue="deno":typeof document<"u"?ue="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ue="react-native":ue="node";const cs={"X-Client-Info":`supabase-js-${ue}/${us}`},hs={headers:cs},ds={schema:"public"},fs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},gs={},ps=i=>i?(...e)=>i(...e):(...e)=>fetch(...e),vs=()=>Headers,_s=(i,e,t)=>{const r=ps(t),s=vs();return async(n,o)=>{var a;const l=(a=await e())!==null&&a!==void 0?a:i;let u=new s(o==null?void 0:o.headers);return u.has("apikey")||u.set("apikey",i),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),r(n,Object.assign(Object.assign({},o),{headers:u}))}};function ws(i){return i.endsWith("/")?i:i+"/"}function ys(i,e){var t,r;const{db:s,auth:n,realtime:o,global:a}=i,{db:l,auth:u,realtime:c,global:f}=e,d={db:Object.assign(Object.assign({},l),s),auth:Object.assign(Object.assign({},u),n),realtime:Object.assign(Object.assign({},c),o),storage:{},global:Object.assign(Object.assign(Object.assign({},f),a),{headers:Object.assign(Object.assign({},(t=f==null?void 0:f.headers)!==null&&t!==void 0?t:{}),(r=a==null?void 0:a.headers)!==null&&r!==void 0?r:{})}),accessToken:async()=>""};return i.accessToken?d.accessToken=i.accessToken:delete d.accessToken,d}function ms(i){const e=i==null?void 0:i.trim();if(!e)throw new Error("supabaseUrl is required.");
26if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(ws(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}const nr="2.84.0",ie=30*1e3,Je=3,xe=Je*ie,bs="http://localhost:9999",Es="supabase.auth.token",Ss={"X-Client-Info":`gotrue-js/${nr}`},ze="X-Supabase-Api-Version",or={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},ks=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Os=10*60*1e3;class fe extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function y(i){return typeof i=="object"&&i!==null&&"__isAuthError"in i}class Ts extends fe{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}function Rs(i){return y(i)&&i.name==="AuthApiError"}class Y extends fe{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class F extends fe{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class $ extends F{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function As(i){return y(i)&&i.name==="AuthSessionMissingError"}class Z extends F{constructor(){super("Auth session or user missing","AuthInvalidToken
26ResponseError",500,void 0)}}class ke extends F{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Oe extends F{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function Ps(i){return y(i)&&i.name==="AuthImplicitGrantRedirectError"}class Et extends F{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Ge extends F{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Ne(i){return y(i)&&i.name==="AuthRetryableFetchError"}class St extends F{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class Ye extends F{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),kt=` 	
27\r=`.split(""),js=(()=>{const i=new Array(128);for(let e=0;e<i.length;e+=1)i[e]=-1;for(let e=0;e<kt.length;e+=1)i[kt[e].charCodeAt(0)]=-2;for(let e=0;e<Te.length;e+=1)i[Te[e].charCodeAt(0)]=e;return i})();function Ot(i,e,t){if(i!==null)for(e.queue=e.queue<<8|i,e.queuedBits+=8;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;t(Te[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;t(Te[r]),e.queuedBits-=6}}function ar(i,e,t){const r=js[i];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(i)}"`)}}function Tt(i){const e=[],t=o=>{e.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},n=o=>{$s(o,r,t)};for(let o=0;o<i.length;o+=1)ar(i.charCodeAt(o),s,n);return e.join("")}function Is(i,e){if(i<=127){e(i);return}else if(i<=2047){e(192|i>>6),e(128|i&63);return}else if(i<=65535){e(224|i>>12),e(128|i>>6&63),e(128|i&63);return}else if(i<=1114111){e(240|i>>18),e(128|i>>12&63),e(128|i>>6&63),e(128|i&63);return}throw new Error(`Unrecognized Unicode codepoint: ${i.toString(16)}`)}function Cs(i,e){for(let t=0;t<i.length;t+=1){let r=i.charCodeAt(t);if(r>55295&&r<=56319){const s=(r-55296)*1024&65535;r=(i.charCodeAt(t+1)-56320&65535|s)+65536,t+=1}Is(r,e)}}function $s(i,e,t){if(e.utf8seq===0){if(i<=127){t(i);return}for(let r=1;r<6;r+=1)if(!(i>>7-r&1)){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=i&31;else if(e.utf8seq===3)e.codepoint=i&15;else if(e.utf8seq===4)e.codepoint=i&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(i<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|i&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function oe(i){const e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};for(let s=0;s<i.length;s+=1)ar(i.charCodeAt(s),t,r);return new Uint8Array(e)}function Us(i){const e=[];return Cs(i,t=>e.push(t)),new Uint8Array(e)}function Q(i){const e=[],t={queue:0,queuedBits:0},r=s=>{e.push(s)};return i.forEach(s=>Ot(s,t,r)),Ot(null,t,r),e.join("")}function xs(i){return Math.round(Date.now()/1e3)+i}function Ns(){return Symbol("auth-callback")}const I=()=>typeof window<"u"&&typeof document<"u",K={tested:!1,writable:!1},lr=()=>{if(!I())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(K.tested)return K.writable;const i=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(i,i),globalThis.localStorage.removeItem(i),K.tested=!0,K.writable=!0}catch{K.tested=!0,K.writable=!1}return K.writable};function Ds(i){const e={},t=new URL(i);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,n)=>{e[n]=s})}catch{}return t.searchParams.forEach((r,s)=>{e[s]=r}),e}const ur=i=>i?(...e)=>i(...e):(...e)=>fetch(...e),Ls=i=>typeof i=="object"&&i!==null&&"status"in i&&"ok"in i&&"json"in i&&typeof i.json=="function",ne=async(i,e,t)=>{await i.setItem(e,JSON.stringify(t))},H=async(i,e)=>{const t=await i.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},W=async(i,e)=>{await i.removeItem(e)};
27class je{constructor(){this.promise=new je.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}je.promiseConstructor=Promise;function De(i){const e=i.split(".");if(e.length!==3)throw new Ye("Invalid JWT structure");for(let r=0;r<e.length;r++)if(!ks.test(e[r]))throw new Ye("JWT not in base64url format");return{header:JSON.parse(Tt(e[0])),payload:JSON.parse(Tt(e[1])),signature:oe(e[2]),raw:{header:e[0],payload:e[1]}}}async function Bs(i){return await new Promise(e=>{setTimeout(()=>e(null),i)})}function qs(i,e){return new Promise((r,s)=>{(async()=>{for(let n=0;n<1/0;n++)try{const o=await i(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){s(o);return}}})()})}function Ms(i){return("0"+i.toString(16)).substr(-2)}function Ws(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length;let s="";for(let n=0;n<56;n++)s+=t.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,Ms).join("")}async function Vs(i){const t=new TextEncoder().encode(i),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(n=>String.fromCharCode(n)).join("")}async function Fs(i){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),i;const t=await Vs(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ee(i,e,t=!1){const r=Ws();let s=r;t&&(s+="/PASSWORD_RECOVERY"),await ne(i,`${e}-code-verifier`,s);const n=await Fs(r);return[n,r===n?"plain":"s256"]}const Ks=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Hs(i){const e=i.headers.get(ze);if(!e||!e.match(Ks))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Js(i){if(!i)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(i<=e)throw new Error("JWT has expired")}function zs(i){switch(i){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")}}const Gs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function te(i){if(!Gs.test(i))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Le(){const i={};return new Proxy(i,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){const r=t.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="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 "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Ys(i,e){return new Proxy(i,{get:(t,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){const n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)"||n==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,r,s)}return!e.value&&typeof r=="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(t,r,s)}})}function Rt(i){return JSON.parse(JSON.stringify(i))}const J=i=>i.msg||i.message||i.error_description||i.error||JSON.stringify(i),Qs=[502,503,504];async function At(i){var e;if(!Ls(i))throw new Ge(J(i),0);if(Qs.includes(i.status))throw new Ge(J(i),i.status);let t;try{t=await i.json()}catch(n){throw new Y(J(n),n)}let r;const s=Hs(i);if(s&&s.getTime()>=or["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new St(J(t),i.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new $}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>
27n&&typeof o=="string",!0))throw new St(J(t),i.status,t.weak_password.reasons);throw new Ts(J(t),i.status||500,r)}const Xs=(i,e,t,r)=>{const s={method:i,headers:(e==null?void 0:e.headers)||{}};return i==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),t))};async function E(i,e,t,r){var s;const n=Object.assign({},r==null?void 0:r.headers);n[ze]||(n[ze]=or["2024-01-01"].name),r!=null&&r.jwt&&(n.Authorization=`Bearer ${r.jwt}`);const o=(s=r==null?void 0:r.query)!==null&&s!==void 0?s:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Zs(i,e,t+a,{headers:n,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(l):{data:Object.assign({},l),error:null}}async function Zs(i,e,t,r,s,n){const o=Xs(e,r,s,n);let a;try{a=await i(t,Object.assign({},o))}catch(l){throw console.error(l),new Ge(J(l),0)}if(a.ok||await At(a),r!=null&&r.noResolveJson)return a;try{return await a.json()}catch(l){await At(l)}}function L(i){var e;let t=null;ri(i)&&(t=Object.assign({},i),i.expires_at||(t.expires_at=xs(i.expires_in)));const r=(e=i.user)!==null&&e!==void 0?e:i;return{data:{session:t,user:r},error:null}}function Pt(i){const e=L(i);return!e.error&&i.weak_password&&typeof i.weak_password=="object"&&Array.isArray(i.weak_password.reasons)&&i.weak_password.reasons.length&&i.weak_password.message&&typeof i.weak_password.message=="string"&&i.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=i.weak_password),e}function V(i){var e;return{data:{user:(e=i.user)!==null&&e!==void 0?e:i},error:null}}function ei(i){return{data:i,error:null}}function ti(i){const{action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:n}=i,o=Pe(i,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:s,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function jt(i){return i}function ri(i){return i.access_token&&i.refresh_token&&i.expires_in}const Be=["global","local","others"];class si{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=ur(r),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)}}async signOut(e,t=Be[0]){if(Be.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Be.join(", ")}`);try{return await E(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(y(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await E(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:V})}catch(r){if(y(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{const{options:t}=e,r=Pe(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=r==null?void 0:r.newEmail,delete s.newEmail),await E(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:ti,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(y(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await E(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:V})}catch(t){if(y(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,s,n,o,a,l;try{const u={nextPage:null,lastPage:0,total:0},c=await E(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(s=e==null?void 0:e.perPage)===null||s===void 0?void 0:s.toString())!==null&&n!==void 0?n:""},xform:jt});if(c.error)throw c.error;const f=await c.json(),d=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>
vendor: 1,151 bytes, line 27
270&&(h.forEach(p=>{const v=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),g=JSON.parse(p.split(";")[1].split("=")[1]);u[`${g}Page`]=v}),u.total=parseInt(d)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(y(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){te(e);try{return await E(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:V})}catch(t){if(y(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){te(e);try{return await E(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:V})}catch(r){if(y(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){te(e);try{return await E(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:V})}catch(r){if(y(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){te(e.userId);try{const{data:t,error:r}=await E(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:r}}catch(t){if(y(t))return{data:null,error:t};throw t}}
27async _deleteFactor(e){te(e.userId),te(e.id);try{return{data:await E(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(y(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,s,n,o,a,l;try{const u={nextPage:null,lastPage:0,total:0},c=await E(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(s=e==null?void 0:e.perPage)===null||s===void 0?void 0:s.toString())!==null&&n!==void 0?n:""},xform:jt});if(c.error)throw c.error;const f=await c.json(),d=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(p=>{const v=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),g=JSON.parse(p.split(";")[1].split("=")[1]);u[`${g}Page`]=v}),u.total=parseInt(d)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(y(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await E(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(y(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await E(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(y(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await E(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(y(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await E(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(y(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await E(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(y(t))return{data:null,error:t};throw t}}}function It(i={}){return{getItem:e=>i[e]||null,setItem:(e,t)=>{i[e]=t},removeItem:e=>{delete i[e]}}}const re={debug:!!(globalThis&&lr()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class cr extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class ii extends cr{}async function ni(i,e,t){re.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",i,e);const r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),re.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",i)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(i,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async s=>{if(s){re.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",i,s.name);try{return await t()}finally{re.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",i,s.name)}}else{if(e===0)throw re.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",i),new ii(`Acquiring an exclusive Navigator LockManager lock "${i}" immediately failed`);if(re.debug)try{const n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null,"  "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}function oi(){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 hr(i){if(!/^0x[a-fA-F0-9]{40}$/.test(i))throw new Error(`@supabase/auth-js: Address "${i}
27" is invalid.`);return i.toLowerCase()}function ai(i){return parseInt(i,16)}function li(i){const e=new TextEncoder().encode(i);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function ui(i){var e;const{chainId:t,domain:r,expirationTime:s,issuedAt:n=new Date,nonce:o,notBefore:a,requestId:l,resources:u,scheme:c,uri:f,version:d}=i;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)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(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(d!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(!((e=i.statement)===null||e===void 0)&&e.includes(`
28`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${i.statement}`)}const h=hr(i.address),p=c?`${c}://${r}`:r,v=i.statement?`${i.statement}
29`:"",g=`${p} wants you to sign in with your Ethereum account:
30${h}
31
32${v}`;let b=`URI: ${f}
33Version: ${d}
34Chain ID: ${t}${o?`
35Nonce: ${o}`:""}
36Issued At: ${n.toISOString()}`;if(s&&(b+=`
37Expiration Time: ${s.toISOString()}`),a&&(b+=`
38Not Before: ${a.toISOString()}`),l&&(b+=`
39Request ID: ${l}`),u){let w=`
40Resources:`;for(const _ of u){if(!_||typeof _!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${_}`);w+=`
41- ${_}`}b+=w}return`${g}
42${b}`}class P extends Error{constructor({message:e,code:t,cause:r,name:s}){var n;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(n=s??(r instanceof Error?r.name:void 0))!==null&&n!==void 0?n:"Unknown Error",this.code=t}}class Re extends P{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function ci({error:i,options:e}){var t,r,s;const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(i.name==="AbortError"){if(e.signal instanceof AbortSignal)return new P({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:i})}else if(i.name==="ConstraintError"){if(((t=n.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new P({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:i});if(e.mediation==="conditional"&&((r=n.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new P({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:i});if(((s=n.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new P({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:i})}else{if(i.name==="InvalidStateError")return new P({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:i});if(i.name==="NotAllowedError")return new P({message:i.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:i});if(i.name==="NotSupportedError")return n.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new P({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:i}):new P({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:i});if(i.name==="SecurityError"){const o=window.location.hostname;if(dr(o)){if(n.rp.id!==o)return new P({message:`The RP ID "${n.rp.id}
42" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:i})}else return new P({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:i})}else if(i.name==="TypeError"){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new P({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:i})}else if(i.name==="UnknownError")return new P({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:i})}return new P({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:i})}function hi({error:i,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(i.name==="AbortError"){if(e.signal instanceof AbortSignal)return new P({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:i})}else{if(i.name==="NotAllowedError")return new P({message:i.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:i});if(i.name==="SecurityError"){const r=window.location.hostname;if(dr(r)){if(t.rpId!==r)return new P({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:i})}else return new P({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:i})}else if(i.name==="UnknownError")return new P({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:i})}return new P({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:i})}class di{createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const fi=new di;function gi(i){if(!i)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(i);const{challenge:e,user:t,excludeCredentials:r}=i,s=Pe(i,["challenge","user","excludeCredentials"]),n=oe(e).buffer,o=Object.assign(Object.assign({},t),{id:oe(t.id).buffer}),a=Object.assign(Object.assign({},s),{challenge:n,user:o});if(r&&r.length>0){a.excludeCredentials=new Array(r.length);for(let l=0;l<r.length;l++){const u=r[l];a.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:oe(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return a}function pi(i){if(!i)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(i);const{challenge:e,allowCredentials:t}=i,r=Pe(i,["challenge","allowCredentials"]),s=oe(e).buffer,n=Object.assign(Object.assign({},r),{challenge:s});if(t&&t.length>0){n.allowCredentials=new Array(t.length);for(let o=0;o<t.length;o++){const a=t[o];n.allowCredentials[o]=Object.assign(Object.assign({},a),{id:oe(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return n}function vi(i){var e;if("toJSON"in i&&typeof i.toJSON=="function")return i.toJSON();const t=i;return{id:i.id,rawId:i.id,response:{attestationObject:Q(new Uint8Array(i.response.attestationObject)),clientDataJSON:Q(new Uint8Array(i.response.clientDataJSON))},type:"public-key",clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function _i(i){var e;if("toJSON"in i&&typeof i.toJSON=="function")return i.toJSON();const t=i,r=i.getClientExtensionResults(),s=i.response;return{id:i.id,rawId:i.id,response:{authenticatorData:Q(new Uint8Array(s.authenticatorData)),clientDataJSON:Q(new Uint8Array(s.clientDataJSON)),signature:Q(new Uint8Array(s.signature)),userHandle:s.userHandle?Q(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function dr(i){return i==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(i)}function Ct(){var i,e;return!!(I()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((i=navigator==null?void 0:navigator.credentials)===null||i===void 0?void 0:i.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function wi(i){try{const e=await navigator.credentials.create(i);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Re("Browser returned unexpected credential type",e)}:{data:null,error:new Re("Empty credential response",e)}}catch(e){return{data:null,error:ci({error:e,options:i})}}}async function yi(i){try{const e=await navigator.credentials.get(i);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Re("Browser returned unexpected credential type",e)}:{data:null,error:new Re("Empty credential response",e)}}catch(e){return{data:null,error:hi({error:e,options:i})}}}const mi={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},bi={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ae(...i){const e=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),t=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(const s of i)if(s)for(const n in s){const o=s[n];if(o!==void 0)if(Array.isArray(o))r[n]=o;else if(t(o))r[n]=o;else if(e(o)){const a=r[n];e(a)?r[n]=Ae(a,o):r[n]=Ae(o)}else r[n]=o}return r}function Ei(i,e){return Ae(mi,i,e||{})}function Si(i,e){return Ae(bi,i,e||{})}class ki{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:t,friendlyName:r,signal:s},n){try{const{data:o,error:a}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!o)return{data:null,error:a};const l=s??fi.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:u}=o.webauthn.credential_options.publicKey;u.name||(u.name=`${u.id}:${r}`),u.displayName||(u.displayName=u.name)}
42switch(o.webauthn.type){case"create":{const u=Ei(o.webauthn.credential_options.publicKey,n==null?void 0:n.create),{data:c,error:f}=await wi({publicKey:u,signal:l});return c?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:c}},error:null}:{data:null,error:f}}case"request":{const u=Si(o.webauthn.credential_options.publicKey,n==null?void 0:n.request),{data:c,error:f}=await yi(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:u,signal:l}));return c?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:c}},error:null}:{data:null,error:f}}}}catch(o){return y(o)?{data:null,error:o}:{data:null,error:new Y("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},n){if(!t)return{data:null,error:new fe("rpId is required for WebAuthn authentication")};try{if(!Ct())return{data:null,error:new Y("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:n});if(!o)return{data:null,error:a};const{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:t,rpOrigins:r,credential_response:l.credential_response}})}catch(o){return y(o)?{data:null,error:o}:{data:null,error:new Y("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},n){if(!t)return{data:null,error:new fe("rpId is required for WebAuthn registration")};try{if(!Ct())return{data:null,error:new Y("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(c=>{var f;return(f=c.data)===null||f===void 0?void 0:f.all.find(d=>d.factor_type==="webauthn"&&d.friendly_name===e&&d.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c==null?void 0:c.id}):void 0),{data:null,error:a};const{data:l,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:n});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:t,rpOrigins:r,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(o){return y(o)?{data:null,error:o}:{data:null,error:new Y("Unexpected error in register",o)}}}}oi();const Oi={url:bs,storageKey:Es,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ss,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1};async function $t(i,e,t){return await t()}const se={};class ge{get jwks(){var e,t;return(t=(e=se[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){se[this.storageKey]=Object.assign(Object.assign({},se[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=se[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){se[this.storageKey]=Object.assign(Object.assign({},se[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const n=Object.assign(Object.assign({},Oi),e);if(this.storageKey=n.storageKey,this.instanceID=(t=ge.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,ge.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!n.debug,typeof n.debug=="function"&&(this.logger=n.debug),this.instanceID>0&&I()){const 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=n.persistSession,this.autoRefreshToken=n.autoRefreshToken,this.admin=new si({url:n.url,headers:n.headers,fetch:n.fetch}),this.url=n.url,this.headers=n.headers,this.fetch=ur(n.fetch),this.lock=n.lock||$t,this.detectSessionInUrl=n.detectSessionInUrl,this.flowType=n.flowType,this.hasCustomAuthorizationHeader=n.hasCustomAuthorizationHeader,this.throwOnError=n.throwOnError,n.lock?this.lock=n.lock:I()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=ni:this.lock=$t,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 ki(this)}
42,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.persistSession?(n.storage?this.storage=n.storage:lr()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=It(this.memoryStorage)),n.userStorage&&(this.userStorage=n.userStorage)):(this.memoryStorage={},this.storage=It(this.memoryStorage)),I()&&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)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),await this._notifyAllSubscribers(o.data.event,o.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${nr}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let t={},r="none";if(I()&&(t=Ds(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),I()&&this.detectSessionInUrl&&r!=="none"){const{data:s,error:n}=await this._getSessionFromURL(t,r);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),Ps(n)){const l=(e=n.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:n}}return await this._removeSession(),{error:n}}const{session:o,redirectType:a}=s;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(t){return y(t)?this._returnResult({error:t}):this._returnResult({error:new Y("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{const n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e==null?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.captchaToken}},xform:L}),{data:o,error:a}=n;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});const l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(y(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signUp(e){var t,r,s;try{let n;if("email"in e){const{email:c,password:f,options:d}=e;let h=null,p=null;this.flowType==="pkce"&&([h,p]=await ee(this.storage,this.storageKey)),n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d==null?void 0:d.emailRedirectTo,body:{email:c,password:f,data:(t=d==null?void 0:d.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},code_challenge:h,code_challenge_method:p},xform:L})}else if("phone"in e){const{phone:c,password:f,options:d}=e;n=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:f,data:(r=d==null?void 0:d.data)!==null&&r!==void 0?r:{},channel:(s=d==null?void 0:d.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:L})}else throw new ke("You must provide either an email or phone number and a password");const{data:o,error:a}=n;
42if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});const l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(y(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithPassword(e){try{let t;if("email"in e){const{email:n,password:o,options:a}=e;t=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Pt})}else if("phone"in e){const{phone:n,password:o,options:a}=e;t=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Pt})}else throw new ke("You must provide either an email or phone number and a password");const{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){const n=new Z;return this._returnResult({data:{user:null,session:null},error:n})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(t){if(y(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,s,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,n,o,a,l,u,c,f,d;let h,p;if("message"in e)h=e.message,p=e.signature;else{const{chain:v,wallet:g,statement:b,options:w}=e;let _;if(I())if(typeof g=="object")_=g;else{const N=window;if("ethereum"in N&&typeof N.ethereum=="object"&&"request"in N.ethereum&&typeof N.ethereum.request=="function")_=N.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 g!="object"||!(w!=null&&w.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=g}const S=new URL((t=w==null?void 0:w.url)!==null&&t!==void 0?t:window.location.href),T=await _.request({method:"eth_requestAccounts"}).then(N=>N).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!T||T.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const k=hr(T[0]);let A=(r=w==null?void 0:w.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!A){const N=await _.request({method:"eth_chainId"});A=ai(N)}const D={domain:S.host,address:k,statement:b,uri:S.href,version:"1",chainId:A,nonce:(s=w==null?void 0:w.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(n=w==null?void 0:w.signInWithEthereum)===null||n===void 0?void 0:n.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=w==null?void 0:w.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=w==null?void 0:w.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=w==null?void 0:w.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=w==null?void 0:w.signInWithEthereum)===null||c===void 0?void 0:c.resources};h=ui(D),p=await _.request({method:"personal_sign",params:[li(h),k]})}try{const{data:v,error:g}=await E(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:p},!((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:L});if(g)throw g;if(!v||!v.session||!v.user){const b=new Z;return this._returnResult({data:{user:null,session:null},error:b})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:g})}catch(v){if(y(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(e){var t,r,s,n,o,a,l,u,c,f,d,h;let p,v;if("message"in e)p=e.message,v=e.signature;else{const{chain:g,wallet:b,statement:w,options:_}=e;let S;if(I())if(typeof b=="object")S=b;
42else{const k=window;if("solana"in k&&typeof k.solana=="object"&&("signIn"in k.solana&&typeof k.solana.signIn=="function"||"signMessage"in k.solana&&typeof k.solana.signMessage=="function"))S=k.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 b!="object"||!(_!=null&&_.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=b}const T=new URL((t=_==null?void 0:_.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in S&&S.signIn){const k=await S.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_==null?void 0:_.signInWithSolana),{version:"1",domain:T.host,uri:T.href}),w?{statement:w}:null));let A;if(Array.isArray(k)&&k[0]&&typeof k[0]=="object")A=k[0];else if(k&&typeof k=="object"&&"signedMessage"in k&&"signature"in k)A=k;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in A&&"signature"in A&&(typeof A.signedMessage=="string"||A.signedMessage instanceof Uint8Array)&&A.signature instanceof Uint8Array)p=typeof A.signedMessage=="string"?A.signedMessage:new TextDecoder().decode(A.signedMessage),v=A.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in S)||typeof S.signMessage!="function"||!("publicKey"in S)||typeof S!="object"||!S.publicKey||!("toBase58"in S.publicKey)||typeof S.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${T.host} wants you to sign in with your Solana account:`,S.publicKey.toBase58(),...w?["",w,""]:[""],"Version: 1",`URI: ${T.href}`,`Issued At: ${(s=(r=_==null?void 0:_.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((n=_==null?void 0:_.signInWithSolana)===null||n===void 0)&&n.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((o=_==null?void 0:_.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((a=_==null?void 0:_.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((l=_==null?void 0:_.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((u=_==null?void 0:_.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((f=(c=_==null?void 0:_.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||f===void 0)&&f.length?["Resources",..._.signInWithSolana.resources.map(A=>`- ${A}`)]:[]].join(`
43`);const k=await S.signMessage(new TextEncoder().encode(p),"utf8");if(!k||!(k instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=k}}try{const{data:g,error:b}=await E(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:Q(v)},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:L});if(b)throw b;if(!g||!g.session||!g.user){const w=new Z;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:b})}catch(g){if(y(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async _exchangeCodeForSession(e){const t=await H(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(t??"").split("/");try{const{data:n,error:o}=await E(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:L});if(await W(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!n||!n.session||!n.user){const a=new Z;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign(Object.assign({},n),{redirectType:s??null}),error:o})}catch(n){if(y(n))return this._returnResult({data:{user:null,session:null,redirectType:null},error:n});throw n}}async signInWithIdToken(e){try{const{options:t,provider:r,token:s,access_token:n,nonce:o}=e,a=await E(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:L}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){const c=new Z;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(t){if(y(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,s,n,o;try{if("email"in e){const{email:a,options:l}=e;let u=null,c=null;this.flowType==="pkce"&&([u,c]=await ee(this.storage,this.storageKey));const{error:f}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l==null?void 0:l.data)!==null&&t!==void 0?t:{},create_user:(r=l==null?void 0:l.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in e){const{phone:a,options:l}=e,{data:u,error:c}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l==null?void 0:l.data)!==null&&s!==void 0?s:{},create_user:(n=l==null?void 0:l.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(o=l==null?void 0:l.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:c})}throw new ke("You must provide either an email or phone number.")}catch(a){if(y(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var t,r;try{let s,n;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:a}=await E(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:L});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,u=o.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(y(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var t,r,s,n,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await ee(this.storage,this.storageKey));const u=await E(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((s=e==null?void 0: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:l}),headers:this.headers,xform:ei});
43return!((n=u.data)===null||n===void 0)&&n.url&&I()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(y(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new $;const{error:s}=await E(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(y(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:s,options:n}=e,{error:o}=await E(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},redirectTo:n==null?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){const{phone:r,type:s,options:n}=e,{data:o,error:a}=await E(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:a})}throw new ke("You must provide either an email or phone number and a type")}catch(t){if(y(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const t=await H(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=e.expires_at?e.expires_at*1e3-Date.now()<xe:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const o=await H(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Le()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=Ys(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{session:null},error:n}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:V}):await this._useSession(async t=>{var r,s,n;const{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new $}:await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0,xform:V})})}catch(t){if(y(t))return As(t)&&(await this._removeSession(),await W(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:s,error:n}=r;if(n)throw n;if(!s.session)throw new $;const o=s.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await ee(this.storage,this.storageKey));const{data:u,error:c}=await E(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:V});if(c)throw c;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(r){if(y(r))return this._returnResult({data:{user:null},error:r});throw r}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new $;const t=Date.now()/1e3;let r=t,s=!0,n=null;const{payload:o}=De(e.access_token);if(o.exp&&(r=o.exp,s=r<=t),s){const{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};n=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return this._returnResult({data:{user:n.user,session:n},error:null})}catch(t){if(y(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(e!=null&&e.refresh_token))throw new $;const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{user:null,session:null},error:n}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(y(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!I())throw new Oe("No browser detected.");
43if(e.error||e.error_description||e.error_code)throw new Oe(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new Et("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Oe("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Et("No code detected.");const{data:w,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;const S=new URL(window.location.href);return S.searchParams.delete("code"),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:w.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:s,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:u}=e;if(!n||!a||!o||!u)throw new Oe("No session defined in URL");const c=Math.round(Date.now()/1e3),f=parseInt(a);let d=c+f;l&&(d=parseInt(l));const h=d-c;h*1e3<=ie&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${f}s`);const p=d-f;c-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,d,c):c-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,d,c);const{data:v,error:g}=await this._getUser(n);if(g)throw g;const b={provider_token:r,provider_refresh_token:s,access_token:n,expires_in:f,expires_at:d,refresh_token:o,token_type:u,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:b,redirectType:e.type},error:null})}catch(r){if(y(r))return this._returnResult({data:{session:null,redirectType:null},error:r});throw r}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await H(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({error:n});const o=(r=s.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!(Rs(a)&&(a.status===404||a.status===401||a.status===403)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await W(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Ns(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{const{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;this.flowType==="pkce"&&([r,s]=await ee(this.storage,this.storageKey,!0));try{return await E(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(y(n))return this._returnResult({data:null,error:n});throw n}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:s}=await this._useSession(async n=>{var o,a,l,u,c;const{data:f,error:d}=n;
43if(d)throw d;const h=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await E(this.fetch,"GET",h,{headers:this.headers,jwt:(c=(u=f.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(s)throw s;return I()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),this._returnResult({data:{provider:e.provider,url:r==null?void 0:r.url},error:null})}catch(r){if(y(r))return this._returnResult({data:{provider:e.provider,url:null},error:r});throw r}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:s,data:{session:n}}=t;if(s)throw s;const{options:o,provider:a,token:l,access_token:u,nonce:c}=e,f=await E(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=n==null?void 0:n.access_token)!==null&&r!==void 0?r:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:L}),{data:d,error:h}=f;return h?this._returnResult({data:{user:null,session:null},error:h}):!d||!d.session||!d.user?this._returnResult({data:{user:null,session:null},error:new Z}):(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session)),this._returnResult({data:d,error:h}))}catch(s){if(y(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:o}=t;if(o)throw o;return await E(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const r=Date.now();return await qs(async s=>(s>
430&&await Bs(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await E(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:L})),(s,n)=>{const o=200*Math.pow(2,s);return n&&Ne(n)&&Date.now()+o-r<ie})}catch(r){if(this._debug(t,"error",r),y(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),I()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const s=await H(this.storage,this.storageKey);if(s&&this.userStorage){let o=await H(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await ne(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Le()}else if(s&&!s.user&&!s.user){const o=await H(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(s.user=o.user,await W(this.storage,this.storageKey+"-user"),await ne(this.storage,this.storageKey,s)):s.user=Le()}if(this._debug(r,"session from storage",s),!this._isValidSession(s)){this._debug(r,"session is not valid"),s!==null&&await this._removeSession();return}const n=((t=s.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<xe;if(this._debug(r,`session has${n?"":" not"} expired with margin of ${xe}s`),n){if(this.autoRefreshToken&&s.refresh_token){const{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),Ne(o)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:a}=await this._getUser(s.access_token);!a&&(o!=null&&o.user)?(s.user=o.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(r,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(r,"error",s),console.error(s);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new $;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new je;const{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new $;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);const a={data:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(s,"error",n),y(n)){const o={data:null,error:n};return Ne(n)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){const s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){n.push(l)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const t=Object.assign({},e),r=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!r&&t.user&&await ne(this.userStorage,this.storageKey+"-user",{user:t.user});const s=Object.assign({},t);delete s.user;const n=Rt(s);await ne(this.storage,this.storageKey,n)}else{const s=Rt(t);await ne(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),await W(this.storage,this.storageKey),await W(this.storage,this.storageKey+"-code-verifier"),await W(this.storage,this.storageKey+"-user"),this.userStorage&&await W(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&I()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}
43catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),ie);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const s=Math.floor((r.expires_at*1e3-e)/ie);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${ie}ms, refresh threshold is ${Je} ticks`),s<=Je&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof cr)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!I()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const s=[`provider=${encodeURIComponent(t)}`];if(r!=null&&r.redirectTo&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[n,o]=await ee(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(r!=null&&r.queryParams){const n=new URLSearchParams(r.queryParams);s.push(n.toString())}return r!=null&&r.skipBrowserRedirect&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;return n?this._returnResult({data:null,error:n}):await E(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:o}=t;if(o)return this._returnResult({data:null,error:o});const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:u}=await E(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(r=n==null?void 0:n.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&l.type==="totp"&&(!((s=l==null?void 0:l.totp)===null||s===void 0)&&s.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?vi(e.webauthn.credential_response):_i(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});const o=await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});if(o.error)return o;const{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:gi(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:pi(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}})}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const s={all:[],phone:[],totp:[],webauthn:[]};for(const n of(e=t==null?void 0:t.factors)!==null&&e!==void 0?e:[])s.all.push(n),n.status==="verified"&&s[n.factor_type].push(n);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:r},error:s}
43=await this.getSession();if(s)return this._returnResult({data:null,error:s});if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:n}=De(r.access_token);let o=null;n.aal&&(o=n.aal);let a=o;((t=(e=r.user.factors)===null||e===void 0?void 0:e.filter(c=>c.status==="verified"))!==null&&t!==void 0?t:[]).length>0&&(a="aal2");const u=n.amr||[];return{data:{currentLevel:o,nextLevel:a,currentAuthenticationMethods:u},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await E(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new $})})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new $});const o=await E(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&I()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new $});const o=await E(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&I()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await E(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new $})})}catch(e){if(y(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await E(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},xform:()=>({data:{},error:null})}):this._returnResult({data:null,error:new $})})}catch(t){if(y(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(a=>a.kid===e);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(a=>a.kid===e),r&&this.jwks_cached_at+Os>s)return r;const{data:n,error:o}=await E(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!n.keys||n.keys.length===0||(this.jwks=n,this.jwks_cached_at=s,r=n.keys.find(a=>a.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){const{data:h,error:p}
43=await this.getSession();if(p||!h.session)return this._returnResult({data:null,error:p});r=h.session.access_token}const{header:s,payload:n,signature:o,raw:{header:a,payload:l}}=De(r);t!=null&&t.allowExpired||Js(n.exp);const u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,t!=null&&t.keys?{keys:t.keys}:t==null?void 0:t.jwks);if(!u){const{error:h}=await this.getUser(r);if(h)throw h;return{data:{claims:n,header:s,signature:o},error:null}}const c=zs(s.alg),f=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,f,o,Us(`${a}.${l}`)))throw new Ye("Invalid JWT signature");return{data:{claims:n,header:s,signature:o},error:null}}catch(r){if(y(r))return this._returnResult({data:null,error:r});throw r}}}ge.nextInstanceID={};const Ti=ge;class Ri extends Ti{constructor(e){super(e)}}class Ai{constructor(e,t,r){var s,n,o;this.supabaseUrl=e,this.supabaseKey=t;const a=ms(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const l=`sb-${a.hostname.split(".")[0]}-auth-token`,u={db:ds,realtime:gs,auth:Object.assign(Object.assign({},fs),{storageKey:l}),global:hs},c=ys(r??{},u);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:(f,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=_s(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&this.accessToken().then(f=>this.realtime.setAuth(f)).catch(f=>console.warn("Failed to set initial Realtime auth token:",f)),this.rest=new br(new URL("rest/v1",a).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this.storage=new ls(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new wr(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t;if(this.accessToken)return await this.accessToken();const{data:r}=await this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:o,flowType:a,lock:l,debug:u,throwOnError:c},f,d){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ri({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),f),storageKey:o,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:l,debug:u,throwOnError:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(p=>p.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new Lr(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r==null?void 0:r.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Pi=(i,e,t)=>new Ai(i,e,t);function ji(){if(typeof window<"u"||typeof process>"u")return!1;const i=process.version;if(i==null)return!1;const e=i.match(/^v(\d+)\./);return e?parseInt(e[1],10)<=18:!1}ji()&&console.warn("⚠️  Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to N
43ode.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");function Ii(){var g,b;if(typeof window>"u")return;const i=location.hostname,t=["lovableproject.com","lovableproject-dev.com","lovable.app","gpt-eng.com","gptengineer.run"].some(w=>i===w||i.endsWith("."+w)),r="[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",s=t?((g=i.match(new RegExp("^(?:id-preview(?:-[a-z0-9]+)?|project)--("+r+")(?:-dev)?(?=\\.|$)","i")))==null?void 0:g[1])??((b=i.match(new RegExp("^("+r+")(?=[.-])","i")))==null?void 0:b[1]):void 0,n=window.parent&&window.parent!==window;if(!s||!n)return localStorage;const o=i.endsWith(".lovableproject-dev.com")||i.endsWith(".gpt-eng.com"),a=o?/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$|^http:\/\/localhost:3000$/:/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$/,l=location.ancestorOrigins&&location.ancestorOrigins[0]||(document.referrer?new URL(document.referrer).origin:""),u=l&&a.test(l)?[l]:o?["https://lovable.dev","http://localhost:3000"]:["https://lovable.dev"],c="lovable-preview-auth:result",f=2e3,d=()=>Math.random().toString(36).slice(2)+Date.now().toString(36),h=(w,_,S)=>new Promise(T=>{const k=d();let A=!1,D;const N=X=>{A||(A=!0,clearTimeout(D),window.removeEventListener("message",nt),T(X))},nt=X=>{if(u.indexOf(X.origin)<0)return;const ve=X.data;ve&&ve.type===c&&ve.requestId===k&&N(ve)};window.addEventListener("message",nt);const ot={type:w,requestId:k,projectId:s,key:_};S!==void 0&&(ot.value=S);for(const X of u)window.parent.postMessage(ot,X);D=setTimeout(()=>N(null),f)}
43);let p=!0;const v=250;return{getItem:async w=>{let _=await h("lovable-preview-auth:get",w);return!_&&p&&(await new Promise(S=>setTimeout(S,v)),_=await h("lovable-preview-auth:get",w)),p=!1,_&&_.ok&&typeof _.value=="string"?_.value===""?(localStorage.removeItem(w),null):_.value:localStorage.getItem(w)},setItem:(w,_)=>(localStorage.setItem(w,_),h("lovable-preview-auth:set",w,_).then(()=>{})),removeItem:w=>(localStorage.removeItem(w),h("lovable-preview-auth:remove",w).then(()=>{}))}}const Ci="https://uifdmthcbqvjehrwnofq.supabase.co",$i="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InVpZmRtdGhjYnF2amVocndub2ZxIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjM3NDA2NTAsImV4cCI6MjA3OTMxNjY1MH0.w8IAWRgs00CP9DrA5h5Qwr-mLOMkcKGs8n_D5h7tlz0",Mi=Pi(Ci,$i,{auth:{storage:Ii(),persistSession:!0,autoRefreshToken:!0}});export{Mi as supabase};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.