Files
manage/dist/assets/index-3808da28.js
2024-12-23 21:06:40 +08:00

25 lines
128 KiB
JavaScript

import{r as y,a as mr,g as vr,b as yr,c as O,u as br,d as we,e as tt,m as L,M as wr,f as kr,S as xr,D as jr,B as le,U as lt,L as ce,h as Tr,A as ct,R as ke,i as Sr,j as rt,O as Pr,F as W,I as ht,k as Er,l as Or,G as $r,n as Ar,C as Ot,o as Cr,p as Rr,q as Ir,W as Lr,E as Dr,N as Ve,s as Ur,t as V,v as Nr,w as $t,x as ut}from"./vendor-61f0f29a.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const n of i)if(n.type==="childList")for(const o of n.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function t(i){const n={};return i.integrity&&(n.integrity=i.integrity),i.referrerPolicy&&(n.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?n.credentials="include":i.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(i){if(i.ep)return;i.ep=!0;const n=t(i);fetch(i.href,n)}})();var At={exports:{}},xe={};/**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Mr=y,Fr=Symbol.for("react.element"),Br=Symbol.for("react.fragment"),zr=Object.prototype.hasOwnProperty,qr=Mr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Jr={key:!0,ref:!0,__self:!0,__source:!0};function Ct(s,e,t){var r,i={},n=null,o=null;t!==void 0&&(n=""+t),e.key!==void 0&&(n=""+e.key),e.ref!==void 0&&(o=e.ref);for(r in e)zr.call(e,r)&&!Jr.hasOwnProperty(r)&&(i[r]=e[r]);if(s&&s.defaultProps)for(r in e=s.defaultProps,e)i[r]===void 0&&(i[r]=e[r]);return{$$typeof:Fr,type:s,key:n,ref:o,props:i,_owner:qr.current}}xe.Fragment=Br;xe.jsx=Ct;xe.jsxs=Ct;At.exports=xe;var u=At.exports,Ge={},dt=mr;Ge.createRoot=dt.createRoot,Ge.hydrateRoot=dt.hydrateRoot;var je={},Rt={exports:{}};(function(s){function e(t){return t&&t.__esModule?t:{default:t}}s.exports=e,s.exports.__esModule=!0,s.exports.default=s.exports})(Rt);var Te=Rt.exports,Se={};Object.defineProperty(Se,"__esModule",{value:!0});Se.default=void 0;var Vr={items_per_page:"条/页",jump_to:"跳至",jump_to_confirm:"确定",page:"页",prev_page:"上一页",next_page:"下一页",prev_5:"向前 5 页",next_5:"向后 5 页",prev_3:"向前 3 页",next_3:"向后 3 页",page_size:"页码"};Se.default=Vr;var Pe={},ue={},Ee={},It={exports:{}},Lt={exports:{}},Dt={exports:{}},Ut={exports:{}};(function(s){function e(t){"@babel/helpers - typeof";return s.exports=e=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},s.exports.__esModule=!0,s.exports.default=s.exports,e(t)}s.exports=e,s.exports.__esModule=!0,s.exports.default=s.exports})(Ut);var Nt=Ut.exports,Mt={exports:{}};(function(s){var e=Nt.default;function t(r,i){if(e(r)!="object"||!r)return r;var n=r[Symbol.toPrimitive];if(n!==void 0){var o=n.call(r,i||"default");if(e(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(i==="string"?String:Number)(r)}s.exports=t,s.exports.__esModule=!0,s.exports.default=s.exports})(Mt);var Gr=Mt.exports;(function(s){var e=Nt.default,t=Gr;function r(i){var n=t(i,"string");return e(n)=="symbol"?n:n+""}s.exports=r,s.exports.__esModule=!0,s.exports.default=s.exports})(Dt);var Kr=Dt.exports;(function(s){var e=Kr;function t(r,i,n){return(i=e(i))in r?Object.defineProperty(r,i,{value:n,enumerable:!0,configurable:!0,writable:!0}):r[i]=n,r}s.exports=t,s.exports.__esModule=!0,s.exports.default=s.exports})(Lt);var Hr=Lt.exports;(function(s){var e=Hr;function t(i,n){var o=Object.keys(i);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(i);n&&(a=a.filter(function(l){return Object.getOwnPropertyDescriptor(i,l).enumerable})),o.push.apply(o,a)}return o}function r(i){for(var n=1;n<arguments.length;n++){var o=arguments[n]!=null?arguments[n]:{};n%2?t(Object(o),!0).forEach(function(a){e(i,a,o[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(o)):t(Object(o)).forEach(function(a){Object.defineProperty(i,a,Object.getOwnPropertyDescriptor(o,a))})}return i}s.exports=r,s.exports.__esModule=!0,s.exports.default=s.exports})(It);var Wr=It.exports,Oe={};Object.defineProperty(Oe,"__esModule",{value:!0});Oe.commonLocale=void 0;Oe.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0};var Yr=Te.default;Object.defineProperty(Ee,"__esModule",{value:!0});Ee.default=void 0;var ft=Yr(Wr),Qr=Oe,Xr=(0,ft.default)((0,ft.default)({},Qr.commonLocale),{},{locale:"zh_CN",today:"今天",now:"此刻",backToToday:"返回今天",ok:"确定",timeSelect:"选择时间",dateSelect:"选择日期",weekSelect:"选择周",clear:"清除",month:"月",year:"年",previousMonth:"上个月 (翻页上键)",nextMonth:"下个月 (翻页下键)",monthSelect:"选择月份",yearSelect:"选择年份",decadeSelect:"选择年代",previousYear:"上一年 (Control键加左方向键)",nextYear:"下一年 (Control键加右方向键)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世纪",nextCentury:"下一世纪",yearFormat:"YYYY年",cellDateFormat:"D",monthBeforeYear:!1});Ee.default=Xr;var de={};Object.defineProperty(de,"__esModule",{value:!0});de.default=void 0;const Zr={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};de.default=Zr;var Ft=Te.default;Object.defineProperty(ue,"__esModule",{value:!0});ue.default=void 0;var es=Ft(Ee),ts=Ft(de);const Bt={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},es.default),timePickerLocale:Object.assign({},ts.default)};Bt.lang.ok="确定";ue.default=Bt;var rs=Te.default;Object.defineProperty(Pe,"__esModule",{value:!0});Pe.default=void 0;var ss=rs(ue);Pe.default=ss.default;var $e=Te.default;Object.defineProperty(je,"__esModule",{value:!0});je.default=void 0;var is=$e(Se),ns=$e(Pe),os=$e(ue),as=$e(de);const P="${label}不是一个有效的${type}",ls={locale:"zh-cn",Pagination:is.default,DatePicker:os.default,TimePicker:as.default,Calendar:ns.default,global:{placeholder:"请选择"},Table:{filterTitle:"筛选",filterConfirm:"确定",filterReset:"重置",filterEmptyText:"无筛选项",filterCheckall:"全选",filterSearchPlaceholder:"在筛选项中搜索",emptyText:"暂无数据",selectAll:"全选当页",selectInvert:"反选当页",selectNone:"清空所有",selectionAll:"全选所有",sortTitle:"排序",expand:"展开行",collapse:"关闭行",triggerDesc:"点击降序",triggerAsc:"点击升序",cancelSort:"取消排序"},Modal:{okText:"确定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"结束导览"},Popconfirm:{cancelText:"取消",okText:"确定"},Transfer:{titles:["",""],searchPlaceholder:"请输入搜索内容",itemUnit:"项",itemsUnit:"项",remove:"删除",selectCurrent:"全选当页",removeCurrent:"删除当页",selectAll:"全选所有",deselectAll:"取消全选",removeAll:"删除全部",selectInvert:"反选当页"},Upload:{uploading:"文件上传中",removeFile:"删除文件",uploadError:"上传错误",previewFile:"预览文件",downloadFile:"下载文件"},Empty:{description:"暂无数据"},Icon:{icon:"图标"},Text:{edit:"编辑",copy:"复制",copied:"复制成功",expand:"展开",collapse:"收起"},Form:{optional:"(可选)",defaultValidateMessages:{default:"字段验证错误${label}",required:"请输入${label}",enum:"${label}必须是其中一个[${enum}]",whitespace:"${label}不能为空字符",date:{format:"${label}日期格式无效",parse:"${label}不能转换为日期",invalid:"${label}是一个无效日期"},types:{string:P,method:P,array:P,object:P,number:P,date:P,boolean:P,integer:P,float:P,regexp:P,email:P,url:P,hex:P},string:{len:"${label}须为${len}个字符",min:"${label}最少${min}个字符",max:"${label}最多${max}个字符",range:"${label}须在${min}-${max}字符之间"},number:{len:"${label}必须等于${len}",min:"${label}最小值为${min}",max:"${label}最大值为${max}",range:"${label}须在${min}-${max}之间"},array:{len:"须为${len}个${label}",min:"最少${min}个${label}",max:"最多${max}个${label}",range:"${label}数量须在${min}-${max}之间"},pattern:{mismatch:"${label}与模式不匹配${pattern}"}}},Image:{preview:"预览"},QRCode:{expired:"二维码过期",refresh:"点击刷新",scanned:"已扫描"},ColorPicker:{presetEmpty:"暂无",transparent:"无色",singleColor:"单色",gradientColor:"渐变色"}};je.default=ls;var cs=je;const hs=vr(cs),zt=y.createContext(),us=({children:s})=>{const[e,t]=y.useState(()=>{const i=localStorage.getItem("theme");return i==="dark"||i===null&&window.matchMedia("(prefers-color-scheme: dark)").matches});y.useEffect(()=>{localStorage.setItem("theme",e?"dark":"light"),document.documentElement.classList.toggle("dark",e)},[e]);const r=()=>{t(!e)};return u.jsx(zt.Provider,{value:{isDarkMode:e,toggleTheme:r},children:s})},fe=()=>{const s=y.useContext(zt);if(!s)throw new Error("useTheme must be used within a ThemeProvider");return s},ds="modulepreload",fs=function(s){return"/"+s},pt={},x=function(e,t,r){if(!t||t.length===0)return e();const i=document.getElementsByTagName("link");return Promise.all(t.map(n=>{if(n=fs(n),n in pt)return;pt[n]=!0;const o=n.endsWith(".css"),a=o?'[rel="stylesheet"]':"";if(!!r)for(let c=i.length-1;c>=0;c--){const d=i[c];if(d.href===n&&(!o||d.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${n}"]${a}`))return;const h=document.createElement("link");if(h.rel=o?"stylesheet":ds,o||(h.as="script",h.crossOrigin=""),h.href=n,document.head.appendChild(h),o)return new Promise((c,d)=>{h.addEventListener("load",c),h.addEventListener("error",()=>d(new Error(`Unable to preload CSS for ${n}`)))})})).then(()=>e()).catch(n=>{const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=n,window.dispatchEvent(o),!o.defaultPrevented)throw n})},ps=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>x(()=>Promise.resolve().then(()=>te),void 0).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)};class st extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class gs extends st{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class _s extends st{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class ms extends st{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Ke;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(Ke||(Ke={}));var vs=globalThis&&globalThis.__awaiter||function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(d){o(d)}}function l(c){try{h(r.throw(c))}catch(d){o(d)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})};class ys{constructor(e,{headers:t={},customFetch:r,region:i=Ke.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=ps(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return vs(this,void 0,void 0,function*(){try{const{headers:i,method:n,body:o}=t;let a={},{region:l}=t;l||(l=this.region),l&&l!=="any"&&(a["x-region"]=l);let h;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",h=o):typeof o=="string"?(a["Content-Type"]="text/plain",h=o):typeof FormData<"u"&&o instanceof FormData?h=o:(a["Content-Type"]="application/json",h=JSON.stringify(o)));const c=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:h}).catch(_=>{throw new gs(_)}),d=c.headers.get("x-relay-error");if(d&&d==="true")throw new _s(c);if(!c.ok)throw new ms(c);let f=((r=c.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),g;return f==="application/json"?g=yield c.json():f==="application/octet-stream"?g=yield c.blob():f==="text/event-stream"?g=c:f==="multipart/form-data"?g=yield c.formData():g=yield c.text(),{data:g,error:null}}catch(i){return{data:null,error:i}}})}}var S={},it={},Ae={},pe={},Ce={},Re={},bs=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},ee=bs();const ws=ee.fetch,qt=ee.fetch.bind(ee),Jt=ee.Headers,ks=ee.Request,xs=ee.Response,te=Object.freeze(Object.defineProperty({__proto__:null,Headers:Jt,Request:ks,Response:xs,default:qt,fetch:ws},Symbol.toStringTag,{value:"Module"})),js=yr(te);var Ie={};Object.defineProperty(Ie,"__esModule",{value:!0});class Ts extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}}Ie.default=Ts;var Vt=O&&O.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Re,"__esModule",{value:!0});const Ss=Vt(js),Ps=Vt(Ie);let Es=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=Ss.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=Object.assign({},this.headers),this.headers[e]=t,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{var o,a,l;let h=null,c=null,d=null,f=n.status,g=n.statusText;if(n.ok){if(this.method!=="HEAD"){const w=await n.text();w===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?c=w:c=JSON.parse(w))}const m=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),p=(a=n.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");m&&p&&p.length>1&&(d=parseInt(p[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(c)&&(c.length>1?(h={code:"PGRST116",details:`Results contain ${c.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},c=null,d=null,f=406,g="Not Acceptable"):c.length===1?c=c[0]:c=null)}else{const m=await n.text();try{h=JSON.parse(m),Array.isArray(h)&&n.status===404&&(c=[],h=null,f=200,g="OK")}catch{n.status===404&&m===""?(f=204,g="No Content"):h={message:m}}if(h&&this.isMaybeSingle&&(!((l=h==null?void 0:h.details)===null||l===void 0)&&l.includes("0 rows"))&&(h=null,f=200,g="OK"),h&&this.shouldThrowOnError)throw new Ps.default(h)}return{error:h,data:c,count:d,status:f,statusText:g}});return this.shouldThrowOnError||(i=i.catch(n=>{var o,a,l;return{error:{message:`${(o=n==null?void 0:n.name)!==null&&o!==void 0?o:"FetchError"}: ${n==null?void 0:n.message}`,details:`${(a=n==null?void 0:n.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(l=n==null?void 0:n.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}};Re.default=Es;var Os=O&&O.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ce,"__esModule",{value:!0});const $s=Os(Re);let As=class extends $s.default{select(e){let t=!1;const r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i,referencedTable:n=i}={}){const o=n?`${n}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){const i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:i=r}={}){const n=typeof i>"u"?"offset":`${i}.offset`,o=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(o,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:i=!1,wal:n=!1,format:o="text"}={}){var a;const l=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,n?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${h}"; options=${l};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};Ce.default=As;var Cs=O&&O.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(pe,"__esModule",{value:!0});const Rs=Cs(Ce);let Is=class extends Rs.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){const r=Array.from(new Set(t)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:i}={}){let n="";i==="plain"?n="pl":i==="phrase"?n="ph":i==="websearch"&&(n="w");const o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){const i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}};pe.default=Is;var Ls=O&&O.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ae,"__esModule",{value:!0});const se=Ls(pe);let Ds=class{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){const i=t?"HEAD":"GET";let n=!1;const o=(e??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new se.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){const i="POST",n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){const o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){const a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new se.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:n=!0}={}){const o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){const l=e.reduce((h,c)=>h.concat(Object.keys(c)),[]);if(l.length>0){const h=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",h.join(","))}}return new se.default({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){const r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new se.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){const t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new se.default({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Ae.default=Ds;var Le={},De={};Object.defineProperty(De,"__esModule",{value:!0});De.version=void 0;De.version="0.0.0-automated";Object.defineProperty(Le,"__esModule",{value:!0});Le.DEFAULT_HEADERS=void 0;const Us=De;Le.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Us.version}`};var Gt=O&&O.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(it,"__esModule",{value:!0});const Ns=Gt(Ae),Ms=Gt(pe),Fs=Le;let Bs=class Kt{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},Fs.DEFAULT_HEADERS),t),this.schemaName=r,this.fetch=i}from(e){const t=new URL(`${this.url}/${e}`);return new Ns.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new Kt(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:n}={}){let o;const a=new URL(`${this.url}/rpc/${e}`);let l;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([c,d])=>d!==void 0).map(([c,d])=>[c,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([c,d])=>{a.searchParams.append(c,d)})):(o="POST",l=t);const h=Object.assign({},this.headers);return n&&(h.Prefer=`count=${n}`),new Ms.default({method:o,url:a,headers:h,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1})}};it.default=Bs;var re=O&&O.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(S,"__esModule",{value:!0});S.PostgrestError=S.PostgrestBuilder=S.PostgrestTransformBuilder=S.PostgrestFilterBuilder=S.PostgrestQueryBuilder=S.PostgrestClient=void 0;const Ht=re(it);S.PostgrestClient=Ht.default;const Wt=re(Ae);S.PostgrestQueryBuilder=Wt.default;const Yt=re(pe);S.PostgrestFilterBuilder=Yt.default;const Qt=re(Ce);S.PostgrestTransformBuilder=Qt.default;const Xt=re(Re);S.PostgrestBuilder=Xt.default;const Zt=re(Ie);S.PostgrestError=Zt.default;var zs=S.default={PostgrestClient:Ht.default,PostgrestQueryBuilder:Wt.default,PostgrestFilterBuilder:Yt.default,PostgrestTransformBuilder:Qt.default,PostgrestBuilder:Xt.default,PostgrestError:Zt.default};const{PostgrestClient:qs,PostgrestQueryBuilder:ro,PostgrestFilterBuilder:so,PostgrestTransformBuilder:io,PostgrestBuilder:no}=zs,Js="2.11.2",Vs={"X-Client-Info":`realtime-js/${Js}`},Gs="1.0.0",er=1e4,Ks=1e3;var Z;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(Z||(Z={}));var E;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(E||(E={}));var R;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(R||(R={}));var He;(function(s){s.websocket="websocket"})(He||(He={}));var G;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(G||(G={}));class Hs{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),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){const i=t.getUint8(1),n=t.getUint8(2);let o=this.HEADER_LENGTH+2;const a=r.decode(e.slice(o,o+i));o=o+i;const l=r.decode(e.slice(o,o+n));o=o+n;const h=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:h}}}class tr{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 k;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(k||(k={}));const gt=(s,e,t={})=>{var r;const i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((n,o)=>(n[o]=Ws(o,s,e,i),n),{})},Ws=(s,e,t,r)=>{const i=e.find(a=>a.name===s),n=i==null?void 0:i.type,o=t[s];return n&&!r.includes(n)?rr(n,o):We(o)},rr=(s,e)=>{if(s.charAt(0)==="_"){const t=s.slice(1,s.length);return Zs(e,t)}switch(s){case k.bool:return Ys(e);case k.float4:case k.float8:case k.int2:case k.int4:case k.int8:case k.numeric:case k.oid:return Qs(e);case k.json:case k.jsonb:return Xs(e);case k.timestamp:return ei(e);case k.abstime:case k.date:case k.daterange:case k.int4range:case k.int8range:case k.money:case k.reltime:case k.text:case k.time:case k.timestamptz:case k.timetz:case k.tsrange:case k.tstzrange:return We(e);default:return We(e)}},We=s=>s,Ys=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Qs=s=>{if(typeof s=="string"){const e=parseFloat(s);if(!Number.isNaN(e))return e}return s},Xs=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},Zs=(s,e)=>{if(typeof s!="string")return s;const t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let n;const o=s.slice(1,t);try{n=JSON.parse("["+o+"]")}catch{n=o?o.split(","):[]}return n.map(a=>rr(e,a))}return s},ei=s=>typeof s=="string"?s.replace(" ","T"):s,sr=s=>{let e=s;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};class Me{constructor(e,t,r={},i=er){this.channel=e,this.event=t,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var _t;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(_t||(_t={}));class oe{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(t==null?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{const{onJoin:n,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=oe.syncState(this.state,i,n,o),this.pendingDiffs.forEach(l=>{this.state=oe.syncDiff(this.state,l,n,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{const{onJoin:n,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=oe.syncDiff(this.state,i,n,o),a())}),this.onJoin((i,n,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:n,newPresences:o})}),this.onLeave((i,n,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:n,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){const n=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(n,(h,c)=>{o[h]||(l[h]=c)}),this.map(o,(h,c)=>{const d=n[h];if(d){const f=c.map(p=>p.presence_ref),g=d.map(p=>p.presence_ref),_=c.filter(p=>g.indexOf(p.presence_ref)<0),m=d.filter(p=>f.indexOf(p.presence_ref)<0);_.length>0&&(a[h]=_),m.length>0&&(l[h]=m)}else a[h]=c}),this.syncDiff(n,{joins:a,leaves:l},r,i)}static syncDiff(e,t,r,i){const{joins:n,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(n,(a,l)=>{var h;const c=(h=e[a])!==null&&h!==void 0?h:[];if(e[a]=this.cloneDeep(l),c.length>0){const d=e[a].map(g=>g.presence_ref),f=c.filter(g=>d.indexOf(g.presence_ref)<0);e[a].unshift(...f)}r(a,c,l)}),this.map(o,(a,l)=>{let h=e[a];if(!h)return;const c=l.map(d=>d.presence_ref);h=h.filter(d=>c.indexOf(d.presence_ref)<0),e[a]=h,i(a,h,l),h.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const i=e[r];return"metas"in i?t[r]=i.metas.map(n=>(n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n)):t[r]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var mt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(mt||(mt={}));var vt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(vt||(vt={}));var U;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(U||(U={}));class nt{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=E.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 Me(this,R.join,this.params,this.timeout),this.rejoinTimer=new tr(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=E.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=E.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=E.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=E.errored,this.rejoinTimer.scheduleTimeout())}),this._on(R.reply,{},(i,n)=>{this._trigger(this._replyEventName(n),i)}),this.presence=new oe(this),this.broadcastEndpointURL=sr(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var r,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:n,presence:o,private:a}}=this.params;this._onError(c=>e==null?void 0:e(U.CHANNEL_ERROR,c)),this._onClose(()=>e==null?void 0:e(U.CLOSED));const l={},h={broadcast:n,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(c=>c.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessTokenValue&&(l.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:h},l)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:c})=>{var d;if(this.socket.setAuth(),c===void 0){e==null||e(U.SUBSCRIBED);return}else{const f=this.bindings.postgres_changes,g=(d=f==null?void 0:f.length)!==null&&d!==void 0?d:0,_=[];for(let m=0;m<g;m++){const p=f[m],{filter:{event:w,schema:D,table:I,filter:$}}=p,A=c&&c[m];if(A&&A.event===w&&A.schema===D&&A.table===I&&A.filter===$)_.push(Object.assign(Object.assign({},p),{id:A.id}));else{this.unsubscribe(),e==null||e(U.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=_,e&&e(U.SUBSCRIBED);return}}).receive("error",c=>{e==null||e(U.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(c).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(U.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,i;if(!this._canPush()&&e.type==="broadcast"){const{event:n,payload:o}=e,l={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:o,private:this.private}]})};try{const h=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=h.body)===null||i===void 0?void 0:i.cancel()),h.ok?"ok":"error"}catch(h){return h.name==="AbortError"?"timed out":"error"}}else return new Promise(n=>{var o,a,l;const h=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&n("ok"),h.receive("ok",()=>n("ok")),h.receive("error",()=>n("error")),h.receive("timeout",()=>n("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=E.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(R.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{const i=new Me(this,R.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}async _fetchWithTimeout(e,t,r){const i=new AbortController,n=setTimeout(()=>i.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:i.signal}));return clearTimeout(n),o}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new Me(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,n;const o=e.toLocaleLowerCase(),{close:a,error:l,leave:h,join:c}=R;if(r&&[a,l,h,c].indexOf(o)>=0&&r!==this._joinRef())return;let f=this._onMessage(o,t,r);if(t&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(g=>{var _,m,p;return((_=g.filter)===null||_===void 0?void 0:_.event)==="*"||((p=(m=g.filter)===null||m===void 0?void 0:m.event)===null||p===void 0?void 0:p.toLocaleLowerCase())===o}).map(g=>g.callback(f,r)):(n=this.bindings[o])===null||n===void 0||n.filter(g=>{var _,m,p,w,D,I;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in g){const $=g.id,A=(_=g.filter)===null||_===void 0?void 0:_.event;return $&&((m=t.ids)===null||m===void 0?void 0:m.includes($))&&(A==="*"||(A==null?void 0:A.toLocaleLowerCase())===((p=t.data)===null||p===void 0?void 0:p.type.toLocaleLowerCase()))}else{const $=(D=(w=g==null?void 0:g.filter)===null||w===void 0?void 0:w.event)===null||D===void 0?void 0:D.toLocaleLowerCase();return $==="*"||$===((I=t==null?void 0:t.event)===null||I===void 0?void 0:I.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===o}).map(g=>{if(typeof f=="object"&&"ids"in f){const _=f.data,{schema:m,table:p,commit_timestamp:w,type:D,errors:I}=_;f=Object.assign(Object.assign({},{schema:m,table:p,commit_timestamp:w,eventType:D,new:{},old:{},errors:I}),this._getPayloadRecords(_))}g.callback(f,r)})}_isClosed(){return this.state===E.closed}_isJoined(){return this.state===E.joined}_isJoining(){return this.state===E.joining}_isLeaving(){return this.state===E.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const i=e.toLocaleLowerCase(),n={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(n):this.bindings[i]=[n],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var n;return!(((n=i.type)===null||n===void 0?void 0:n.toLocaleLowerCase())===r&&nt.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(R.close,{},e)}_onError(e){this._on(R.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=E.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=gt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=gt(e.columns,e.old_record)),t}}const ti=()=>{},ri=typeof WebSocket<"u",si=`
addEventListener("message", (e) => {
if (e.data.event === "start") {
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
}
});`;class ii{constructor(e,t){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=Vs,this.params={},this.timeout=er,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=ti,this.conn=null,this.sendBuffer=[],this.serializer=new Hs,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=n=>{let o;return n?o=n:typeof fetch>"u"?o=(...a)=>x(()=>Promise.resolve().then(()=>te),void 0).then(({default:l})=>l(...a)):o=fetch,(...a)=>o(...a)},this.endPoint=`${e}/${He.websocket}`,this.httpEndpoint=sr(e),t!=null&&t.transport?this.transport=t.transport:this.transport=null,t!=null&&t.params&&(this.params=t.params),t!=null&&t.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t!=null&&t.timeout&&(this.timeout=t.timeout),t!=null&&t.logger&&(this.logger=t.logger),t!=null&&t.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);const i=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.apikey;if(i&&(this.accessTokenValue=i,this.apiKey=i),this.reconnectAfterMs=t!=null&&t.reconnectAfterMs?t.reconnectAfterMs:n=>[1e3,2e3,5e3,1e4][n-1]||1e4,this.encode=t!=null&&t.encode?t.encode:(n,o)=>o(JSON.stringify(n)),this.decode=t!=null&&t.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new tr(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t==null?void 0:t.fetch),t!=null&&t.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(t==null?void 0:t.worker)||!1,this.workerUrl=t==null?void 0:t.workerUrl}this.accessToken=(t==null?void 0:t.accessToken)||null}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers});return}if(ri){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new ni(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),x(()=>import("./browser-f9352300.js").then(e=>e.b),["assets/browser-f9352300.js","assets/vendor-61f0f29a.js"]).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:Gs}))}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,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case Z.connecting:return G.Connecting;case Z.open:return G.Open;case Z.closing:return G.Closing;default:return G.Closed}}isConnected(){return this.connectionState()===G.Open}channel(e,t={config:{}}){const r=new nt(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){const{topic:t,event:r,payload:i,ref:n}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${r} (${n})`,i),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){let t=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;if(t){let r=null;try{r=JSON.parse(atob(t.split(".")[1]))}catch{}if(r&&r.exp&&!(Math.floor(Date.now()/1e3)-r.exp<0))return this.log("auth",`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${r.exp}`),Promise.reject(`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${r.exp}`);this.accessTokenValue=t,this.channels.forEach(i=>{t&&i.updateJoinPayload({access_token:t}),i.joinedOnce&&i._isJoined()&&i._push(R.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(Ks,"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(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:n,ref:o}=t;o&&o===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,n),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,n,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}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(R.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_workerObjectUrl(e){let t;if(e)t=e;else{const r=new Blob([si],{type:"application/javascript"});t=URL.createObjectURL(r)}return t}}class ni{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Z.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}}class ot extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function j(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class oi extends ot{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class Ye extends ot{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var ai=globalThis&&globalThis.__awaiter||function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(d){o(d)}}function l(c){try{h(r.throw(c))}catch(d){o(d)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})};const ir=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>x(()=>Promise.resolve().then(()=>te),void 0).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},li=()=>ai(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield x(()=>Promise.resolve().then(()=>te),void 0)).Response:Response}),Qe=s=>{if(Array.isArray(s))return s.map(t=>Qe(t));if(typeof s=="function"||s!==Object(s))return s;const e={};return Object.entries(s).forEach(([t,r])=>{const i=t.replace(/([-_][a-z])/gi,n=>n.toUpperCase().replace(/[-_]/g,""));e[i]=Qe(r)}),e};var K=globalThis&&globalThis.__awaiter||function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(d){o(d)}}function l(c){try{h(r.throw(c))}catch(d){o(d)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})};const Fe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),ci=(s,e,t)=>K(void 0,void 0,void 0,function*(){const r=yield li();s instanceof r&&!(t!=null&&t.noResolveJson)?s.json().then(i=>{e(new oi(Fe(i),s.status||500))}).catch(i=>{e(new Ye(Fe(i),i))}):e(new Ye(Fe(s),s))}),hi=(s,e,t,r)=>{const i={method:s,headers:(e==null?void 0:e.headers)||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),r&&(i.body=JSON.stringify(r)),Object.assign(Object.assign({},i),t))};function ge(s,e,t,r,i,n){return K(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,hi(e,r,i,n)).then(l=>{if(!l.ok)throw l;return r!=null&&r.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>ci(l,a,r))})})}function be(s,e,t,r){return K(this,void 0,void 0,function*(){return ge(s,"GET",e,t,r)})}function F(s,e,t,r,i){return K(this,void 0,void 0,function*(){return ge(s,"POST",e,r,i,t)})}function ui(s,e,t,r,i){return K(this,void 0,void 0,function*(){return ge(s,"PUT",e,r,i,t)})}function di(s,e,t,r){return K(this,void 0,void 0,function*(){return ge(s,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),r)})}function nr(s,e,t,r,i){return K(this,void 0,void 0,function*(){return ge(s,"DELETE",e,r,i,t)})}var T=globalThis&&globalThis.__awaiter||function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(d){o(d)}}function l(c){try{h(r.throw(c))}catch(d){o(d)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})};const fi={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},yt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class pi{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=ir(i)}uploadOrUpdate(e,t,r,i){return T(this,void 0,void 0,function*(){try{let n;const o=Object.assign(Object.assign({},yt),i);let a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(n=new FormData,n.append("cacheControl",o.cacheControl),l&&n.append("metadata",this.encodeMetadata(l)),n.append("",r)):typeof FormData<"u"&&r instanceof FormData?(n=r,n.append("cacheControl",o.cacheControl),l&&n.append("metadata",this.encodeMetadata(l))):(n=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(l)))),i!=null&&i.headers&&(a=Object.assign(Object.assign({},a),i.headers));const h=this._removeEmptyFolders(t),c=this._getFinalPath(h),d=yield this.fetch(`${this.url}/object/${c}`,Object.assign({method:e,body:n,headers:a},o!=null&&o.duplex?{duplex:o.duplex}:{})),f=yield d.json();return d.ok?{data:{path:h,id:f.Id,fullPath:f.Key},error:null}:{data:null,error:f}}catch(n){if(j(n))return{data:null,error:n};throw n}})}upload(e,t,r){return T(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return T(this,void 0,void 0,function*(){const n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l;const h=Object.assign({upsert:yt.upsert},i),c=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",h.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",h.cacheControl)):(l=r,c["cache-control"]=`max-age=${h.cacheControl}`,c["content-type"]=h.contentType);const d=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:c}),f=yield d.json();return d.ok?{data:{path:n,fullPath:f.Key},error:null}:{data:null,error:f}}catch(l){if(j(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return T(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e);const i=Object.assign({},this.headers);t!=null&&t.upsert&&(i["x-upsert"]="true");const n=yield F(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(this.url+n.url),a=o.searchParams.get("token");if(!a)throw new ot("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}})}update(e,t,r){return T(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return T(this,void 0,void 0,function*(){try{return{data:yield F(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(j(i))return{data:null,error:i};throw i}})}copy(e,t,r){return T(this,void 0,void 0,function*(){try{return{data:{path:(yield F(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(j(i))return{data:null,error:i};throw i}})}createSignedUrl(e,t,r){return T(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),n=yield F(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${o}`)},{data:n,error:null}}catch(i){if(j(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return T(this,void 0,void 0,function*(){try{const i=yield F(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${n}`):null})),error:null}}catch(i){if(j(i))return{data:null,error:i};throw i}})}download(e,t){return T(this,void 0,void 0,function*(){const i=typeof(t==null?void 0:t.transform)<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),o=n?`?${n}`:"";try{const a=this._getFinalPath(e);return{data:yield(yield be(this.fetch,`${this.url}/${i}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(j(a))return{data:null,error:a};throw a}})}info(e){return T(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const r=yield be(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:Qe(r),error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}})}exists(e){return T(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield di(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(j(r)&&r instanceof Ye){const i=r.originalError;if([400,404].includes(i==null?void 0:i.status))return{data:!1,error:r}}throw r}})}getPublicUrl(e,t){const r=this._getFinalPath(e),i=[],n=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";n!==""&&i.push(n);const a=typeof(t==null?void 0:t.transform)<"u"?"render/image":"object",l=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});l!==""&&i.push(l);let h=i.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${h}`)}}}remove(e){return T(this,void 0,void 0,function*(){try{return{data:yield nr(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}list(e,t,r){return T(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},fi),t),{prefix:e||""});return{data:yield F(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(j(i))return{data:null,error:i};throw i}})}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 gi="2.7.1",_i={"X-Client-Info":`storage-js/${gi}`};var Y=globalThis&&globalThis.__awaiter||function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(d){o(d)}}function l(c){try{h(r.throw(c))}catch(d){o(d)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})};class mi{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},_i),t),this.fetch=ir(r)}listBuckets(){return Y(this,void 0,void 0,function*(){try{return{data:yield be(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(j(e))return{data:null,error:e};throw e}})}getBucket(e){return Y(this,void 0,void 0,function*(){try{return{data:yield be(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return Y(this,void 0,void 0,function*(){try{return{data:yield F(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return Y(this,void 0,void 0,function*(){try{return{data:yield ui(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}})}emptyBucket(e){return Y(this,void 0,void 0,function*(){try{return{data:yield F(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}deleteBucket(e){return Y(this,void 0,void 0,function*(){try{return{data:yield nr(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(j(t))return{data:null,error:t};throw t}})}}class vi extends mi{constructor(e,t={},r){super(e,t,r)}from(e){return new pi(this.url,this.headers,e,this.fetch)}}const yi="2.47.7";let ne="";typeof Deno<"u"?ne="deno":typeof document<"u"?ne="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ne="react-native":ne="node";const bi={"X-Client-Info":`supabase-js-${ne}/${yi}`},wi={headers:bi},ki={schema:"public"},xi={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ji={};var Ti=globalThis&&globalThis.__awaiter||function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(d){o(d)}}function l(c){try{h(r.throw(c))}catch(d){o(d)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})};const Si=s=>{let e;return s?e=s:typeof fetch>"u"?e=qt:e=fetch,(...t)=>e(...t)},Pi=()=>typeof Headers>"u"?Jt:Headers,Ei=(s,e,t)=>{const r=Si(t),i=Pi();return(n,o)=>Ti(void 0,void 0,void 0,function*(){var a;const l=(a=yield e())!==null&&a!==void 0?a:s;let h=new i(o==null?void 0:o.headers);return h.has("apikey")||h.set("apikey",s),h.has("Authorization")||h.set("Authorization",`Bearer ${l}`),r(n,Object.assign(Object.assign({},o),{headers:h}))})};var Oi=globalThis&&globalThis.__awaiter||function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(d){o(d)}}function l(c){try{h(r.throw(c))}catch(d){o(d)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})};function $i(s){return s.replace(/\/$/,"")}function Ai(s,e){const{db:t,auth:r,realtime:i,global:n}=s,{db:o,auth:a,realtime:l,global:h}=e,c={db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},l),i),global:Object.assign(Object.assign({},h),n),accessToken:()=>Oi(this,void 0,void 0,function*(){return""})};return s.accessToken?c.accessToken=s.accessToken:delete c.accessToken,c}const or="2.67.1",Ci="http://localhost:9999",Ri="supabase.auth.token",Ii={"X-Client-Info":`gotrue-js/${or}`},bt=10,Xe="X-Supabase-Api-Version",ar={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function Li(s){return Math.round(Date.now()/1e3)+s}function Di(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){const e=Math.random()*16|0;return(s=="x"?e:e&3|8).toString(16)})}const C=()=>typeof document<"u",z={tested:!1,writable:!1},ae=()=>{if(!C())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(z.tested)return z.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),z.tested=!0,z.writable=!0}catch{z.tested=!0,z.writable=!1}return z.writable};function Be(s){const e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((i,n)=>{e[n]=i})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}const lr=s=>{let e;return s?e=s:typeof fetch>"u"?e=(...t)=>x(()=>Promise.resolve().then(()=>te),void 0).then(({default:r})=>r(...t)):e=fetch,(...t)=>e(...t)},Ui=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",cr=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},_e=async(s,e)=>{const t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},me=async(s,e)=>{await s.removeItem(e)};function Ni(s){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",r,i,n,o,a,l,h,c=0;for(s=s.replace("-","+").replace("_","/");c<s.length;)o=e.indexOf(s.charAt(c++)),a=e.indexOf(s.charAt(c++)),l=e.indexOf(s.charAt(c++)),h=e.indexOf(s.charAt(c++)),r=o<<2|a>>4,i=(a&15)<<4|l>>2,n=(l&3)<<6|h,t=t+String.fromCharCode(r),l!=64&&i!=0&&(t=t+String.fromCharCode(i)),h!=64&&n!=0&&(t=t+String.fromCharCode(n));return t}class Ue{constructor(){this.promise=new Ue.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}Ue.promiseConstructor=Promise;function wt(s){const e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=s.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");const r=t[1];return JSON.parse(Ni(r))}async function Mi(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Fi(s,e){return new Promise((r,i)=>{(async()=>{for(let n=0;n<1/0;n++)try{const o=await s(n);if(!e(n,null,o)){r(o);return}}catch(o){if(!e(n,o)){i(o);return}}})()})}function Bi(s){return("0"+s.toString(16)).substr(-2)}function zi(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length;let i="";for(let n=0;n<56;n++)i+=t.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,Bi).join("")}async function qi(s){const t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),i=new Uint8Array(r);return Array.from(i).map(n=>String.fromCharCode(n)).join("")}function Ji(s){return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Vi(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;const t=await qi(s);return Ji(t)}async function Q(s,e,t=!1){const r=zi();let i=r;t&&(i+="/PASSWORD_RECOVERY"),await cr(s,`${e}-code-verifier`,i);const n=await Vi(r);return[n,r===n?"plain":"s256"]}const Gi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Ki(s){const e=s.headers.get(Xe);if(!e||!e.match(Gi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}class at extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function v(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class Hi extends at{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}function Wi(s){return v(s)&&s.name==="AuthApiError"}class hr extends at{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class H extends at{constructor(e,t,r,i){super(e,r,i),this.name=t,this.status=r}}class N extends H{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Yi(s){return v(s)&&s.name==="AuthSessionMissingError"}class ze extends H{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ve extends H{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class ye extends H{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 Qi(s){return v(s)&&s.name==="AuthImplicitGrantRedirectError"}class kt extends H{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 Ze extends H{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function qe(s){return v(s)&&s.name==="AuthRetryableFetchError"}class xt extends H{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}var Xi=globalThis&&globalThis.__rest||function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t};const J=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Zi=[502,503,504];async function jt(s){var e;if(!Ui(s))throw new Ze(J(s),0);if(Zi.includes(s.status))throw new Ze(J(s),s.status);let t;try{t=await s.json()}catch(n){throw new hr(J(n),n)}let r;const i=Ki(s);if(i&&i.getTime()>=ar["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new xt(J(t),s.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new N}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((n,o)=>n&&typeof o=="string",!0))throw new xt(J(t),s.status,t.weak_password.reasons);throw new Hi(J(t),s.status||500,r)}const en=(s,e,t,r)=>{const i={method:s,headers:(e==null?void 0:e.headers)||{}};return s==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function b(s,e,t,r){var i;const n=Object.assign({},r==null?void 0:r.headers);n[Xe]||(n[Xe]=ar["2024-01-01"].name),r!=null&&r.jwt&&(n.Authorization=`Bearer ${r.jwt}`);const o=(i=r==null?void 0:r.query)!==null&&i!==void 0?i:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await tn(s,e,t+a,{headers:n,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(l):{data:Object.assign({},l),error:null}}async function tn(s,e,t,r,i,n){const o=en(e,r,i,n);let a;try{a=await s(t,Object.assign({},o))}catch(l){throw console.error(l),new Ze(J(l),0)}if(a.ok||await jt(a),r!=null&&r.noResolveJson)return a;try{return await a.json()}catch(l){await jt(l)}}function M(s){var e;let t=null;on(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Li(s.expires_in)));const r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function Tt(s){const e=M(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function B(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function rn(s){return{data:s,error:null}}function sn(s){const{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n}=s,o=Xi(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:n},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function nn(s){return s}function on(s){return s.access_token&&s.refresh_token&&s.expires_in}var an=globalThis&&globalThis.__rest||function(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(s);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(s,r[i])&&(t[r[i]]=s[r[i]]);return t};class ln{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=lr(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await b(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(v(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await b(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:B})}catch(r){if(v(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{const{options:t}=e,r=an(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r==null?void 0:r.newEmail,delete i.newEmail),await b(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:sn,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(v(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await b(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:B})}catch(t){if(v(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,n,o,a,l;try{const h={nextPage:null,lastPage:0,total:0},c=await b(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(n=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&n!==void 0?n:""},xform:nn});if(c.error)throw c.error;const d=await c.json(),f=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,g=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return g.length>0&&(g.forEach(_=>{const m=parseInt(_.split(";")[0].split("=")[1].substring(0,1)),p=JSON.parse(_.split(";")[1].split("=")[1]);h[`${p}Page`]=m}),h.total=parseInt(f)),{data:Object.assign(Object.assign({},d),h),error:null}}catch(h){if(v(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await b(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:B})}catch(t){if(v(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await b(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:B})}catch(r){if(v(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await b(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:B})}catch(r){if(v(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{const{data:t,error:r}=await b(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(v(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await b(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(v(t))return{data:null,error:t};throw t}}}const cn={getItem:s=>ae()?globalThis.localStorage.getItem(s):null,setItem:(s,e)=>{ae()&&globalThis.localStorage.setItem(s,e)},removeItem:s=>{ae()&&globalThis.localStorage.removeItem(s)}};function St(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}function hn(){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 X={debug:!!(globalThis&&ae()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class ur extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class un extends ur{}async function dn(s,e,t){X.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);const r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),X.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async i=>{if(i){X.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,i.name);try{return await t()}finally{X.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,i.name)}}else{if(e===0)throw X.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new un(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(X.debug)try{const n=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(n,null," "))}catch(n){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",n)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}hn();const fn={url:Ci,storageKey:Ri,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ii,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},ie=30*1e3,Pt=3;async function Et(s,e,t){return await t()}class he{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=he.nextInstanceID,he.nextInstanceID+=1,this.instanceID>0&&C()&&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 i=Object.assign(Object.assign({},fn),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new ln({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=lr(i.fetch),this.lock=i.lock||Et,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:C()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=dn:this.lock=Et,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:ae()?this.storage=cn:(this.memoryStorage={},this.storage=St(this.memoryStorage)):(this.memoryStorage={},this.storage=St(this.memoryStorage)),C()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",n)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async n=>{this._debug("received broadcast notification from other tab or client",n),await this._notifyAllSubscribers(n.data.event,n.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${or}) ${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=C()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",t),t||this.detectSessionInUrl&&this._isImplicitGrantFlow()){const{data:r,error:i}=await this._getSessionFromURL(t);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Qi(i)){const a=(e=i.details)===null||e===void 0?void 0:e.code;if(a==="identity_already_exists"||a==="identity_not_found"||a==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:n,redirectType:o}=r;return this._debug("#_initialize()","detected session in URL",n,"redirect type",o),await this._saveSession(n),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return v(t)?{error:t}:{error:new hr("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,i;try{const n=await b(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e==null?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}},xform:M}),{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(n){if(v(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,r,i;try{let n;if("email"in e){const{email:c,password:d,options:f}=e;let g=null,_=null;this.flowType==="pkce"&&([g,_]=await Q(this.storage,this.storageKey)),n=await b(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:c,password:d,data:(t=f==null?void 0:f.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:g,code_challenge_method:_},xform:M})}else if("phone"in e){const{phone:c,password:d,options:f}=e;n=await b(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},channel:(i=f==null?void 0:f.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:M})}else throw new ve("You must provide either an email or phone number and a password");const{data:o,error:a}=n;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,h=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(n){if(v(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){const{email:n,password:o,options:a}=e;t=await b(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Tt})}else if("phone"in e){const{phone:n,password:o,options:a}=e;t=await b(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Tt})}else throw new ve("You must provide either an email or phone number and a password");const{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new ze}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(t){if(v(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,n;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(n=e.options)===null||n===void 0?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){const t=await _e(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(t??"").split("/");try{const{data:n,error:o}=await b(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:M});if(await me(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!n||!n.session||!n.user?{data:{user:null,session:null,redirectType:null},error:new ze}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign(Object.assign({},n),{redirectType:i??null}),error:o})}catch(n){if(v(n))return{data:{user:null,session:null,redirectType:null},error:n};throw n}}async signInWithIdToken(e){try{const{options:t,provider:r,token:i,access_token:n,nonce:o}=e,a=await b(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:n,nonce:o,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:M}),{data:l,error:h}=a;return h?{data:{user:null,session:null},error:h}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new ze}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:h})}catch(t){if(v(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,n,o;try{if("email"in e){const{email:a,options:l}=e;let h=null,c=null;this.flowType==="pkce"&&([h,c]=await Q(this.storage,this.storageKey));const{error:d}=await b(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l==null?void 0:l.data)!==null&&t!==void 0?t:{},create_user:(r=l==null?void 0:l.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:h,code_challenge_method:c},redirectTo:l==null?void 0:l.emailRedirectTo});return{data:{user:null,session:null},error:d}}if("phone"in e){const{phone:a,options:l}=e,{data:h,error:c}=await b(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l==null?void 0:l.data)!==null&&i!==void 0?i:{},create_user:(n=l==null?void 0:l.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(o=l==null?void 0:l.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:h==null?void 0:h.message_id},error:c}}throw new ve("You must provide either an email or phone number.")}catch(a){if(v(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{let i,n;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,n=(r=e.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:a}=await b(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:i,xform:M});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,h=o.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:h,session:l},error:null}}catch(i){if(v(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{let n=null,o=null;return this.flowType==="pkce"&&([n,o]=await Q(this.storage,this.storageKey)),await b(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:o}),headers:this.headers,xform:rn})}catch(n){if(v(n))return{data:null,error:n};throw n}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new N;const{error:i}=await b(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(v(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:r,type:i,options:n}=e,{error:o}=await b(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},redirectTo:n==null?void 0:n.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){const{phone:r,type:i,options:n}=e,{data:o,error:a}=await b(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}}});return{data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:a}}throw new ve("You must provide either an email or phone number and a type")}catch(t){if(v(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 r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{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 _e(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let o=this.suppressGetSessionWarning;e=new Proxy(e,{get:(l,h,c)=>(!o&&h==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and 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,h,c))})}return{data:{session:e},error:null}}const{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await b(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:B}):await this._useSession(async t=>{var r,i,n;const{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new N}:await b(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(n=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&n!==void 0?n:void 0,xform:B})})}catch(t){if(v(t))return Yi(t)&&(await this._removeSession(),await me(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 r=>{const{data:i,error:n}=r;if(n)throw n;if(!i.session)throw new N;const o=i.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Q(this.storage,this.storageKey));const{data:h,error:c}=await b(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:B});if(c)throw c;return o.user=h.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(v(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return wt(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new N;const t=Date.now()/1e3;let r=t,i=!0,n=null;const o=wt(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){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};n=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;n={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(v(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(e!=null&&e.refresh_token))throw new N;const{session:i,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(v(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!C())throw new ye("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new ye("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new kt("Not a valid PKCE flow url.");const t=Be(window.location.href);if(e){if(!t.code)throw new kt("No code detected.");const{data:D,error:I}=await this._exchangeCodeForSession(t.code);if(I)throw I;const $=new URL(window.location.href);return $.searchParams.delete("code"),window.history.replaceState(window.history.state,"",$.toString()),{data:{session:D.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new ye(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});const{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:h}=t;if(!n||!a||!o||!h)throw new ye("No session defined in URL");const c=Math.round(Date.now()/1e3),d=parseInt(a);let f=c+d;l&&(f=parseInt(l));const g=f-c;g*1e3<=ie&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${d}s`);const _=f-d;c-_>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",_,f,c):c-_<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",_,f,c);const{data:m,error:p}=await this._getUser(n);if(p)throw p;const w={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:d,expires_at:f,refresh_token:o,token_type:h,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:w,redirectType:t.type},error:null}}catch(t){if(v(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){const e=Be(window.location.href);return!!(C()&&(e.access_token||e.error_description))}async _isPKCEFlow(){const e=Be(window.location.href),t=await _e(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:i,error:n}=t;if(n)return{error:n};const o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!(Wi(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await me(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t=Di(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{const{data:{session:n},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(n){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n),console.error(n)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await Q(this.storage,this.storageKey,!0));try{return await b(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(v(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(v(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{const{data:r,error:i}=await this._useSession(async n=>{var o,a,l,h,c;const{data:d,error:f}=n;if(f)throw f;const g=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 b(this.fetch,"GET",g,{headers:this.headers,jwt:(c=(h=d.session)===null||h===void 0?void 0:h.access_token)!==null&&c!==void 0?c:void 0})});if(i)throw i;return C()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),{data:{provider:e.provider,url:r==null?void 0:r.url},error:null}}catch(r){if(v(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,i;const{data:n,error:o}=t;if(o)throw o;return await b(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(t){if(v(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const r=Date.now();return await Fi(async i=>(i>0&&await Mi(200*Math.pow(2,i-1)),this._debug(t,"refreshing attempt",i),await b(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:M})),(i,n)=>{const o=200*Math.pow(2,i);return n&&qe(n)&&Date.now()+o-r<ie})}catch(r){if(this._debug(t,"error",r),v(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),C()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;const t="#_recoverAndRefresh()";this._debug(t,"begin");try{const r=await _e(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}const i=Math.round(Date.now()/1e3),n=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<i+bt;if(this._debug(t,`session has${n?"":" not"} expired with margin of ${bt}s`),n){if(this.autoRefreshToken&&r.refresh_token){const{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),qe(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new N;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Ue;const{data:n,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!n.session)throw new N;await this._saveSession(n.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",n.session);const a={session:n.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(n){if(this._debug(i,"error",n),v(n)){const o={session:null,error:n};return qe(n)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(n),n}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){const i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const n=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){n.push(l)}});if(await Promise.all(o),n.length>0){for(let a=0;a<n.length;a+=1)console.error(n[a]);throw n[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await cr(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await me(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&C()&&(window!=null&&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(),ie);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((r.expires_at*1e3-e)/ie);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${ie}ms, refresh threshold is ${Pt} ticks`),i<=Pt&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof ur)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!C()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const i=[`provider=${encodeURIComponent(t)}`];if(r!=null&&r.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[n,o]=await Q(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(n)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(r!=null&&r.queryParams){const n=new URLSearchParams(r.queryParams);i.push(n.toString())}return r!=null&&r.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:i,error:n}=t;return n?{data:null,error:n}:await b(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(v(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;const{data:n,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:h}=await b(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(r=n==null?void 0:n.session)===null||r===void 0?void 0:r.access_token});return h?{data:null,error:h}:(e.factorType==="totp"&&(!((i=l==null?void 0:l.totp)===null||i===void 0)&&i.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),{data:l,error:null})})}catch(t){if(v(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:i,error:n}=t;if(n)return{data:null,error:n};const{data:o,error:a}=await b(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(v(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:i,error:n}=t;return n?{data:null,error:n}:await b(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(v(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){const{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};const r=(e==null?void 0:e.factors)||[],i=r.filter(o=>o.factor_type==="totp"&&o.status==="verified"),n=r.filter(o=>o.factor_type==="phone"&&o.status==="verified");return{data:{all:r,totp:i,phone:n},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;const{data:{session:i},error:n}=e;if(n)return{data:null,error:n};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const o=this._decodeJWT(i.access_token);let a=null;o.aal&&(a=o.aal);let l=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(d=>d.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(l="aal2");const c=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:c},error:null}}))}}he.nextInstanceID=0;const pn=he;class gn extends pn{constructor(e){super(e)}}var _n=globalThis&&globalThis.__awaiter||function(s,e,t,r){function i(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function a(c){try{h(r.next(c))}catch(d){o(d)}}function l(c){try{h(r.throw(c))}catch(d){o(d)}}function h(c){c.done?n(c.value):i(c.value).then(a,l)}h((r=r.apply(s,e||[])).next())})};class mn{constructor(e,t,r){var i,n,o;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");const a=$i(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`,h={db:ki,realtime:ji,auth:Object.assign(Object.assign({},xi),{storageKey:l}),global:wi},c=Ai(r??{},h);this.storageKey=(i=c.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken?(this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(d,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=c.auth)!==null&&o!==void 0?o:{},this.headers,c.global.fetch),this.fetch=Ei(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.rest=new qs(`${a}/rest/v1`,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),c.accessToken||this._listenForAuthEvents()}get functions(){return new ys(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new vi(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return _n(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:n,flowType:o,lock:a,debug:l},h,c){var d;const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new gn({url:this.authUrl,headers:Object.assign(Object.assign({},f),h),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,lock:a,debug:l,fetch:c,hasCustomAuthorizationHeader:(d="Authorization"in this.headers)!==null&&d!==void 0?d:!1})}_initRealtimeClient(e){return new ii(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r==null?void 0:r.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?this.changedAccessToken=r:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const vn=(s,e,t)=>new mn(s,e,t);let Je=null;const yn=()=>(Je||(Je=vn("https://base.uppmkt.com","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJzZXJ2aWNlX3JvbGUiLAogICAgImlzcyI6ICJzdXBhYmFzZS1kZW1vIiwKICAgICJpYXQiOiAxNjQxNzY5MjAwLAogICAgImV4cCI6IDE3OTk1MzU2MDAKfQ.DaYlNEoUrrEn2Ig7tqibS-PHK5vgusbcbo7X36XVt4Q",{auth:{autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!1},db:{schema:"limq_dev"}})),Je),q=yn(),dr=y.createContext({}),bn=({children:s})=>{const[e,t]=br(),r=we(),i=tt(),[n,o]=y.useState(null),[a,l]=y.useState(!0);y.useEffect(()=>{const _=window.location.hash.substring(1),m=new URLSearchParams(_),p=m.get("access_token"),w=m.get("refresh_token");p&&w&&(async()=>await q.auth.setSession({access_token:p,refresh_token:w}))()},[r]),y.useEffect(()=>{(async()=>{try{const{data:{session:p},error:w}=await q.auth.getSession();o((p==null?void 0:p.user)??null)}catch(p){console.error("Error getting session:",p)}finally{l(!1)}})();const{data:{subscription:m}}=q.auth.onAuthStateChange((p,w)=>{o((w==null?void 0:w.user)??null)});return()=>{m==null||m.unsubscribe()}},[]);const g={user:n,loading:a,login:async(_,m)=>{try{l(!0);const{data:p,error:w}=await q.auth.signInWithPassword({email:_,password:m});if(w){L.error(w.message||"登录失败,请稍后重试");return}return o(p.user),p}catch(p){L.error(p.message||"登录失败,请稍后重试")}finally{l(!1)}},logout:async()=>{try{l(!0);const{error:_}=await q.auth.signOut({scope:"local"});if(_){L.error(_.message||"登出失败,请稍后重试");return}o(null),L.success("已成功登出"),r(`/login?redirectTo=${i.pathname}`,{replace:!0})}catch(_){L.error(_.message||"登出失败,请稍后重试")}finally{l(!1)}},register:async(_,m)=>{try{l(!0);const{data:p,error:w}=await q.auth.signUp({email:_,password:m,options:{emailRedirectTo:`${window.location.origin}/auth/callback`}});if(w)throw w;return L.success("注册成功!请查收验证邮件。"),p}catch(p){throw L.error(p.message||"注册失败"),p}finally{l(!1)}},signInWithGoogle:async()=>{try{l(!0);const _=e.get("redirectTo"),{data:m,error:p}=await q.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/login?redirectTo=${_??""}`}});if(p){L.error(p.message||"Google 登录失败,请稍后重试");return}return m}catch(_){L.error(_.message||"Google 登录失败,请稍后重试")}finally{l(!1)}}};return u.jsx(dr.Provider,{value:g,children:s})},Ne=()=>y.useContext(dr),wn=({collapsed:s,setCollapsed:e,isDarkMode:t})=>{const r=s?wr:kr;return u.jsx(r,{className:"trigger",onClick:()=>e(!s),style:{fontSize:"18px",padding:"0 24px",cursor:"pointer",color:t?"#fff":"#000"}})},{Header:kn}=ce,xn=({collapsed:s,setCollapsed:e})=>{const{isDarkMode:t,toggleTheme:r}=fe(),{user:i,logout:n}=Ne(),o=async()=>{try{await n()}catch(l){console.error("Logout error:",l)}},a=[{key:"profile",icon:u.jsx(lt,{}),label:"个人信息"},{key:"logout",icon:u.jsx(Tr,{}),label:"退出登录",onClick:o}];return u.jsxs(kn,{style:{padding:0,background:t?"#141414":"#fff",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[u.jsx("div",{className:"flex items-center",children:u.jsx(wn,{collapsed:s,setCollapsed:e,isDarkMode:t})}),u.jsxs("div",{className:"flex items-center gap-4 mr-6",children:[u.jsx(xr,{checked:t,onChange:r,checkedChildren:"🌙",unCheckedChildren:"☀️"}),u.jsx(jr,{menu:{items:a},placement:"bottomRight",trigger:["click"],children:u.jsx(le,{type:"text",icon:u.jsx(lt,{}),className:"flex items-center",children:i==null?void 0:i.email})})]})]})},jn={path:"dashboard",component:y.lazy(()=>x(()=>Promise.resolve().then(()=>Jn),void 0)),name:"仪表盘",icon:"dashboard"},Tn=[{path:"team",component:y.lazy(()=>x(()=>import("./index-be5fed8f.js"),["assets/index-be5fed8f.js","assets/vendor-61f0f29a.js"])),name:"团队管理",icon:"team"},{path:"bucket",component:y.lazy(()=>x(()=>import("./index-5f9ef69d.js"),["assets/index-5f9ef69d.js","assets/vendor-61f0f29a.js"])),name:"对象存储",icon:"shop"},{path:"task",component:y.lazy(()=>x(()=>import("./index-b33c2304.js"),["assets/index-b33c2304.js","assets/vendor-61f0f29a.js","assets/useResource-9c541112.js"])),name:"任务管理",icon:"appstore"},{path:"task/edit/:id?",component:y.lazy(()=>x(()=>import("./index-fd856c91.js"),["assets/index-fd856c91.js","assets/vendor-61f0f29a.js","assets/v4-82fce61c.js"])),hidden:!0,name:"新增/编辑任务"}],Sn=[{path:"quotation",component:y.lazy(()=>x(()=>import("./index-7a916509.js"),["assets/index-7a916509.js","assets/vendor-61f0f29a.js","assets/useResource-9c541112.js"])),name:"报价单",icon:"file"},{path:"quotaInfo/:id?",hidden:!0,component:y.lazy(()=>x(()=>import("./index-4a46251b.js"),["assets/index-4a46251b.js","assets/vendor-61f0f29a.js","assets/v4-82fce61c.js"])),name:"报价单详情",icon:"file"},{path:"serviceTeamplate",component:y.lazy(()=>x(()=>import("./index-8c177bec.js"),["assets/index-8c177bec.js","assets/vendor-61f0f29a.js"])),name:"服务管理",icon:"container"},{path:"serviceType",hidden:!0,component:y.lazy(()=>x(()=>import("./index-c535d235.js"),["assets/index-c535d235.js","assets/vendor-61f0f29a.js"])),name:"类型管理",icon:"container"},{path:"serviceTemplateInfo/:id?",hidden:!0,component:y.lazy(()=>x(()=>import("./index-2eaa6d56.js"),["assets/index-2eaa6d56.js","assets/vendor-61f0f29a.js"])),name:"服务模版详情",icon:"container"},{path:"quotaInfo/preview/:id?",hidden:!0,component:y.lazy(()=>x(()=>import("./index-230be5c6.js"),["assets/index-230be5c6.js","assets/vendor-61f0f29a.js"])),name:"报价单预览",icon:"file"},{path:"customer",component:y.lazy(()=>x(()=>import("./index-727cea98.js"),["assets/index-727cea98.js","assets/vendor-61f0f29a.js","assets/useResource-9c541112.js"])),name:"客户管理",icon:"user"},{path:"customerInfo/:id?",hidden:!0,component:y.lazy(()=>x(()=>import("./index-79bccede.js"),["assets/index-79bccede.js","assets/vendor-61f0f29a.js"])),name:"客户详情",icon:"user"},{path:"supplier",component:y.lazy(()=>x(()=>import("./index-71676cce.js"),["assets/index-71676cce.js","assets/vendor-61f0f29a.js","assets/useResource-9c541112.js"])),name:"供应商管理",icon:"branches"},{path:"supplierInfo/:id?",hidden:!0,component:y.lazy(()=>x(()=>import("./index-b415efab.js"),["assets/index-b415efab.js","assets/vendor-61f0f29a.js"])),name:"供应商详情",icon:"branches"}],Pn=[],fr=[jn,{path:"resource",component:y.lazy(()=>x(()=>import("./index-414b499d.js"),["assets/index-414b499d.js","assets/vendor-61f0f29a.js"])),name:"资源管理",icon:"appstore",children:Tn},{path:"company",component:y.lazy(()=>x(()=>import("./index-ad6cc26e.js"),["assets/index-ad6cc26e.js","assets/vendor-61f0f29a.js"])),name:"公司管理",icon:"bank",children:Sn},{path:"marketing",component:y.lazy(()=>x(()=>import("./index-ab4c34a5.js"),["assets/index-ab4c34a5.js","assets/vendor-61f0f29a.js"])),name:"行销中心",icon:"shopping",children:Pn}],En=({icon:s,background:e})=>{const{isDarkMode:t}=fe();return u.jsx("div",{className:`
inline-flex items-center justify-center
w-8 h-8 rounded-lg transition-all duration-300
${t?"bg-opacity-25":"bg-opacity-15"}
hover:${t?"bg-opacity-35":"bg-opacity-25"}
`,style:{backgroundColor:e},children:u.jsx("span",{className:"text-base transition-colors duration-300",style:{color:e},children:s})})},On=s=>{const e=`${s.charAt(0).toUpperCase()}${s.slice(1)}Outlined`;return ct[e]?ke.createElement(ct[e]):null},pr=(s,e="")=>s.filter(t=>!t.hidden).map(t=>{const r=`${e}/${t.path}`.replace(/\/+/g,"/"),i=t.icon&&u.jsx(En,{icon:On(t.icon)}),n={key:r,icon:i,label:t.name};return t.children&&(n.children=pr(t.children,r)),n}),$n=()=>pr(fr),An=({collapsed:s,isDarkMode:e})=>u.jsx("div",{className:"logo",children:u.jsxs("div",{className:"flex items-center justify-center gap-2",children:[u.jsx("span",{className:"material-symbols-rounded text-primary-500",children:"rocket_launch"}),u.jsx("h1",{style:{color:e?"#fff":"#000",fontSize:s?"14px":"18px",margin:0,display:s?"none":"block"},children:"Uppeta"})]})}),{Sider:Cn}=ce,Rn=({collapsed:s})=>{const e=we(),t=tt(),{isDarkMode:r}=fe(),i=y.useMemo(()=>$n(),[]),n=y.useMemo(()=>{const a=t.pathname.split("/").filter(Boolean);return a.reduce((l,h,c)=>{const d=`/${a.slice(0,c+1).join("/")}`;return l.push(d),l},[])},[t.pathname]),o=({key:a})=>{e(a)};return u.jsxs(Cn,{trigger:null,collapsible:!0,collapsed:s,theme:r?"dark":"light",width:256,collapsedWidth:80,className:`app-sidebar ${s?"collapsed":""}`,children:[u.jsx(An,{collapsed:s,isDarkMode:r}),u.jsx(Sr,{theme:r?"dark":"light",mode:"inline",selectedKeys:[t.pathname],defaultOpenKeys:n,items:i,onClick:o})]})},In=ke.memo(Rn),{Content:Ln}=ce,Dn=()=>{const[s,e]=y.useState(!1),{isDarkMode:t}=fe();return u.jsxs(ce,{className:"min-h-screen",children:[u.jsx(In,{collapsed:s}),u.jsxs(ce,{className:"flex flex-col h-screen",children:[u.jsx(xn,{collapsed:s,setCollapsed:e}),u.jsx(Ln,{className:`
m-2 p-4 rounded-lg overflow-auto
${t?"bg-[#141414]":"bg-white"}
flex-1
`,children:u.jsx(y.Suspense,{fallback:u.jsx("div",{className:"flex items-center justify-center h-full",children:u.jsx(rt,{size:"large"})}),children:u.jsx(Pr,{})})})]})]})},Un=()=>{const s=we(),{login:e,signInWithGoogle:t,loading:r}=Ne(),[i]=W.useForm(),n=async a=>{try{await e(a.email,a.password),L.success("登录成功!"),s("/")}catch(l){console.error("Login error:",l)}},o=async()=>{try{await t()}catch(a){console.error("Google login error:",a)}};return u.jsx("div",{className:"min-h-screen flex bg-gradient-to-br from-[#f5f7fa] to-[#c3cfe2]",children:u.jsxs("div",{className:"w-full max-w-[1200px] mx-auto flex p-8 gap-16",children:[u.jsxs("div",{className:"flex-1 bg-white p-12 rounded-[20px] shadow-[0_10px_30px_rgba(0,0,0,0.1)]",children:[u.jsxs("div",{className:"mb-8 text-center",children:[u.jsx("h1",{className:"text-3xl font-bold mb-2 bg-gradient-to-r from-primary-500 to-[#36cff0] bg-clip-text text-transparent",children:"Uppeta"}),u.jsx("p",{className:"text-gray-500",children:"欢迎回来!请登录您的账户。"})]}),u.jsxs(W,{form:i,name:"login",onFinish:n,layout:"vertical",size:"large",children:[u.jsx(W.Item,{name:"email",rules:[{required:!0,message:"请输入邮箱!"},{type:"email",message:"请输入有效的邮箱地址!"}],children:u.jsx(ht,{placeholder:"邮箱"})}),u.jsx(W.Item,{name:"password",rules:[{required:!0,message:"请输入密码!"}],children:u.jsx(ht.Password,{placeholder:"密码"})}),u.jsx("div",{className:"flex justify-between items-center mb-6",children:u.jsx(W.Item,{name:"remember",valuePropName:"checked",noStyle:!0,children:u.jsx(Er,{to:"/forgot-password",className:"text-primary-500 hover:text-primary-600",children:"忘记密码?"})})}),u.jsx(W.Item,{children:u.jsx(le,{type:"primary",htmlType:"submit",block:!0,children:"登录"})}),u.jsx(Or,{children:"或"}),u.jsx(le,{icon:u.jsx($r,{}),block:!0,onClick:o,className:"mb-6",loading:r,children:"使用 Google 账号登录"})]})]}),u.jsx("div",{className:"flex-1 hidden md:block rounded-[20px] bg-[url('https://uppeta.com/img/svg/main.svg')] bg-center bg-contain bg-no-repeat"})]})})},Nn=()=>{const s=we();return u.jsx("div",{className:"h-screen flex items-center justify-center bg-gray-50",children:u.jsx(Ar,{status:"404",title:"404",subTitle:"抱歉,您访问的页面不存在。",extra:[u.jsx(le,{type:"primary",onClick:()=>s("/dashboard"),children:"返回首页"},"home"),u.jsx(le,{onClick:()=>s(-1),children:"返回上一页"},"back")]})})},Mn=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(s),Fn=({icon:s,title:e,count:t,amount:r,color:i="#1677ff"})=>u.jsx("div",{className:"flex-1",children:u.jsx(Ot,{styles:{body:{padding:"20px",height:"100%",background:"var(--color-bg-container)"}},className:"h-full hover:shadow-md transition-shadow duration-300",children:u.jsxs("div",{className:"flex items-start gap-4",children:[u.jsx("div",{className:"w-12 h-12 rounded-full flex items-center justify-center text-lg",style:{backgroundColor:`${i}15`},children:u.jsx("span",{style:{color:i},children:s})}),u.jsxs("div",{className:"flex-1",children:[u.jsx("h3",{className:"text-base text-gray-500 dark:text-gray-400 m-0",children:e}),u.jsxs("div",{className:"text-sm text-gray-400 dark:text-gray-500 mt-1",children:[t," invoices"]}),u.jsx("div",{className:"text-xl font-semibold mt-2 dark:text-white",children:Mn(r)})]})]})})}),Bn=[{icon:u.jsx(Cr,{className:"text-lg"}),title:"Total",count:20,amount:46218.04,color:"#1677ff"},{icon:u.jsx(Rr,{className:"text-lg"}),title:"Paid",count:10,amount:23110.23,color:"#52c41a"},{icon:u.jsx(Ir,{className:"text-lg"}),title:"Pending",count:6,amount:13825.05,color:"#faad14"},{icon:u.jsx(Lr,{className:"text-lg"}),title:"Overdue",count:2,amount:4655.63,color:"#ff4d4f"},{icon:u.jsx(Dr,{className:"text-lg"}),title:"Draft",count:2,amount:4627.13,color:"#8c8c8c"}],zn=()=>u.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4",children:Bn.map((s,e)=>u.jsx(Fn,{...s},e))}),qn=ke.memo(zn),gr=()=>u.jsx("div",{className:"space-y-6",children:u.jsx(Ot,{title:"Statistics Overview",bordered:!1,styles:{body:{padding:"24px"}},children:u.jsx(qn,{})})}),Jn=Object.freeze(Object.defineProperty({__proto__:null,default:gr},Symbol.toStringTag,{value:"Module"})),Vn=({children:s})=>{const{user:e,loading:t}=Ne();return tt(),t?u.jsx("div",{className:"min-h-screen flex items-center justify-center",children:u.jsx(rt,{size:"large"})}):e?s:u.jsx(Ve,{to:"/login",replace:!0})},et=()=>u.jsx("div",{className:"flex justify-center items-center min-h-[200px]",children:u.jsx(rt,{size:"large"})}),_r=s=>s.map(e=>{const t=e.component;return e.children?u.jsx(V,{path:e.path,element:u.jsx(y.Suspense,{fallback:u.jsx(et,{}),children:u.jsx(t,{})}),children:_r(e.children)},e.path):u.jsx(V,{path:e.path,element:u.jsx(y.Suspense,{fallback:u.jsx(et,{}),children:u.jsx(t,{})})},e.path)}),Gn=()=>{const{user:s}=Ne();return u.jsxs(Ur,{children:[u.jsx(V,{path:"/login",element:s?u.jsx(Ve,{to:"/dashboard",replace:!0}):u.jsx(Un,{})}),u.jsxs(V,{path:"/",element:u.jsx(Vn,{children:u.jsx(Dn,{})}),children:[u.jsx(V,{path:"dashboard",element:u.jsx(y.Suspense,{fallback:u.jsx(et,{}),children:u.jsx(gr,{})})}),_r(fr),u.jsx(V,{index:!0,element:u.jsx(Ve,{to:"/dashboard",replace:!0})}),u.jsx(V,{path:"*",element:u.jsx(Nn,{})})]})]})},Kn=y.createContext({}),Hn=({children:s})=>u.jsx(Kn.Provider,{value:{},children:s}),Wn=()=>{const{isDarkMode:s}=fe();return u.jsx($t,{theme:{algorithm:s?ut.darkAlgorithm:ut.defaultAlgorithm,token:{colorPrimary:"#1677ff",borderRadius:4,colorBgContainer:s?"#141414":"#ffffff",colorBgElevated:s?"#1f1f1f":"#ffffff",colorText:s?"rgba(255, 255, 255, 0.85)":"rgba(0, 0, 0, 0.85)",colorTextSecondary:s?"rgba(255, 255, 255, 0.45)":"rgba(0, 0, 0, 0.45)"},components:{Form:{variant:"filled"},Input:{variant:"filled"},Select:{variant:"filled"},TreeSelect:{variant:"filled"},DatePicker:{variant:"filled"},TimePicker:{variant:"filled"},Cascader:{variant:"filled"},AutoComplete:{variant:"filled"}}},children:u.jsx("div",{className:s?"dark":"",children:u.jsx(Gn,{})})})},Yn=()=>u.jsx(Nr,{children:u.jsx(bn,{children:u.jsx(Hn,{children:u.jsx(us,{children:u.jsx(Wn,{})})})})});Ge.createRoot(document.getElementById("root")).render(u.jsx(ke.StrictMode,{children:u.jsx($t,{locale:hs,children:u.jsx(Yn,{})})}));export{x as _,u as j,q as s,Ne as u};
//# sourceMappingURL=index-3808da28.js.map