Linux websever 5.15.0-153-generic #163-Ubuntu SMP Thu Aug 7 16:37:18 UTC 2025 x86_64
Apache/2.4.52 (Ubuntu)
: 192.168.3.70 | : 192.168.1.99
Cant Read [ /etc/named.conf ]
8.1.2-1ubuntu2.23
urlab
www.github.com/MadExploits
Terminal
AUTO ROOT
Adminer
Backdoor Destroyer
Linux Exploit
Lock Shell
Lock File
Create User
CREATE RDP
PHP Mailer
BACKCONNECT
UNLOCK SHELL
HASH IDENTIFIER
CPANEL RESET
CREATE WP USER
README
+ Create Folder
+ Create File
/
var /
www /
html /
coursewise /
assets /
[ HOME SHELL ]
Name
Size
Permission
Action
AcademicTools-tj30wEj0.js
7.55
KB
-rwxr-xr-x
AcademicTools-tj30wEj0.js.map
14.63
KB
-rwxr-xr-x
AddCourse-BTNu-pnI.js
10.08
KB
-rwxr-xr-x
AddCourse-BTNu-pnI.js.map
35.84
KB
-rwxr-xr-x
AdminFeedbackManagement-DsTd1C...
13.52
KB
-rwxr-xr-x
AdminFeedbackManagement-DsTd1C...
45.25
KB
-rwxr-xr-x
CourseReviews-CLlzbLuT.js
27.45
KB
-rwxr-xr-x
CourseReviews-CLlzbLuT.js.map
112.09
KB
-rwxr-xr-x
Dewan-B5d13VSK.png
819.07
KB
-rwxr-xr-x
Dewan-Bniqtmij.js
102
B
-rwxr-xr-x
Dewan-Bniqtmij.js.map
197
B
-rwxr-xr-x
EditCourse-DeWQqcol.js
9.65
KB
-rwxr-xr-x
EditCourse-DeWQqcol.js.map
34.87
KB
-rwxr-xr-x
MyCourses-BA9wctPB.js
8.48
KB
-rwxr-xr-x
MyCourses-BA9wctPB.js.map
31.95
KB
-rwxr-xr-x
Rajput-BnxWGXCy.js
104
B
-rwxr-xr-x
Rajput-BnxWGXCy.js.map
200
B
-rwxr-xr-x
Rajput-CE3gMniE.png
908.11
KB
-rwxr-xr-x
Settings-BGf6-NRc.js
2.09
KB
-rwxr-xr-x
Settings-BGf6-NRc.js.map
5.35
KB
-rwxr-xr-x
TimetableClashChecker-gskbNvYE...
32.74
KB
-rwxr-xr-x
TimetableClashChecker-gskbNvYE...
137.78
KB
-rwxr-xr-x
UserManagement-pl4YxOXe.js
2.17
KB
-rwxr-xr-x
UserManagement-pl4YxOXe.js.map
5.49
KB
-rwxr-xr-x
academic-components-DF0R8Z3x.j...
670.84
KB
-rwxr-xr-x
academic-components-DF0R8Z3x.j...
1.87
MB
-rwxr-xr-x
admin-components-DUStTukf.js
1.36
MB
-rwxr-xr-x
admin-components-DUStTukf.js.m...
5.5
MB
-rwxr-xr-x
apple-touch-icon-CvbJoadU.png
20.94
KB
-rwxr-xr-x
browser-DyVnc2OH.js
392
B
-rwxr-xr-x
browser-DyVnc2OH.js.map
404
B
-rwxr-xr-x
favicon-16x16-CXk8OJVQ.png
734
B
-rwxr-xr-x
favicon-32x32-BMg2Kocu.png
1.78
KB
-rwxr-xr-x
favicon-hhFM0i7Z.ico
15.04
KB
-rwxr-xr-x
geminiService-khxcBfs7.js
2.36
KB
-rwxr-xr-x
geminiService-khxcBfs7.js.map
6.73
KB
-rwxr-xr-x
index-BbxTXAhJ.css
45.32
KB
-rwxr-xr-x
index-DN1SJQ1D.js
73.27
KB
-rwxr-xr-x
index-DN1SJQ1D.js.map
215.58
KB
-rwxr-xr-x
index.es-B3idowhG.js
155.35
KB
-rwxr-xr-x
index.es-B3idowhG.js.map
624.87
KB
-rwxr-xr-x
kunal-UYflGF6w.jpg
9.22
MB
-rwxr-xr-x
kunal-ozIpZZVI.js
102
B
-rwxr-xr-x
kunal-ozIpZZVI.js.map
197
B
-rwxr-xr-x
pdf-vendor-Bz5wMm03.js
317.87
KB
-rwxr-xr-x
pdf-vendor-Bz5wMm03.js.map
976.2
KB
-rwxr-xr-x
purify.es-CQJ0hv7W.js
21.35
KB
-rwxr-xr-x
purify.es-CQJ0hv7W.js.map
88.01
KB
-rwxr-xr-x
react-vendor-BFYHlx6n.js
160.29
KB
-rwxr-xr-x
react-vendor-BFYHlx6n.js.map
687.16
KB
-rwxr-xr-x
sarthak-CfXTejkX.png
764.15
KB
-rwxr-xr-x
sarthak-Cq6ZcrGb.js
106
B
-rwxr-xr-x
sarthak-Cq6ZcrGb.js.map
203
B
-rwxr-xr-x
site-BwHFeIBa.webmanifest
263
B
-rwxr-xr-x
supabase-vendor-DtZyL83W.js
105.45
KB
-rwxr-xr-x
supabase-vendor-DtZyL83W.js.ma...
449.41
KB
-rwxr-xr-x
ui-vendor-DSJ4jbeb.js
44.26
KB
-rwxr-xr-x
ui-vendor-DSJ4jbeb.js.map
190.96
KB
-rwxr-xr-x
useToast-Bg1woyD1.js
414
B
-rwxr-xr-x
useToast-Bg1woyD1.js.map
1.83
KB
-rwxr-xr-x
xlsx-vendor-D_ykzFJ-.js
276.48
KB
-rwxr-xr-x
xlsx-vendor-D_ykzFJ-.js.map
1.37
MB
-rwxr-xr-x
Delete
Unzip
Zip
${this.title}
Close
Code Editor : supabase-vendor-DtZyL83W.js
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browser-DyVnc2OH.js","assets/react-vendor-BFYHlx6n.js"])))=>i.map(i=>d[i]); import{g as St,a as Tt}from"./react-vendor-BFYHlx6n.js";const Et="modulepreload",Pt=function(n){return"/"+n},Ie={},X=function(e,t,s){let r=Promise.resolve();if(t&&t.length>0){let o=function(c){return Promise.all(c.map(h=>Promise.resolve(h).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");r=o(t.map(c=>{if(c=Pt(c),c in Ie)return;Ie[c]=!0;const h=c.endsWith(".css"),u=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${u}`))return;const d=document.createElement("link");if(d.rel=h?"stylesheet":Et,h||(d.as="script"),d.crossOrigin="",d.href=c,l&&d.setAttribute("nonce",l),document.head.appendChild(d),h)return new Promise((f,g)=>{d.addEventListener("load",f),d.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return r.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return e().catch(i)})},Ot=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>X(async()=>{const{default:s}=await Promise.resolve().then(()=>Z);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)};class Ae extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class jt extends Ae{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class At extends Ae{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class $t extends Ae{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var be;(function(n){n.Any="any",n.ApNortheast1="ap-northeast-1",n.ApNortheast2="ap-northeast-2",n.ApSouth1="ap-south-1",n.ApSoutheast1="ap-southeast-1",n.ApSoutheast2="ap-southeast-2",n.CaCentral1="ca-central-1",n.EuCentral1="eu-central-1",n.EuWest1="eu-west-1",n.EuWest2="eu-west-2",n.EuWest3="eu-west-3",n.SaEast1="sa-east-1",n.UsEast1="us-east-1",n.UsWest1="us-west-1",n.UsWest2="us-west-2"})(be||(be={}));var Rt=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};class Ct{constructor(e,{headers:t={},customFetch:s,region:r=be.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=Ot(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s;return Rt(this,void 0,void 0,function*(){try{const{headers:r,method:i,body:o}=t;let a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let c;o&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",c=o):typeof o=="string"?(a["Content-Type"]="text/plain",c=o):typeof FormData<"u"&&o instanceof FormData?c=o:(a["Content-Type"]="application/json",c=JSON.stringify(o)));const h=yield this.fetch(`${this.url}/${e}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),r),body:c}).catch(g=>{throw new jt(g)}),u=h.headers.get("x-relay-error");if(u&&u==="true")throw new At(h);if(!h.ok)throw new $t(h);let d=((s=h.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),f;return d==="application/json"?f=yield h.json():d==="application/octet-stream"?f=yield h.blob():d==="text/event-stream"?f=h:d==="multipart/form-data"?f=yield h.formData():f=yield h.text(),{data:f,error:null}}catch(r){return{data:null,error:r}}})}}var m={},F={},M={},J={},z={},H={},xt=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof globalThis<"u")return globalThis;throw new Error("unable to locate global object")},Y=xt();const It=Y.fetch,it=Y.fetch.bind(Y),nt=Y.Headers,Lt=Y.Request,Ut=Y.Response,Z=Object.freeze(Object.defineProperty({__proto__:null,Headers:nt,Request:Lt,Response:Ut,default:it,fetch:It},Symbol.toStringTag,{value:"Module"})),Dt=St(Z);var le={},Le;function ot(){if(Le)return le;Le=1,Object.defineProperty(le,"__esModule",{value:!0});class n extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}}return le.default=n,le}var Ue;function at(){if(Ue)return H;Ue=1;var n=H&&H.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(H,"__esModule",{value:!0});const e=n(Dt),t=n(ot());class s{constructor(i){this.shouldThrowOnError=!1,this.method=i.method,this.url=i.url,this.headers=i.headers,this.schema=i.schema,this.body=i.body,this.shouldThrowOnError=i.shouldThrowOnError,this.signal=i.signal,this.isMaybeSingle=i.isMaybeSingle,i.fetch?this.fetch=i.fetch:typeof fetch>"u"?this.fetch=e.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(i,o){return this.headers=Object.assign({},this.headers),this.headers[i]=o,this}then(i,o){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const a=this.fetch;let l=a(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async c=>{var h,u,d;let f=null,g=null,y=null,_=c.status,E=c.statusText;if(c.ok){if(this.method!=="HEAD"){const T=await c.text();T===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?g=T:g=JSON.parse(T))}const k=(h=this.headers.Prefer)===null||h===void 0?void 0:h.match(/count=(exact|planned|estimated)/),S=(u=c.headers.get("content-range"))===null||u===void 0?void 0:u.split("/");k&&S&&S.length>1&&(y=parseInt(S[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(g)&&(g.length>1?(f={code:"PGRST116",details:`Results contain ${g.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},g=null,y=null,_=406,E="Not Acceptable"):g.length===1?g=g[0]:g=null)}else{const k=await c.text();try{f=JSON.parse(k),Array.isArray(f)&&c.status===404&&(g=[],f=null,_=200,E="OK")}catch{c.status===404&&k===""?(_=204,E="No Content"):f={message:k}}if(f&&this.isMaybeSingle&&(!((d=f?.details)===null||d===void 0)&&d.includes("0 rows"))&&(f=null,_=200,E="OK"),f&&this.shouldThrowOnError)throw new t.default(f)}return{error:f,data:g,count:y,status:_,statusText:E}});return this.shouldThrowOnError||(l=l.catch(c=>{var h,u,d;return{error:{message:`${(h=c?.name)!==null&&h!==void 0?h:"FetchError"}: ${c?.message}`,details:`${(u=c?.stack)!==null&&u!==void 0?u:""}`,hint:"",code:`${(d=c?.code)!==null&&d!==void 0?d:""}`},data:null,count:null,status:0,statusText:""}})),l.then(i,o)}returns(){return this}overrideTypes(){return this}}return H.default=s,H}var De;function lt(){if(De)return z;De=1;var n=z&&z.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(z,"__esModule",{value:!0});const e=n(at());class t extends e.default{select(r){let i=!1;const o=(r??"*").split("").map(a=>/\s/.test(a)&&!i?"":(a==='"'&&(i=!i),a)).join("");return this.url.searchParams.set("select",o),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(r,{ascending:i=!0,nullsFirst:o,foreignTable:a,referencedTable:l=a}={}){const c=l?`${l}.order`:"order",h=this.url.searchParams.get(c);return this.url.searchParams.set(c,`${h?`${h},`:""}${r}.${i?"asc":"desc"}${o===void 0?"":o?".nullsfirst":".nullslast"}`),this}limit(r,{foreignTable:i,referencedTable:o=i}={}){const a=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(a,`${r}`),this}range(r,i,{foreignTable:o,referencedTable:a=o}={}){const l=typeof a>"u"?"offset":`${a}.offset`,c=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(l,`${r}`),this.url.searchParams.set(c,`${i-r+1}`),this}abortSignal(r){return this.signal=r,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:r=!1,verbose:i=!1,settings:o=!1,buffers:a=!1,wal:l=!1,format:c="text"}={}){var h;const u=[r?"analyze":null,i?"verbose":null,o?"settings":null,a?"buffers":null,l?"wal":null].filter(Boolean).join("|"),d=(h=this.headers.Accept)!==null&&h!==void 0?h:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${c}; for="${d}"; options=${u};`,c==="json"?this:this}rollback(){var r;return((r=this.headers.Prefer)!==null&&r!==void 0?r:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}return z.default=t,z}var qe;function $e(){if(qe)return J;qe=1;var n=J&&J.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(J,"__esModule",{value:!0});const e=n(lt());class t extends e.default{eq(r,i){return this.url.searchParams.append(r,`eq.${i}`),this}neq(r,i){return this.url.searchParams.append(r,`neq.${i}`),this}gt(r,i){return this.url.searchParams.append(r,`gt.${i}`),this}gte(r,i){return this.url.searchParams.append(r,`gte.${i}`),this}lt(r,i){return this.url.searchParams.append(r,`lt.${i}`),this}lte(r,i){return this.url.searchParams.append(r,`lte.${i}`),this}like(r,i){return this.url.searchParams.append(r,`like.${i}`),this}likeAllOf(r,i){return this.url.searchParams.append(r,`like(all).{${i.join(",")}}`),this}likeAnyOf(r,i){return this.url.searchParams.append(r,`like(any).{${i.join(",")}}`),this}ilike(r,i){return this.url.searchParams.append(r,`ilike.${i}`),this}ilikeAllOf(r,i){return this.url.searchParams.append(r,`ilike(all).{${i.join(",")}}`),this}ilikeAnyOf(r,i){return this.url.searchParams.append(r,`ilike(any).{${i.join(",")}}`),this}is(r,i){return this.url.searchParams.append(r,`is.${i}`),this}in(r,i){const o=Array.from(new Set(i)).map(a=>typeof a=="string"&&new RegExp("[,()]").test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(r,`in.(${o})`),this}contains(r,i){return typeof i=="string"?this.url.searchParams.append(r,`cs.${i}`):Array.isArray(i)?this.url.searchParams.append(r,`cs.{${i.join(",")}}`):this.url.searchParams.append(r,`cs.${JSON.stringify(i)}`),this}containedBy(r,i){return typeof i=="string"?this.url.searchParams.append(r,`cd.${i}`):Array.isArray(i)?this.url.searchParams.append(r,`cd.{${i.join(",")}}`):this.url.searchParams.append(r,`cd.${JSON.stringify(i)}`),this}rangeGt(r,i){return this.url.searchParams.append(r,`sr.${i}`),this}rangeGte(r,i){return this.url.searchParams.append(r,`nxl.${i}`),this}rangeLt(r,i){return this.url.searchParams.append(r,`sl.${i}`),this}rangeLte(r,i){return this.url.searchParams.append(r,`nxr.${i}`),this}rangeAdjacent(r,i){return this.url.searchParams.append(r,`adj.${i}`),this}overlaps(r,i){return typeof i=="string"?this.url.searchParams.append(r,`ov.${i}`):this.url.searchParams.append(r,`ov.{${i.join(",")}}`),this}textSearch(r,i,{config:o,type:a}={}){let l="";a==="plain"?l="pl":a==="phrase"?l="ph":a==="websearch"&&(l="w");const c=o===void 0?"":`(${o})`;return this.url.searchParams.append(r,`${l}fts${c}.${i}`),this}match(r){return Object.entries(r).forEach(([i,o])=>{this.url.searchParams.append(i,`eq.${o}`)}),this}not(r,i,o){return this.url.searchParams.append(r,`not.${i}.${o}`),this}or(r,{foreignTable:i,referencedTable:o=i}={}){const a=o?`${o}.or`:"or";return this.url.searchParams.append(a,`(${r})`),this}filter(r,i,o){return this.url.searchParams.append(r,`${i}.${o}`),this}}return J.default=t,J}var Be;function ct(){if(Be)return M;Be=1;var n=M&&M.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(M,"__esModule",{value:!0});const e=n($e());class t{constructor(r,{headers:i={},schema:o,fetch:a}){this.url=r,this.headers=i,this.schema=o,this.fetch=a}select(r,{head:i=!1,count:o}={}){const a=i?"HEAD":"GET";let l=!1;const c=(r??"*").split("").map(h=>/\s/.test(h)&&!l?"":(h==='"'&&(l=!l),h)).join("");return this.url.searchParams.set("select",c),o&&(this.headers.Prefer=`count=${o}`),new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(r,{count:i,defaultToNull:o=!0}={}){const a="POST",l=[];if(this.headers.Prefer&&l.push(this.headers.Prefer),i&&l.push(`count=${i}`),o||l.push("missing=default"),this.headers.Prefer=l.join(","),Array.isArray(r)){const c=r.reduce((h,u)=>h.concat(Object.keys(u)),[]);if(c.length>0){const h=[...new Set(c)].map(u=>`"${u}"`);this.url.searchParams.set("columns",h.join(","))}}return new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:r,fetch:this.fetch,allowEmpty:!1})}upsert(r,{onConflict:i,ignoreDuplicates:o=!1,count:a,defaultToNull:l=!0}={}){const c="POST",h=[`resolution=${o?"ignore":"merge"}-duplicates`];if(i!==void 0&&this.url.searchParams.set("on_conflict",i),this.headers.Prefer&&h.push(this.headers.Prefer),a&&h.push(`count=${a}`),l||h.push("missing=default"),this.headers.Prefer=h.join(","),Array.isArray(r)){const u=r.reduce((d,f)=>d.concat(Object.keys(f)),[]);if(u.length>0){const d=[...new Set(u)].map(f=>`"${f}"`);this.url.searchParams.set("columns",d.join(","))}}return new e.default({method:c,url:this.url,headers:this.headers,schema:this.schema,body:r,fetch:this.fetch,allowEmpty:!1})}update(r,{count:i}={}){const o="PATCH",a=[];return this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),this.headers.Prefer=a.join(","),new e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:r,fetch:this.fetch,allowEmpty:!1})}delete({count:r}={}){const i="DELETE",o=[];return r&&o.push(`count=${r}`),this.headers.Prefer&&o.unshift(this.headers.Prefer),this.headers.Prefer=o.join(","),new e.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}return M.default=t,M}var ee={},te={},Ne;function qt(){return Ne||(Ne=1,Object.defineProperty(te,"__esModule",{value:!0}),te.version=void 0,te.version="0.0.0-automated"),te}var Fe;function Bt(){if(Fe)return ee;Fe=1,Object.defineProperty(ee,"__esModule",{value:!0}),ee.DEFAULT_HEADERS=void 0;const n=qt();return ee.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${n.version}`},ee}var Me;function Nt(){if(Me)return F;Me=1;var n=F&&F.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(F,"__esModule",{value:!0});const e=n(ct()),t=n($e()),s=Bt();class r{constructor(o,{headers:a={},schema:l,fetch:c}={}){this.url=o,this.headers=Object.assign(Object.assign({},s.DEFAULT_HEADERS),a),this.schemaName=l,this.fetch=c}from(o){const a=new URL(`${this.url}/${o}`);return new e.default(a,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(o){return new r(this.url,{headers:this.headers,schema:o,fetch:this.fetch})}rpc(o,a={},{head:l=!1,get:c=!1,count:h}={}){let u;const d=new URL(`${this.url}/rpc/${o}`);let f;l||c?(u=l?"HEAD":"GET",Object.entries(a).filter(([y,_])=>_!==void 0).map(([y,_])=>[y,Array.isArray(_)?`{${_.join(",")}}`:`${_}`]).forEach(([y,_])=>{d.searchParams.append(y,_)})):(u="POST",f=a);const g=Object.assign({},this.headers);return h&&(g.Prefer=`count=${h}`),new t.default({method:u,url:d,headers:g,schema:this.schemaName,body:f,fetch:this.fetch,allowEmpty:!1})}}return F.default=r,F}var Je;function Ft(){if(Je)return m;Je=1;var n=m&&m.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(m,"__esModule",{value:!0}),m.PostgrestError=m.PostgrestBuilder=m.PostgrestTransformBuilder=m.PostgrestFilterBuilder=m.PostgrestQueryBuilder=m.PostgrestClient=void 0;const e=n(Nt());m.PostgrestClient=e.default;const t=n(ct());m.PostgrestQueryBuilder=t.default;const s=n($e());m.PostgrestFilterBuilder=s.default;const r=n(lt());m.PostgrestTransformBuilder=r.default;const i=n(at());m.PostgrestBuilder=i.default;const o=n(ot());return m.PostgrestError=o.default,m.default={PostgrestClient:e.default,PostgrestQueryBuilder:t.default,PostgrestFilterBuilder:s.default,PostgrestTransformBuilder:r.default,PostgrestBuilder:i.default,PostgrestError:o.default},m}var Mt=Ft();const Jt=Tt(Mt),{PostgrestClient:zt,PostgrestQueryBuilder:jr,PostgrestFilterBuilder:Ar,PostgrestTransformBuilder:$r,PostgrestBuilder:Rr,PostgrestError:Cr}=Jt,Ht="2.11.2",Kt={"X-Client-Info":`realtime-js/${Ht}`},Gt="1.0.0",ht=1e4,Vt=1e3;var Q;(function(n){n[n.connecting=0]="connecting",n[n.open=1]="open",n[n.closing=2]="closing",n[n.closed=3]="closed"})(Q||(Q={}));var O;(function(n){n.closed="closed",n.errored="errored",n.joined="joined",n.joining="joining",n.leaving="leaving"})(O||(O={}));var j;(function(n){n.close="phx_close",n.error="phx_error",n.join="phx_join",n.reply="phx_reply",n.leave="phx_leave",n.access_token="access_token"})(j||(j={}));var ke;(function(n){n.websocket="websocket"})(ke||(ke={}));var B;(function(n){n.Connecting="connecting",n.Open="open",n.Closing="closing",n.Closed="closed"})(B||(B={}));class Wt{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){const r=t.getUint8(1),i=t.getUint8(2);let o=this.HEADER_LENGTH+2;const a=s.decode(e.slice(o,o+r));o=o+r;const l=s.decode(e.slice(o,o+i));o=o+i;const c=JSON.parse(s.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:c}}}class ut{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var w;(function(n){n.abstime="abstime",n.bool="bool",n.date="date",n.daterange="daterange",n.float4="float4",n.float8="float8",n.int2="int2",n.int4="int4",n.int4range="int4range",n.int8="int8",n.int8range="int8range",n.json="json",n.jsonb="jsonb",n.money="money",n.numeric="numeric",n.oid="oid",n.reltime="reltime",n.text="text",n.time="time",n.timestamp="timestamp",n.timestamptz="timestamptz",n.timetz="timetz",n.tsrange="tsrange",n.tstzrange="tstzrange"})(w||(w={}));const ze=(n,e,t={})=>{var s;const r=(s=t.skipTypes)!==null&&s!==void 0?s:[];return Object.keys(e).reduce((i,o)=>(i[o]=Qt(o,n,e,r),i),{})},Qt=(n,e,t,s)=>{const r=e.find(a=>a.name===n),i=r?.type,o=t[n];return i&&!s.includes(i)?dt(i,o):Se(o)},dt=(n,e)=>{if(n.charAt(0)==="_"){const t=n.slice(1,n.length);return es(e,t)}switch(n){case w.bool:return Xt(e);case w.float4:case w.float8:case w.int2:case w.int4:case w.int8:case w.numeric:case w.oid:return Yt(e);case w.json:case w.jsonb:return Zt(e);case w.timestamp:return ts(e);case w.abstime:case w.date:case w.daterange:case w.int4range:case w.int8range:case w.money:case w.reltime:case w.text:case w.time:case w.timestamptz:case w.timetz:case w.tsrange:case w.tstzrange:return Se(e);default:return Se(e)}},Se=n=>n,Xt=n=>{switch(n){case"t":return!0;case"f":return!1;default:return n}},Yt=n=>{if(typeof n=="string"){const e=parseFloat(n);if(!Number.isNaN(e))return e}return n},Zt=n=>{if(typeof n=="string")try{return JSON.parse(n)}catch(e){return console.log(`JSON parse error: ${e}`),n}return n},es=(n,e)=>{if(typeof n!="string")return n;const t=n.length-1,s=n[t];if(n[0]==="{"&&s==="}"){let i;const o=n.slice(1,t);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>dt(e,a))}return n},ts=n=>typeof n=="string"?n.replace(" ","T"):n,ft=n=>{let e=n;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};class pe{constructor(e,t,s={},r=ht){this.channel=e,this.event=t,this.payload=s,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);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(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var He;(function(n){n.SYNC="sync",n.JOIN="join",n.LEAVE="leave"})(He||(He={}));class re{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},r=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=re.syncState(this.state,r,i,o),this.pendingDiffs.forEach(l=>{this.state=re.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},r=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(r):(this.state=re.syncDiff(this.state,r,i,o),a())}),this.onJoin((r,i,o)=>{this.channel._trigger("presence",{event:"join",key:r,currentPresences:i,newPresences:o})}),this.onLeave((r,i,o)=>{this.channel._trigger("presence",{event:"leave",key:r,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){const i=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(i,(c,h)=>{o[c]||(l[c]=h)}),this.map(o,(c,h)=>{const u=i[c];if(u){const d=h.map(_=>_.presence_ref),f=u.map(_=>_.presence_ref),g=h.filter(_=>f.indexOf(_.presence_ref)<0),y=u.filter(_=>d.indexOf(_.presence_ref)<0);g.length>0&&(a[c]=g),y.length>0&&(l[c]=y)}else a[c]=h}),this.syncDiff(i,{joins:a,leaves:l},s,r)}static syncDiff(e,t,s,r){const{joins:i,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(i,(a,l)=>{var c;const h=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),h.length>0){const u=e[a].map(f=>f.presence_ref),d=h.filter(f=>u.indexOf(f.presence_ref)<0);e[a].unshift(...d)}s(a,h,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;const h=l.map(u=>u.presence_ref);c=c.filter(u=>h.indexOf(u.presence_ref)<0),e[a]=c,r(a,c,l),c.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{const r=e[s];return"metas"in r?t[s]=r.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):t[s]=r,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 Ke;(function(n){n.ALL="*",n.INSERT="INSERT",n.UPDATE="UPDATE",n.DELETE="DELETE"})(Ke||(Ke={}));var Ge;(function(n){n.BROADCAST="broadcast",n.PRESENCE="presence",n.POSTGRES_CHANGES="postgres_changes",n.SYSTEM="system"})(Ge||(Ge={}));var R;(function(n){n.SUBSCRIBED="SUBSCRIBED",n.TIMED_OUT="TIMED_OUT",n.CLOSED="CLOSED",n.CHANNEL_ERROR="CHANNEL_ERROR"})(R||(R={}));class Re{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=O.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new pe(this,j.join,this.params,this.timeout),this.rejoinTimer=new ut(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=O.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=O.closed,this.socket._remove(this)}),this._onError(r=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,r),this.state=O.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=O.errored,this.rejoinTimer.scheduleTimeout())}),this._on(j.reply,{},(r,i)=>{this._trigger(this._replyEventName(i),r)}),this.presence=new re(this),this.broadcastEndpointURL=ft(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var s,r;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:i,presence:o,private:a}}=this.params;this._onError(h=>e?.(R.CHANNEL_ERROR,h)),this._onClose(()=>e?.(R.CLOSED));const l={},c={broadcast:i,presence:o,postgres_changes:(r=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(h=>h.filter))!==null&&r!==void 0?r:[],private:a};this.socket.accessTokenValue&&(l.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:c},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:h})=>{var u;if(this.socket.setAuth(),h===void 0){e?.(R.SUBSCRIBED);return}else{const d=this.bindings.postgres_changes,f=(u=d?.length)!==null&&u!==void 0?u:0,g=[];for(let y=0;y<f;y++){const _=d[y],{filter:{event:E,schema:A,table:k,filter:S}}=_,T=h&&h[y];if(T&&T.event===E&&T.schema===A&&T.table===k&&T.filter===S)g.push(Object.assign(Object.assign({},_),{id:T.id}));else{this.unsubscribe(),e?.(R.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=g,e&&e(R.SUBSCRIBED);return}}).receive("error",h=>{e?.(R.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")))}).receive("timeout",()=>{e?.(R.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,r;if(!this._canPush()&&e.type==="broadcast"){const{event:i,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:i,payload:o,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((r=c.body)===null||r===void 0?void 0:r.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;const c=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)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=O.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(j.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{const r=new pe(this,j.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",{})})}async _fetchWithTimeout(e,t,s){const r=new AbortController,i=setTimeout(()=>r.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),o}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new pe(this,e,t,s);return this._canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,i;const o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:h}=j;if(s&&[a,l,c,h].indexOf(o)>=0&&s!==this._joinRef())return;let d=this._onMessage(o,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(r=this.bindings.postgres_changes)===null||r===void 0||r.filter(f=>{var g,y,_;return((g=f.filter)===null||g===void 0?void 0:g.event)==="*"||((_=(y=f.filter)===null||y===void 0?void 0:y.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(f=>f.callback(d,s)):(i=this.bindings[o])===null||i===void 0||i.filter(f=>{var g,y,_,E,A,k;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){const S=f.id,T=(g=f.filter)===null||g===void 0?void 0:g.event;return S&&((y=t.ids)===null||y===void 0?void 0:y.includes(S))&&(T==="*"||T?.toLocaleLowerCase()===((_=t.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{const S=(A=(E=f?.filter)===null||E===void 0?void 0:E.event)===null||A===void 0?void 0:A.toLocaleLowerCase();return S==="*"||S===((k=t?.event)===null||k===void 0?void 0:k.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof d=="object"&&"ids"in d){const g=d.data,{schema:y,table:_,commit_timestamp:E,type:A,errors:k}=g;d=Object.assign(Object.assign({},{schema:y,table:_,commit_timestamp:E,eventType:A,new:{},old:{},errors:k}),this._getPayloadRecords(g))}f.callback(d,s)})}_isClosed(){return this.state===O.closed}_isJoined(){return this.state===O.joined}_isJoining(){return this.state===O.joining}_isLeaving(){return this.state===O.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){const r=e.toLocaleLowerCase(),i={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(i):this.bindings[r]=[i],this}_off(e,t){const s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter(r=>{var i;return!(((i=r.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===s&&Re.isEqual(r.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(j.close,{},e)}_onError(e){this._on(j.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=O.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=ze(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=ze(e.columns,e.old_record)),t}}const ss=()=>{},rs=typeof WebSocket<"u",is=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class ns{constructor(e,t){var s;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Kt,this.params={},this.timeout=ht,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=ss,this.conn=null,this.sendBuffer=[],this.serializer=new Wt,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let o;return i?o=i:typeof fetch>"u"?o=(...a)=>X(async()=>{const{default:l}=await Promise.resolve().then(()=>Z);return{default:l}},void 0).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${ke.websocket}`,this.httpEndpoint=ft(e),t?.transport?this.transport=t.transport:this.transport=null,t?.params&&(this.params=t.params),t?.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t?.timeout&&(this.timeout=t.timeout),t?.logger&&(this.logger=t.logger),t?.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);const r=(s=t?.params)===null||s===void 0?void 0:s.apikey;if(r&&(this.accessTokenValue=r,this.apiKey=r),this.reconnectAfterMs=t?.reconnectAfterMs?t.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=t?.encode?t.encode:(i,o)=>o(JSON.stringify(i)),this.decode=t?.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new ut(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t?.fetch),t?.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=t?.worker||!1,this.workerUrl=t?.workerUrl}this.accessToken=t?.accessToken||null}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers});return}if(rs){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new os(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),X(async()=>{const{default:e}=await import("./browser-DyVnc2OH.js").then(t=>t.b);return{default:e}},__vite__mapDeps([0,1])).then(({default:e})=>{this.conn=new e(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Gt}))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){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.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case Q.connecting:return B.Connecting;case Q.open:return B.Open;case Q.closing:return B.Closing;default:return B.Closed}}isConnected(){return this.connectionState()===B.Open}channel(e,t={config:{}}){const s=new Re(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){const{topic:t,event:s,payload:r,ref:i}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${s} (${i})`,r),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){let t=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;if(t){let s=null;try{s=JSON.parse(atob(t.split(".")[1]))}catch{}if(s&&s.exp&&!(Math.floor(Date.now()/1e3)-s.exp<0))return this.log("auth",`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${s.exp}`),Promise.reject(`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${s.exp}`);this.accessTokenValue=t,this.channels.forEach(r=>{t&&r.updateJoinPayload({access_token:t}),r.joinedOnce&&r._isJoined()&&r._push(j.access_token,{access_token:t})})}}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Vt,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth()}}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(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(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:s,event:r,payload:i,ref:o}=t;o&&o===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${s} ${r} ${o&&"("+o+")"||""}`,i),this.channels.filter(a=>a._isMember(s)).forEach(a=>a._trigger(r,i,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}async _onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);else{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})}this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(j.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const s=e.match(/\?/)?"&":"?",r=new URLSearchParams(t);return`${e}${s}${r}`}_workerObjectUrl(e){let t;if(e)t=e;else{const s=new Blob([is],{type:"application/javascript"});t=URL.createObjectURL(s)}return t}}class os{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Q.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}}class Ce extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function b(n){return typeof n=="object"&&n!==null&&"__isStorageError"in n}class as extends Ce{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class Te extends Ce{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var ls=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};const gt=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>X(async()=>{const{default:s}=await Promise.resolve().then(()=>Z);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},cs=()=>ls(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield X(()=>Promise.resolve().then(()=>Z),void 0)).Response:Response}),Ee=n=>{if(Array.isArray(n))return n.map(t=>Ee(t));if(typeof n=="function"||n!==Object(n))return n;const e={};return Object.entries(n).forEach(([t,s])=>{const r=t.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[r]=Ee(s)}),e};var N=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};const _e=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),hs=(n,e,t)=>N(void 0,void 0,void 0,function*(){const s=yield cs();n instanceof s&&!t?.noResolveJson?n.json().then(r=>{e(new as(_e(r),n.status||500))}).catch(r=>{e(new Te(_e(r),r))}):e(new Te(_e(n),n))}),us=(n,e,t,s)=>{const r={method:n,headers:e?.headers||{}};return n==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json"},e?.headers),s&&(r.body=JSON.stringify(s)),Object.assign(Object.assign({},r),t))};function ae(n,e,t,s,r,i){return N(this,void 0,void 0,function*(){return new Promise((o,a)=>{n(t,us(e,s,r,i)).then(l=>{if(!l.ok)throw l;return s?.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>hs(l,a,s))})})}function fe(n,e,t,s){return N(this,void 0,void 0,function*(){return ae(n,"GET",e,t,s)})}function I(n,e,t,s,r){return N(this,void 0,void 0,function*(){return ae(n,"POST",e,s,r,t)})}function ds(n,e,t,s,r){return N(this,void 0,void 0,function*(){return ae(n,"PUT",e,s,r,t)})}function fs(n,e,t,s){return N(this,void 0,void 0,function*(){return ae(n,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),s)})}function pt(n,e,t,s,r){return N(this,void 0,void 0,function*(){return ae(n,"DELETE",e,s,r,t)})}var P=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};const gs={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ve={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class ps{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=gt(r)}uploadOrUpdate(e,t,s,r){return P(this,void 0,void 0,function*(){try{let i;const o=Object.assign(Object.assign({},Ve),r);let a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&s instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",this.encodeMetadata(l)),i.append("",s)):typeof FormData<"u"&&s instanceof FormData?(i=s,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",this.encodeMetadata(l))):(i=s,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(l)))),r?.headers&&(a=Object.assign(Object.assign({},a),r.headers));const c=this._removeEmptyFolders(t),h=this._getFinalPath(c),u=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:e,body:i,headers:a},o?.duplex?{duplex:o.duplex}:{})),d=yield u.json();return u.ok?{data:{path:c,id:d.Id,fullPath:d.Key},error:null}:{data:null,error:d}}catch(i){if(b(i))return{data:null,error:i};throw i}})}upload(e,t,s){return P(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return P(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(e),o=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l;const c=Object.assign({upsert:Ve.upsert},r),h=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&s instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",s)):typeof FormData<"u"&&s instanceof FormData?(l=s,l.append("cacheControl",c.cacheControl)):(l=s,h["cache-control"]=`max-age=${c.cacheControl}`,h["content-type"]=c.contentType);const u=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:h}),d=yield u.json();return u.ok?{data:{path:i,fullPath:d.Key},error:null}:{data:null,error:d}}catch(l){if(b(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return P(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e);const r=Object.assign({},this.headers);t?.upsert&&(r["x-upsert"]="true");const i=yield I(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),o=new URL(this.url+i.url),a=o.searchParams.get("token");if(!a)throw new Ce("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(s){if(b(s))return{data:null,error:s};throw s}})}update(e,t,s){return P(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return P(this,void 0,void 0,function*(){try{return{data:yield I(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}})}copy(e,t,s){return P(this,void 0,void 0,function*(){try{return{data:{path:(yield I(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:s?.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return P(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=yield I(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},s?.transform?{transform:s.transform}:{}),{headers:this.headers});const o=s?.download?`&download=${s.download===!0?"":s.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return P(this,void 0,void 0,function*(){try{const r=yield I(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=s?.download?`&download=${s.download===!0?"":s.download}`:"";return{data:r.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${i}`):null})),error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}})}download(e,t){return P(this,void 0,void 0,function*(){const r=typeof t?.transform<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString(t?.transform||{}),o=i?`?${i}`:"";try{const a=this._getFinalPath(e);return{data:yield(yield fe(this.fetch,`${this.url}/${r}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(b(a))return{data:null,error:a};throw a}})}info(e){return P(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const s=yield fe(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:Ee(s),error:null}}catch(s){if(b(s))return{data:null,error:s};throw s}})}exists(e){return P(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield fs(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(s){if(b(s)&&s instanceof Te){const r=s.originalError;if([400,404].includes(r?.status))return{data:!1,error:s}}throw s}})}getPublicUrl(e,t){const s=this._getFinalPath(e),r=[],i=t?.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&r.push(i);const a=typeof t?.transform<"u"?"render/image":"object",l=this.transformOptsToQueryString(t?.transform||{});l!==""&&r.push(l);let c=r.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${s}${c}`)}}}remove(e){return P(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}list(e,t,s){return P(this,void 0,void 0,function*(){try{const r=Object.assign(Object.assign(Object.assign({},gs),t),{prefix:e||""});return{data:yield I(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(b(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}`}_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 _s="2.7.1",vs={"X-Client-Info":`storage-js/${_s}`};var K=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,[])).next())})};class ys{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},vs),t),this.fetch=gt(s)}listBuckets(){return K(this,void 0,void 0,function*(){try{return{data:yield fe(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(b(e))return{data:null,error:e};throw e}})}getBucket(e){return K(this,void 0,void 0,function*(){try{return{data:yield fe(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return K(this,void 0,void 0,function*(){try{return{data:yield I(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(b(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return K(this,void 0,void 0,function*(){try{return{data:yield ds(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(b(s))return{data:null,error:s};throw s}})}emptyBucket(e){return K(this,void 0,void 0,function*(){try{return{data:yield I(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}deleteBucket(e){return K(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}})}}class ws extends ys{constructor(e,t={},s){super(e,t,s)}from(e){return new ps(this.url,this.headers,e,this.fetch)}}const ms="2.49.4";let se="";typeof Deno<"u"?se="deno":typeof document<"u"?se="web":typeof navigator<"u"&&navigator.product==="ReactNative"?se="react-native":se="node";const bs={"X-Client-Info":`supabase-js-${se}/${ms}`},ks={headers:bs},Ss={schema:"public"},Ts={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Es={};var Ps=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,e||[])).next())})};const Os=n=>{let e;return n?e=n:typeof fetch>"u"?e=it:e=fetch,(...t)=>e(...t)},js=()=>typeof Headers>"u"?nt:Headers,As=(n,e,t)=>{const s=Os(t),r=js();return(i,o)=>Ps(void 0,void 0,void 0,function*(){var a;const l=(a=yield e())!==null&&a!==void 0?a:n;let c=new r(o?.headers);return c.has("apikey")||c.set("apikey",n),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),s(i,Object.assign(Object.assign({},o),{headers:c}))})};var $s=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,[])).next())})};function Rs(n){return n.replace(/\/$/,"")}function Cs(n,e){const{db:t,auth:s,realtime:r,global:i}=n,{db:o,auth:a,realtime:l,global:c}=e,h={db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},l),r),global:Object.assign(Object.assign({},c),i),accessToken:()=>$s(this,void 0,void 0,function*(){return""})};return n.accessToken?h.accessToken=n.accessToken:delete h.accessToken,h}const _t="2.69.1",W=30*1e3,Pe=3,ve=Pe*W,xs="http://localhost:9999",Is="supabase.auth.token",Ls={"X-Client-Info":`gotrue-js/${_t}`},Oe="X-Supabase-Api-Version",vt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Us=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Ds=6e5;class xe extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function p(n){return typeof n=="object"&&n!==null&&"__isAuthError"in n}class qs extends xe{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function Bs(n){return p(n)&&n.name==="AuthApiError"}class yt extends xe{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class U extends xe{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}}class C extends U{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Ns(n){return p(n)&&n.name==="AuthSessionMissingError"}class ye extends U{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ce extends U{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class he extends U{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 Fs(n){return p(n)&&n.name==="AuthImplicitGrantRedirectError"}class We extends U{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 je extends U{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function we(n){return p(n)&&n.name==="AuthRetryableFetchError"}class Qe extends U{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class ie extends U{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Xe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Ye=` \r=`.split(""),Ms=(()=>{const n=new Array(128);for(let e=0;e<n.length;e+=1)n[e]=-1;for(let e=0;e<Ye.length;e+=1)n[Ye[e].charCodeAt(0)]=-2;for(let e=0;e<Xe.length;e+=1)n[Xe[e].charCodeAt(0)]=e;return n})();function wt(n,e,t){const s=Ms[n];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`)}}function Ze(n){const e=[],t=o=>{e.push(String.fromCodePoint(o))},s={utf8seq:0,codepoint:0},r={queue:0,queuedBits:0},i=o=>{Hs(o,s,t)};for(let o=0;o<n.length;o+=1)wt(n.charCodeAt(o),r,i);return e.join("")}function Js(n,e){if(n<=127){e(n);return}else if(n<=2047){e(192|n>>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function zs(n,e){for(let t=0;t<n.length;t+=1){let s=n.charCodeAt(t);if(s>55295&&s<=56319){const r=(s-55296)*1024&65535;s=(n.charCodeAt(t+1)-56320&65535|r)+65536,t+=1}Js(s,e)}}function Hs(n,e,t){if(e.utf8seq===0){if(n<=127){t(n);return}for(let s=1;s<6;s+=1)if((n>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function Ks(n){const e=[],t={queue:0,queuedBits:0},s=r=>{e.push(r)};for(let r=0;r<n.length;r+=1)wt(n.charCodeAt(r),t,s);return new Uint8Array(e)}function Gs(n){const e=[];return zs(n,t=>e.push(t)),new Uint8Array(e)}function Vs(n){return Math.round(Date.now()/1e3)+n}function Ws(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){const e=Math.random()*16|0;return(n=="x"?e:e&3|8).toString(16)})}const $=()=>typeof window<"u"&&typeof document<"u",D={tested:!1,writable:!1},ne=()=>{if(!$())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(D.tested)return D.writable;const n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),D.tested=!0,D.writable=!0}catch{D.tested=!0,D.writable=!1}return D.writable};function Qs(n){const e={},t=new URL(n);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,i)=>{e[i]=r})}catch{}return t.searchParams.forEach((s,r)=>{e[r]=s}),e}const mt=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>X(async()=>{const{default:s}=await Promise.resolve().then(()=>Z);return{default:s}},void 0).then(({default:s})=>s(...t)):e=fetch,(...t)=>e(...t)},Xs=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",bt=async(n,e,t)=>{await n.setItem(e,JSON.stringify(t))},ue=async(n,e)=>{const t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},de=async(n,e)=>{await n.removeItem(e)};class ge{constructor(){this.promise=new ge.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}ge.promiseConstructor=Promise;function me(n){const e=n.split(".");if(e.length!==3)throw new ie("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Us.test(e[s]))throw new ie("JWT not in base64url format");return{header:JSON.parse(Ze(e[0])),payload:JSON.parse(Ze(e[1])),signature:Ks(e[2]),raw:{header:e[0],payload:e[1]}}}async function Ys(n){return await new Promise(e=>{setTimeout(()=>e(null),n)})}function Zs(n,e){return new Promise((s,r)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await n(i);if(!e(i,null,o)){s(o);return}}catch(o){if(!e(i,o)){r(o);return}}})()})}function er(n){return("0"+n.toString(16)).substr(-2)}function tr(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length;let r="";for(let i=0;i<56;i++)r+=t.charAt(Math.floor(Math.random()*s));return r}return crypto.getRandomValues(e),Array.from(e,er).join("")}async function sr(n){const t=new TextEncoder().encode(n),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(i=>String.fromCharCode(i)).join("")}async function rr(n){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."),n;const t=await sr(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function G(n,e,t=!1){const s=tr();let r=s;t&&(r+="/PASSWORD_RECOVERY"),await bt(n,`${e}-code-verifier`,r);const i=await rr(s);return[i,s===i?"plain":"s256"]}const ir=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function nr(n){const e=n.headers.get(Oe);if(!e||!e.match(ir))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function or(n){if(!n)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function ar(n){switch(n){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var lr=function(n,e){var t={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(n,s[r])&&(t[s[r]]=n[s[r]]);return t};const q=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),cr=[502,503,504];async function et(n){var e;if(!Xs(n))throw new je(q(n),0);if(cr.includes(n.status))throw new je(q(n),n.status);let t;try{t=await n.json()}catch(i){throw new yt(q(i),i)}let s;const r=nr(n);if(r&&r.getTime()>=vt["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new Qe(q(t),n.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new C}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((i,o)=>i&&typeof o=="string",!0))throw new Qe(q(t),n.status,t.weak_password.reasons);throw new qs(q(t),n.status||500,s)}const hr=(n,e,t,s)=>{const r={method:n,headers:e?.headers||{}};return n==="GET"?r:(r.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),r.body=JSON.stringify(s),Object.assign(Object.assign({},r),t))};async function v(n,e,t,s){var r;const i=Object.assign({},s?.headers);i[Oe]||(i[Oe]=vt["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);const o=(r=s?.query)!==null&&r!==void 0?r:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await ur(n,e,t+a,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function ur(n,e,t,s,r,i){const o=hr(e,s,r,i);let a;try{a=await n(t,Object.assign({},o))}catch(l){throw console.error(l),new je(q(l),0)}if(a.ok||await et(a),s?.noResolveJson)return a;try{return await a.json()}catch(l){await et(l)}}function x(n){var e;let t=null;pr(n)&&(t=Object.assign({},n),n.expires_at||(t.expires_at=Vs(n.expires_in)));const s=(e=n.user)!==null&&e!==void 0?e:n;return{data:{session:t,user:s},error:null}}function tt(n){const e=x(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=n.weak_password),e}function L(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function dr(n){return{data:n,error:null}}function fr(n){const{action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:i}=n,o=lr(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:s,redirect_to:r,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function gr(n){return n}function pr(n){return n.access_token&&n.refresh_token&&n.expires_in}var _r=function(n,e){var t={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,s=Object.getOwnPropertySymbols(n);r<s.length;r++)e.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(n,s[r])&&(t[s[r]]=n[s[r]]);return t};class vr{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=mt(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await v(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(p(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await v(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:L})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:t}=e,s=_r(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=s?.newEmail,delete r.newEmail),await v(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:fr,redirectTo:t?.redirectTo})}catch(t){if(p(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await v(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:L})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,i,o,a,l;try{const c={nextPage:null,lastPage:0,total:0},h=await v(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(i=(r=e?.perPage)===null||r===void 0?void 0:r.toString())!==null&&i!==void 0?i:""},xform:gr});if(h.error)throw h.error;const u=await h.json(),d=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=h.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(g.split(";")[1].split("=")[1]);c[`${_}Page`]=y}),c.total=parseInt(d)),{data:Object.assign(Object.assign({},u),c),error:null}}catch(c){if(p(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){try{return await v(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:L})}catch(t){if(p(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await v(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:L})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){try{return await v(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:L})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){try{const{data:t,error:s}=await v(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:r=>({data:{factors:r},error:null})});return{data:t,error:s}}catch(t){if(p(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await v(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}}const yr={getItem:n=>ne()?globalThis.localStorage.getItem(n):null,setItem:(n,e)=>{ne()&&globalThis.localStorage.setItem(n,e)},removeItem:n=>{ne()&&globalThis.localStorage.removeItem(n)}};function st(n={}){return{getItem:e=>n[e]||null,setItem:(e,t)=>{n[e]=t},removeItem:e=>{delete n[e]}}}function wr(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}const V={debug:!!(globalThis&&ne()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class kt extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class mr extends kt{}async function br(n,e,t){V.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",n,e);const s=new globalThis.AbortController;return e>0&&setTimeout(()=>{s.abort(),V.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",n)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(n,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async r=>{if(r){V.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",n,r.name);try{return await t()}finally{V.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",n,r.name)}}else{if(e===0)throw V.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",n),new mr(`Acquiring an exclusive Navigator LockManager lock "${n}" immediately failed`);if(V.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}wr();const kr={url:xs,storageKey:Is,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ls,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function rt(n,e,t){return await t()}class oe{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=oe.nextInstanceID,oe.nextInstanceID+=1,this.instanceID>0&&$()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const r=Object.assign(Object.assign({},kr),e);if(this.logDebugMessages=!!r.debug,typeof r.debug=="function"&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new vr({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=mt(r.fetch),this.lock=r.lock||rt,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:$()&&(!((t=globalThis?.navigator)===null||t===void 0)&&t.locks)?this.lock=br:this.lock=rt,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)},this.persistSession?r.storage?this.storage=r.storage:ne()?this.storage=yr:(this.memoryStorage={},this.storage=st(this.memoryStorage)):(this.memoryStorage={},this.storage=st(this.memoryStorage)),$()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${_t}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{const t=Qs(window.location.href);let s="none";if(this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce"),$()&&this.detectSessionInUrl&&s!=="none"){const{data:r,error:i}=await this._getSessionFromURL(t,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Fs(i)){const l=(e=i.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:i}}return await this._removeSession(),{error:i}}const{session:o,redirectType:a}=r;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 p(t)?{error:t}:{error:new yt("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{const i=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}},xform:x}),{data:o,error:a}=i;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(p(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var t,s,r;try{let i;if("email"in e){const{email:h,password:u,options:d}=e;let f=null,g=null;this.flowType==="pkce"&&([f,g]=await G(this.storage,this.storageKey)),i=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:h,password:u,data:(t=d?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:f,code_challenge_method:g},xform:x})}else if("phone"in e){const{phone:h,password:u,options:d}=e;i=await v(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:u,data:(s=d?.data)!==null&&s!==void 0?s:{},channel:(r=d?.channel)!==null&&r!==void 0?r:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:x})}else throw new ce("You must provide either an email or phone number and a password");const{data:o,error:a}=i;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(p(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let t;if("email"in e){const{email:i,password:o,options:a}=e;t=await v(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:tt})}else if("phone"in e){const{phone:i,password:o,options:a}=e;t=await v(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:tt})}else throw new ce("You must provide either an email or phone number and a password");const{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:!s||!s.session||!s.user?{data:{user:null,session:null},error:new ye}:(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(r=e.options)===null||r===void 0?void 0:r.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){const t=await ue(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(t??"").split("/");try{const{data:i,error:o}=await v(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:x});if(await de(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new ye}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:r??null}),error:o})}catch(i){if(p(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(e){try{const{options:t,provider:s,token:r,access_token:i,nonce:o}=e,a=await v(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:x}),{data:l,error:c}=a;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new ye}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,i,o;try{if("email"in e){const{email:a,options:l}=e;let c=null,h=null;this.flowType==="pkce"&&([c,h]=await G(this.storage,this.storageKey));const{error:u}=await v(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l?.data)!==null&&t!==void 0?t:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:h},redirectTo:l?.emailRedirectTo});return{data:{user:null,session:null},error:u}}if("phone"in e){const{phone:a,options:l}=e,{data:c,error:h}=await v(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c?.message_id},error:h}}throw new ce("You must provide either an email or phone number.")}catch(a){if(p(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let r,i;"options"in e&&(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:o,error:a}=await v(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:r,xform:x});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(r){if(p(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let i=null,o=null;return this.flowType==="pkce"&&([i,o]=await G(this.storage,this.storageKey)),await v(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&s!==void 0?s:void 0}),!((r=e?.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:o}),headers:this.headers,xform:dr})}catch(i){if(p(i))return{data:null,error:i};throw i}}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:s}=e;if(s)throw s;if(!t)throw new C;const{error:r}=await v(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(p(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:s,type:r,options:i}=e,{error:o}=await v(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){const{phone:s,type:r,options:i}=e,{data:o,error:a}=await v(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return{data:{user:null,session:null,messageId:o?.message_id},error:a}}throw new ce("You must provide either an email or phone number and a type")}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await s,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch{}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const r=[...this.pendingInLock];await Promise.all(r),this.pendingInLock.splice(0,r.length)}return await s}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{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 ue(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<ve:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,c,h)=>(!o&&c==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(l,c,h))})}return{data:{session:e},error:null}}const{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:r},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 v(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:L}):await this._useSession(async t=>{var s,r,i;const{data:o,error:a}=t;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new C}:await v(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0,xform:L})})}catch(t){if(p(t))return Ns(t)&&(await this._removeSession(),await de(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{const{data:r,error:i}=s;if(i)throw i;if(!r.session)throw new C;const o=r.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await G(this.storage,this.storageKey));const{data:c,error:h}=await v(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:L});if(h)throw h;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(s){if(p(s))return{data:{user:null},error:s};throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new C;const t=Date.now()/1e3;let s=t,r=!0,i=null;const{payload:o}=me(e.access_token);if(o.exp&&(s=o.exp,r=s<=t),r){const{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};i=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(t){if(p(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){const{data:o,error:a}=t;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new C;const{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(p(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!$())throw new he("No browser detected.");if(e.error||e.error_description||e.error_code)throw new he(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 We("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new he("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 We("No code detected.");const{data:A,error:k}=await this._exchangeCodeForSession(e.code);if(k)throw k;const S=new URL(window.location.href);return S.searchParams.delete("code"),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:A.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:r,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!i||!a||!o||!c)throw new he("No session defined in URL");const h=Math.round(Date.now()/1e3),u=parseInt(a);let d=h+u;l&&(d=parseInt(l));const f=d-h;f*1e3<=W&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);const g=d-u;h-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,d,h):h-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,d,h);const{data:y,error:_}=await this._getUser(i);if(_)throw _;const E={provider_token:s,provider_refresh_token:r,access_token:i,expires_in:u,expires_at:d,refresh_token:o,token_type:c,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:E,redirectType:e.type},error:null}}catch(s){if(p(s))return{data:{session:null,redirectType:null},error:s};throw s}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await ue(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;const{data:r,error:i}=t;if(i)return{error:i};const o=(s=r.session)===null||s===void 0?void 0:s.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!(Bs(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await de(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t=Ws(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;try{const{data:{session:i},error:o}=t;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;this.flowType==="pkce"&&([s,r]=await G(this.storage,this.storageKey,!0));try{return await v(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(p(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{const{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(p(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{const{data:s,error:r}=await this._useSession(async i=>{var o,a,l,c,h;const{data:u,error:d}=i;if(d)throw d;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await v(this.fetch,"GET",f,{headers:this.headers,jwt:(h=(c=u.session)===null||c===void 0?void 0:c.access_token)!==null&&h!==void 0?h:void 0})});if(r)throw r;return $()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),{data:{provider:e.provider,url:s?.url},error:null}}catch(s){if(p(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;const{data:i,error:o}=t;if(o)throw o;return await v(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(r=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&r!==void 0?r:void 0})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const s=Date.now();return await Zs(async r=>(r>0&&await Ys(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await v(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:x})),(r,i)=>{const o=200*Math.pow(2,r);return i&&we(i)&&Date.now()+o-s<W})}catch(s){if(this._debug(t,"error",s),p(s))return{data:{session:null,user:null},error:s};throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),$()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;const t="#_recoverAndRefresh()";this._debug(t,"begin");try{const s=await ue(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s)){this._debug(t,"session is not valid"),s!==null&&await this._removeSession();return}const r=((e=s.expires_at)!==null&&e!==void 0?e:1/0)*1e3-Date.now()<ve;if(this._debug(t,`session has${r?"":" not"} expired with margin of ${ve}s`),r){if(this.autoRefreshToken&&s.refresh_token){const{error:i}=await this._callRefreshToken(s.refresh_token);i&&(console.error(i),we(i)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(t,"error",s),console.error(s);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new C;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new ge;const{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new C;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const a={session:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(r,"error",i),p(i)){const o={session:null,error:i};return we(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){const r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await bt(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await de(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&$()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),W);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:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const r=Math.floor((s.expires_at*1e3-e)/W);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts ${W}ms, refresh threshold is ${Pe} ticks`),r<=Pe&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof kt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!$()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){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,s){const r=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,o]=await G(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(a.toString())}if(s?.queryParams){const i=new URLSearchParams(s.queryParams);r.push(i.toString())}return s?.skipBrowserRedirect&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;const{data:r,error:i}=t;return i?{data:null,error:i}:await v(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,r;const{data:i,error:o}=t;if(o)return{data:null,error:o};const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:l,error:c}=await v(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return c?{data:null,error:c}:(e.factorType==="totp"&&(!((r=l?.totp)===null||r===void 0)&&r.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),{data:l,error:null})})}catch(t){if(p(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:r,error:i}=t;if(i)return{data:null,error:i};const{data:o,error:a}=await v(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:r,error:i}=t;return i?{data:null,error:i}:await v(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(s=r?.session)===null||s===void 0?void 0:s.access_token})})}catch(t){if(p(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){const{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){const{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};const s=e?.factors||[],r=s.filter(o=>o.factor_type==="totp"&&o.status==="verified"),i=s.filter(o=>o.factor_type==="phone"&&o.status==="verified");return{data:{all:s,totp:r,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;const{data:{session:r},error:i}=e;if(i)return{data:null,error:i};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=me(r.access_token);let a=null;o.aal&&(a=o.aal);let l=a;((s=(t=r.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(l="aal2");const h=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:h},error:null}}))}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(o=>o.kid===e);if(s||(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+Ds>Date.now()))return s;const{data:r,error:i}=await v(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;if(!r.keys||r.keys.length===0)throw new ie("JWKS is empty");if(this.jwks=r,this.jwks_cached_at=Date.now(),s=r.keys.find(o=>o.kid===e),!s)throw new ie("No matching signing key found in JWKS");return s}async getClaims(e,t={keys:[]}){try{let s=e;if(!s){const{data:f,error:g}=await this.getSession();if(g||!f.session)return{data:null,error:g};s=f.session.access_token}const{header:r,payload:i,signature:o,raw:{header:a,payload:l}}=me(s);if(or(i.exp),!r.kid||r.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:i,header:r,signature:o},error:null}}const c=ar(r.alg),h=await this.fetchJwk(r.kid,t),u=await crypto.subtle.importKey("jwk",h,c,!0,["verify"]);if(!await crypto.subtle.verify(c,u,o,Gs(`${a}.${l}`)))throw new ie("Invalid JWT signature");return{data:{claims:i,header:r,signature:o},error:null}}catch(s){if(p(s))return{data:null,error:s};throw s}}}oe.nextInstanceID=0;const Sr=oe;class Tr extends Sr{constructor(e){super(e)}}var Er=function(n,e,t,s){function r(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(h){try{c(s.next(h))}catch(u){o(u)}}function l(h){try{c(s.throw(h))}catch(u){o(u)}}function c(h){h.done?i(h.value):r(h.value).then(a,l)}c((s=s.apply(n,[])).next())})};class Pr{constructor(e,t,s){var r,i,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");const a=Rs(e);this.realtimeUrl=`${a}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${a}/auth/v1`,this.storageUrl=`${a}/storage/v1`,this.functionsUrl=`${a}/functions/v1`;const l=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,c={db:Ss,realtime:Es,auth:Object.assign(Object.assign({},Ts),{storageKey:l}),global:ks},h=Cs(s??{},c);this.storageKey=(r=h.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.accessToken,this.auth=new Proxy({},{get:(u,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=h.auth)!==null&&o!==void 0?o:{},this.headers,h.global.fetch),this.fetch=As(t,this._getAccessToken.bind(this),h.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},h.realtime)),this.rest=new zt(`${a}/rest/v1`,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new Ct(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ws(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Er(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:s}=yield this.auth.getSession();return(t=(e=s.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,storageKey:i,flowType:o,lock:a,debug:l},c,h){const u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Tr({url:this.authUrl,headers:Object.assign(Object.assign({},u),c),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:o,lock:a,debug:l,fetch:h,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new ns(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,s)=>{this._handleTokenChanged(t,"CLIENT",s?.access_token)})}_handleTokenChanged(e,t,s){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==s?this.changedAccessToken=s:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const xr=(n,e,t)=>new Pr(n,e,t);export{X as _,xr as c}; //# sourceMappingURL=supabase-vendor-DtZyL83W.js.map
Close