import{j as e,Q as t,U as s,W as r,X as n,Y as i,Z as a,_ as o,$ as l,a0 as c,a1 as d,a2 as u,a3 as h,a4 as f,a5 as p,a6 as m,a7 as g,a8 as y,a9 as v,aa as b,ab as _,a as w,u as k,P as x,f as j,d as S,t as T,v as E,q as O,r as A,b as C,s as N,I as R,ac as I,ad as P,ae as $}from"./ui-vendor-Dyu0xMC9.js";import{r as D,R as U,k as L,L as V}from"./react-vendor-BiKEbLqf.js";import{B as F}from"./button-iayXQ_q_.js";import{L as B,I as q,a as M}from"./label-Cl_UshjE.js";import{d as z,c as W,X as Z,D as K,_ as J,n as H,o as G,E as Y,F as Q,t as X,G as ee,u as te}from"./index-CxSR60Bh.js";import{b as se,a as re,C as ne}from"./chevron-right-LutMVzxT.js";function ie(e,t){for(var s=0;s<t.length;s++){const r=t[s];if("string"!=typeof r&&!Array.isArray(r))for(const t in r)if("default"!==t&&!(t in e)){const s=Object.getOwnPropertyDescriptor(r,t);s&&Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>r[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}
/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ae=z("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]),oe=z("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),le=z("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),ce=z("Github",[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]]),de=z("Linkedin",[["path",{d:"M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z",key:"c2jq9f"}],["rect",{width:"4",height:"12",x:"2",y:"9",key:"mk3on5"}],["circle",{cx:"4",cy:"4",r:"2",key:"bt5ra8"}]]),ue=z("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),he=z("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]),fe=z("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]),pe=z("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]),me=z("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]),ge=z("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]),ye=z("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]),ve=z("Twitter",[["path",{d:"M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z",key:"pff0z6"}]]),be=z("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]),_e=a,we=o,ke=l,xe=D.forwardRef(({className:s,...r},n)=>e.jsx(t,{className:W("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...r,ref:n}));
/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */xe.displayName=t.displayName;const je=K("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4  border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),Se=D.forwardRef(({side:t="right",className:n,children:i,...a},o)=>e.jsxs(ke,{children:[e.jsx(xe,{}),e.jsxs(s,{ref:o,className:W(je({side:t}),n),...a,children:[i,e.jsxs(r,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-secondary hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[e.jsx(Z,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Se.displayName=s.displayName;D.forwardRef(({className:t,...s},r)=>e.jsx(n,{ref:r,className:W("text-lg font-semibold text-foreground",t),...s})).displayName=n.displayName;D.forwardRef(({className:t,...s},r)=>e.jsx(i,{ref:r,className:W("text-sm text-muted-foreground",t),...s})).displayName=i.displayName;const Te=b,Ee=_;D.forwardRef(({className:t,inset:s,children:r,...n},i)=>e.jsxs(c,{ref:i,className:W("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent focus:bg-accent",s&&"pl-8",t),...n,children:[r,e.jsx(se,{className:"ml-auto h-4 w-4"})]})).displayName=c.displayName;D.forwardRef(({className:t,...s},r)=>e.jsx(d,{ref:r,className:W("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...s})).displayName=d.displayName;const Oe=D.forwardRef(({className:t,sideOffset:s=4,...r},n)=>e.jsx(u,{children:e.jsx(h,{ref:n,sideOffset:s,className:W("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...r})}));Oe.displayName=h.displayName;const Ae=D.forwardRef(({className:t,inset:s,...r},n)=>e.jsx(f,{ref:n,className:W("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",s&&"pl-8",t),...r}));Ae.displayName=f.displayName;D.forwardRef(({className:t,children:s,checked:r,...n},i)=>e.jsxs(p,{ref:i,className:W("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t),checked:r,...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(m,{children:e.jsx(ae,{className:"h-4 w-4"})})}),s]})).displayName=p.displayName;D.forwardRef(({className:t,children:s,...r},n)=>e.jsxs(g,{ref:n,className:W("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t),...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(m,{children:e.jsx(le,{className:"h-2 w-2 fill-current"})})}),s]})).displayName=g.displayName;D.forwardRef(({className:t,inset:s,...r},n)=>e.jsx(y,{ref:n,className:W("px-2 py-1.5 text-sm font-semibold",s&&"pl-8",t),...r})).displayName=y.displayName;D.forwardRef(({className:t,...s},r)=>e.jsx(v,{ref:r,className:W("-mx-1 my-1 h-px bg-muted",t),...s})).displayName=v.displayName;var Ce=e=>"checkbox"===e.type,Ne=e=>e instanceof Date,Re=e=>null==e;const Ie=e=>"object"==typeof e;var Pe=e=>!Re(e)&&!Array.isArray(e)&&Ie(e)&&!Ne(e),$e="undefined"!=typeof window&&void 0!==window.HTMLElement&&"undefined"!=typeof document;function De(e){let t;const s=Array.isArray(e),r="undefined"!=typeof FileList&&e instanceof FileList;if(e instanceof Date)t=new Date(e);else{if($e&&(e instanceof Blob||r)||!s&&!Pe(e))return e;if(t=s?[]:{},s||(e=>{const t=e.constructor&&e.constructor.prototype;return Pe(t)&&t.hasOwnProperty("isPrototypeOf")})(e))for(const s in e)e.hasOwnProperty(s)&&(t[s]=De(e[s]));else t=e}return t}var Ue=e=>/^\w*$/.test(e),Le=e=>void 0===e,Ve=e=>Array.isArray(e)?e.filter(Boolean):[],Fe=e=>Ve(e.replace(/["|']|\]/g,"").split(/\.|\[/)),Be=(e,t,s)=>{if(!t||!Pe(e))return s;const r=(Ue(t)?[t]:Fe(t)).reduce((e,t)=>Re(e)?e:e[t],e);return Le(r)||r===e?Le(e[t])?s:e[t]:r},qe=e=>"boolean"==typeof e,Me=(e,t,s)=>{let r=-1;const n=Ue(t)?[t]:Fe(t),i=n.length,a=i-1;for(;++r<i;){const t=n[r];let i=s;if(r!==a){const s=e[t];i=Pe(s)||Array.isArray(s)?s:isNaN(+n[r+1])?{}:[]}if("__proto__"===t||"constructor"===t||"prototype"===t)return;e[t]=i,e=e[t]}};const ze="blur",We="focusout",Ze="onBlur",Ke="onChange",Je="onSubmit",He="onTouched",Ge="all",Ye="max",Qe="min",Xe="maxLength",et="minLength",tt="pattern",st="required",rt="validate";U.createContext(null).displayName="HookFormContext";const nt="undefined"!=typeof window?U.useLayoutEffect:U.useEffect;var it=e=>"string"==typeof e,at=e=>Re(e)||!Ie(e);function ot(e,t,s=new WeakSet){if(at(e)||at(t))return e===t;if(Ne(e)&&Ne(t))return e.getTime()===t.getTime();const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;if(s.has(e)||s.has(t))return!0;s.add(e),s.add(t);for(const i of r){const r=e[i];if(!n.includes(i))return!1;if("ref"!==i){const e=t[i];if(Ne(r)&&Ne(e)||Pe(r)&&Pe(e)||Array.isArray(r)&&Array.isArray(e)?!ot(r,e,s):r!==e)return!1}}return!0}var lt=(e,t,s,r,n)=>t?{...s[e],types:{...s[e]&&s[e].types?s[e].types:{},[r]:n||!0}}:{},ct=e=>Array.isArray(e)?e:[e],dt=()=>{let e=[];return{get observers(){return e},next:t=>{for(const s of e)s.next&&s.next(t)},subscribe:t=>(e.push(t),{unsubscribe:()=>{e=e.filter(e=>e!==t)}}),unsubscribe:()=>{e=[]}}},ut=e=>Pe(e)&&!Object.keys(e).length,ht=e=>"file"===e.type,ft=e=>"function"==typeof e,pt=e=>{if(!$e)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},mt=e=>"select-multiple"===e.type,gt=e=>"radio"===e.type,yt=e=>pt(e)&&e.isConnected;function vt(e,t){const s=Array.isArray(t)?t:Ue(t)?[t]:Fe(t),r=1===s.length?e:function(e,t){const s=t.slice(0,-1).length;let r=0;for(;r<s;)e=Le(e)?r++:e[t[r++]];return e}(e,s),n=s.length-1,i=s[n];return r&&delete r[i],0!==n&&(Pe(r)&&ut(r)||Array.isArray(r)&&function(e){for(const t in e)if(e.hasOwnProperty(t)&&!Le(e[t]))return!1;return!0}(r))&&vt(e,s.slice(0,-1)),e}var bt=e=>{for(const t in e)if(ft(e[t]))return!0;return!1};function _t(e,t={}){const s=Array.isArray(e);if(Pe(e)||s)for(const r in e)Array.isArray(e[r])||Pe(e[r])&&!bt(e[r])?(t[r]=Array.isArray(e[r])?[]:{},_t(e[r],t[r])):Re(e[r])||(t[r]=!0);return t}function wt(e,t,s){const r=Array.isArray(e);if(Pe(e)||r)for(const n in e)Array.isArray(e[n])||Pe(e[n])&&!bt(e[n])?Le(t)||at(s[n])?s[n]=Array.isArray(e[n])?_t(e[n],[]):{..._t(e[n])}:wt(e[n],Re(t)?{}:t[n],s[n]):s[n]=!ot(e[n],t[n]);return s}var kt=(e,t)=>wt(e,t,_t(t));const xt={value:!1,isValid:!1},jt={value:!0,isValid:!0};var St=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(e=>e&&e.checked&&!e.disabled).map(e=>e.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Le(e[0].attributes.value)?Le(e[0].value)||""===e[0].value?jt:{value:e[0].value,isValid:!0}:jt:xt}return xt},Tt=(e,{valueAsNumber:t,valueAsDate:s,setValueAs:r})=>Le(e)?e:t?""===e?NaN:e?+e:e:s&&it(e)?new Date(e):r?r(e):e;const Et={isValid:!1,value:null};var Ot=e=>Array.isArray(e)?e.reduce((e,t)=>t&&t.checked&&!t.disabled?{isValid:!0,value:t.value}:e,Et):Et;function At(e){const t=e.ref;return ht(t)?t.files:gt(t)?Ot(e.refs).value:mt(t)?[...t.selectedOptions].map(({value:e})=>e):Ce(t)?St(e.refs).value:Tt(Le(t.value)?e.ref.value:t.value,e)}var Ct=e=>e instanceof RegExp,Nt=e=>Le(e)?e:Ct(e)?e.source:Pe(e)?Ct(e.value)?e.value.source:e.value:e,Rt=e=>({isOnSubmit:!e||e===Je,isOnBlur:e===Ze,isOnChange:e===Ke,isOnAll:e===Ge,isOnTouch:e===He});const It="AsyncFunction";var Pt=e=>!!e&&!!e.validate&&!!(ft(e.validate)&&e.validate.constructor.name===It||Pe(e.validate)&&Object.values(e.validate).find(e=>e.constructor.name===It)),$t=(e,t,s)=>!s&&(t.watchAll||t.watch.has(e)||[...t.watch].some(t=>e.startsWith(t)&&/^\.\w+/.test(e.slice(t.length))));const Dt=(e,t,s,r)=>{for(const n of s||Object.keys(e)){const s=Be(e,n);if(s){const{_f:e,...i}=s;if(e){if(e.refs&&e.refs[0]&&t(e.refs[0],n)&&!r)return!0;if(e.ref&&t(e.ref,e.name)&&!r)return!0;if(Dt(i,t))break}else if(Pe(i)&&Dt(i,t))break}}};function Ut(e,t,s){const r=Be(e,s);if(r||Ue(s))return{error:r,name:s};const n=s.split(".");for(;n.length;){const r=n.join("."),i=Be(t,r),a=Be(e,r);if(i&&!Array.isArray(i)&&s!==r)return{name:s};if(a&&a.type)return{name:r,error:a};if(a&&a.root&&a.root.type)return{name:`${r}.root`,error:a.root};n.pop()}return{name:s}}var Lt=(e,t,s)=>{const r=ct(Be(e,s));return Me(r,"root",t[s]),Me(e,s,r),e},Vt=e=>it(e);function Ft(e,t,s="validate"){if(Vt(e)||Array.isArray(e)&&e.every(Vt)||qe(e)&&!e)return{type:s,message:Vt(e)?e:"",ref:t}}var Bt=e=>Pe(e)&&!Ct(e)?e:{value:e,message:""},qt=async(e,t,s,r,n,i)=>{const{ref:a,refs:o,required:l,maxLength:c,minLength:d,min:u,max:h,pattern:f,validate:p,name:m,valueAsNumber:g,mount:y}=e._f,v=Be(s,m);if(!y||t.has(m))return{};const b=o?o[0]:a,_=e=>{n&&b.reportValidity&&(b.setCustomValidity(qe(e)?"":e||""),b.reportValidity())},w={},k=gt(a),x=Ce(a),j=k||x,S=(g||ht(a))&&Le(a.value)&&Le(v)||pt(a)&&""===a.value||""===v||Array.isArray(v)&&!v.length,T=lt.bind(null,m,r,w),E=(e,t,s,r=Xe,n=et)=>{const i=e?t:s;w[m]={type:e?r:n,message:i,ref:a,...T(e?r:n,i)}};if(i?!Array.isArray(v)||!v.length:l&&(!j&&(S||Re(v))||qe(v)&&!v||x&&!St(o).isValid||k&&!Ot(o).isValid)){const{value:e,message:t}=Vt(l)?{value:!!l,message:l}:Bt(l);if(e&&(w[m]={type:st,message:t,ref:b,...T(st,t)},!r))return _(t),w}if(!(S||Re(u)&&Re(h))){let e,t;const s=Bt(h),n=Bt(u);if(Re(v)||isNaN(v)){const r=a.valueAsDate||new Date(v),i=e=>new Date((new Date).toDateString()+" "+e),o="time"==a.type,l="week"==a.type;it(s.value)&&v&&(e=o?i(v)>i(s.value):l?v>s.value:r>new Date(s.value)),it(n.value)&&v&&(t=o?i(v)<i(n.value):l?v<n.value:r<new Date(n.value))}else{const r=a.valueAsNumber||(v?+v:v);Re(s.value)||(e=r>s.value),Re(n.value)||(t=r<n.value)}if((e||t)&&(E(!!e,s.message,n.message,Ye,Qe),!r))return _(w[m].message),w}if((c||d)&&!S&&(it(v)||i&&Array.isArray(v))){const e=Bt(c),t=Bt(d),s=!Re(e.value)&&v.length>+e.value,n=!Re(t.value)&&v.length<+t.value;if((s||n)&&(E(s,e.message,t.message),!r))return _(w[m].message),w}if(f&&!S&&it(v)){const{value:e,message:t}=Bt(f);if(Ct(e)&&!v.match(e)&&(w[m]={type:tt,message:t,ref:a,...T(tt,t)},!r))return _(t),w}if(p)if(ft(p)){const e=Ft(await p(v,s),b);if(e&&(w[m]={...e,...T(rt,e.message)},!r))return _(e.message),w}else if(Pe(p)){let e={};for(const t in p){if(!ut(e)&&!r)break;const n=Ft(await p[t](v,s),b,t);n&&(e={...n,...T(t,n.message)},_(n.message),r&&(w[m]=e))}if(!ut(e)&&(w[m]={ref:b,...e},!r))return w}return _(!0),w};const Mt={mode:Je,reValidateMode:Ke,shouldFocusError:!0};function zt(e={}){let t,s={...Mt,...e},r={submitCount:0,isDirty:!1,isReady:!1,isLoading:ft(s.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:s.errors||{},disabled:s.disabled||!1},n={},i=(Pe(s.defaultValues)||Pe(s.values))&&De(s.defaultValues||s.values)||{},a=s.shouldUnregister?{}:De(i),o={action:!1,mount:!1,watch:!1},l={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},c=0;const d={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let u={...d};const h={array:dt(),state:dt()},f=s.criteriaMode===Ge,p=async e=>{if(!s.disabled&&(d.isValid||u.isValid||e)){const e=s.resolver?ut((await b()).errors):await _(n,!0);e!==r.isValid&&h.state.next({isValid:e})}},m=(e,t)=>{!s.disabled&&(d.isValidating||d.validatingFields||u.isValidating||u.validatingFields)&&((e||Array.from(l.mount)).forEach(e=>{e&&(t?Me(r.validatingFields,e,t):vt(r.validatingFields,e))}),h.state.next({validatingFields:r.validatingFields,isValidating:!ut(r.validatingFields)}))},g=(e,t,s,r)=>{const l=Be(n,e);if(l){const n=Be(a,e,Le(s)?Be(i,e):s);Le(n)||r&&r.defaultChecked||t?Me(a,e,t?n:At(l._f)):x(e,n),o.mount&&p()}},y=(e,t,n,a,o)=>{let l=!1,c=!1;const f={name:e};if(!s.disabled){if(!n||a){(d.isDirty||u.isDirty)&&(c=r.isDirty,r.isDirty=f.isDirty=w(),l=c!==f.isDirty);const s=ot(Be(i,e),t);c=!!Be(r.dirtyFields,e),s?vt(r.dirtyFields,e):Me(r.dirtyFields,e,!0),f.dirtyFields=r.dirtyFields,l=l||(d.dirtyFields||u.dirtyFields)&&c!==!s}if(n){const t=Be(r.touchedFields,e);t||(Me(r.touchedFields,e,n),f.touchedFields=r.touchedFields,l=l||(d.touchedFields||u.touchedFields)&&t!==n)}l&&o&&h.state.next(f)}return l?f:{}},v=(e,n,i,a)=>{const o=Be(r.errors,e),l=(d.isValid||u.isValid)&&qe(n)&&r.isValid!==n;var f;if(s.delayError&&i?(f=()=>((e,t)=>{Me(r.errors,e,t),h.state.next({errors:r.errors})})(e,i),t=e=>{clearTimeout(c),c=setTimeout(f,e)},t(s.delayError)):(clearTimeout(c),t=null,i?Me(r.errors,e,i):vt(r.errors,e)),(i?!ot(o,i):o)||!ut(a)||l){const t={...a,...l&&qe(n)?{isValid:n}:{},errors:r.errors,name:e};r={...r,...t},h.state.next(t)}},b=async e=>{m(e,!0);const t=await s.resolver(a,s.context,((e,t,s,r)=>{const n={};for(const i of e){const e=Be(t,i);e&&Me(n,i,e._f)}return{criteriaMode:s,names:[...e],fields:n,shouldUseNativeValidation:r}})(e||l.mount,n,s.criteriaMode,s.shouldUseNativeValidation));return m(e),t},_=async(e,t,n={valid:!0})=>{for(const i in e){const o=e[i];if(o){const{_f:e,...c}=o;if(e){const c=l.array.has(e.name),u=o._f&&Pt(o._f);u&&d.validatingFields&&m([i],!0);const h=await qt(o,l.disabled,a,f,s.shouldUseNativeValidation&&!t,c);if(u&&d.validatingFields&&m([i]),h[e.name]&&(n.valid=!1,t))break;!t&&(Be(h,e.name)?c?Lt(r.errors,h,e.name):Me(r.errors,e.name,h[e.name]):vt(r.errors,e.name))}!ut(c)&&await _(c,t,n)}}return n.valid},w=(e,t)=>!s.disabled&&(e&&t&&Me(a,e,t),!ot(A(),i)),k=(e,t,s)=>((e,t,s,r,n)=>it(e)?(r&&t.watch.add(e),Be(s,e,n)):Array.isArray(e)?e.map(e=>(r&&t.watch.add(e),Be(s,e))):(r&&(t.watchAll=!0),s))(e,l,{...o.mount?a:Le(t)?i:it(e)?{[e]:t}:t},s,t),x=(e,t,s={})=>{const r=Be(n,e);let i=t;if(r){const s=r._f;s&&(!s.disabled&&Me(a,e,Tt(t,s)),i=pt(s.ref)&&Re(t)?"":t,mt(s.ref)?[...s.ref.options].forEach(e=>e.selected=i.includes(e.value)):s.refs?Ce(s.ref)?s.refs.forEach(e=>{e.defaultChecked&&e.disabled||(Array.isArray(i)?e.checked=!!i.find(t=>t===e.value):e.checked=i===e.value||!!i)}):s.refs.forEach(e=>e.checked=e.value===i):ht(s.ref)?s.ref.value="":(s.ref.value=i,s.ref.type||h.state.next({name:e,values:De(a)})))}(s.shouldDirty||s.shouldTouch)&&y(e,i,s.shouldTouch,s.shouldDirty,!0),s.shouldValidate&&O(e)},j=(e,t,s)=>{for(const r in t){if(!t.hasOwnProperty(r))return;const i=t[r],a=e+"."+r,o=Be(n,a);(l.array.has(e)||Pe(i)||o&&!o._f)&&!Ne(i)?j(a,i,s):x(a,i,s)}},S=(e,t,s={})=>{const c=Be(n,e),f=l.array.has(e),p=De(t);Me(a,e,p),f?(h.array.next({name:e,values:De(a)}),(d.isDirty||d.dirtyFields||u.isDirty||u.dirtyFields)&&s.shouldDirty&&h.state.next({name:e,dirtyFields:kt(i,a),isDirty:w(e,p)})):!c||c._f||Re(p)?x(e,p,s):j(e,p,s),$t(e,l)&&h.state.next({...r,name:e}),h.state.next({name:o.mount?e:void 0,values:De(a)})},T=async e=>{o.mount=!0;const i=e.target;let c=i.name,g=!0;const w=Be(n,c),k=e=>{g=Number.isNaN(e)||Ne(e)&&isNaN(e.getTime())||ot(e,Be(a,c,e))},x=Rt(s.mode),j=Rt(s.reValidateMode);if(w){let o,T;const E=i.type?At(w._f):(e=>Pe(e)&&e.target?Ce(e.target)?e.target.checked:e.target.value:e)(e),A=e.type===ze||e.type===We,C=!((S=w._f).mount&&(S.required||S.min||S.max||S.maxLength||S.minLength||S.pattern||S.validate)||s.resolver||Be(r.errors,c)||w._f.deps)||((e,t,s,r,n)=>!n.isOnAll&&(!s&&n.isOnTouch?!(t||e):(s?r.isOnBlur:n.isOnBlur)?!e:!(s?r.isOnChange:n.isOnChange)||e))(A,Be(r.touchedFields,c),r.isSubmitted,j,x),N=$t(c,l,A);Me(a,c,E),A?(w._f.onBlur&&w._f.onBlur(e),t&&t(0)):w._f.onChange&&w._f.onChange(e);const R=y(c,E,A),I=!ut(R)||N;if(!A&&h.state.next({name:c,type:e.type,values:De(a)}),C)return(d.isValid||u.isValid)&&("onBlur"===s.mode?A&&p():A||p()),I&&h.state.next({name:c,...N?{}:R});if(!A&&N&&h.state.next({...r}),s.resolver){const{errors:e}=await b([c]);if(k(E),g){const t=Ut(r.errors,n,c),s=Ut(e,n,t.name||c);o=s.error,c=s.name,T=ut(e)}}else m([c],!0),o=(await qt(w,l.disabled,a,f,s.shouldUseNativeValidation))[c],m([c]),k(E),g&&(o?T=!1:(d.isValid||u.isValid)&&(T=await _(n,!0)));g&&(w._f.deps&&O(w._f.deps),v(c,T,o,R))}var S},E=(e,t)=>{if(Be(r.errors,t)&&e.focus)return e.focus(),1},O=async(e,t={})=>{let i,a;const o=ct(e);if(s.resolver){const t=await(async e=>{const{errors:t}=await b(e);if(e)for(const s of e){const e=Be(t,s);e?Me(r.errors,s,e):vt(r.errors,s)}else r.errors=t;return t})(Le(e)?e:o);i=ut(t),a=e?!o.some(e=>Be(t,e)):i}else e?(a=(await Promise.all(o.map(async e=>{const t=Be(n,e);return await _(t&&t._f?{[e]:t}:t)}))).every(Boolean),(a||r.isValid)&&p()):a=i=await _(n);return h.state.next({...!it(e)||(d.isValid||u.isValid)&&i!==r.isValid?{}:{name:e},...s.resolver||!e?{isValid:i}:{},errors:r.errors}),t.shouldFocus&&!a&&Dt(n,E,e?o:l.mount),a},A=e=>{const t={...o.mount?a:i};return Le(e)?t:it(e)?Be(t,e):e.map(e=>Be(t,e))},C=(e,t)=>({invalid:!!Be((t||r).errors,e),isDirty:!!Be((t||r).dirtyFields,e),error:Be((t||r).errors,e),isValidating:!!Be(r.validatingFields,e),isTouched:!!Be((t||r).touchedFields,e)}),N=(e,t,s)=>{const i=(Be(n,e,{_f:{}})._f||{}).ref,a=Be(r.errors,e)||{},{ref:o,message:l,type:c,...d}=a;Me(r.errors,e,{...d,...t,ref:i}),h.state.next({name:e,errors:r.errors,isValid:!1}),s&&s.shouldFocus&&i&&i.focus&&i.focus()},R=e=>h.state.subscribe({next:t=>{var s,n,o;s=e.name,n=t.name,o=e.exact,s&&n&&s!==n&&!ct(s).some(e=>e&&(o?e===n:e.startsWith(n)||n.startsWith(e)))||!((e,t,s,r)=>{s(e);const{name:n,...i}=e;return ut(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(e=>t[e]===(!r||Ge))})(t,e.formState||d,F,e.reRenderRoot)||e.callback({values:{...a},...r,...t,defaultValues:i})}}).unsubscribe,I=(e,t={})=>{for(const o of e?ct(e):l.mount)l.mount.delete(o),l.array.delete(o),t.keepValue||(vt(n,o),vt(a,o)),!t.keepError&&vt(r.errors,o),!t.keepDirty&&vt(r.dirtyFields,o),!t.keepTouched&&vt(r.touchedFields,o),!t.keepIsValidating&&vt(r.validatingFields,o),!s.shouldUnregister&&!t.keepDefaultValue&&vt(i,o);h.state.next({values:De(a)}),h.state.next({...r,...t.keepDirty?{isDirty:w()}:{}}),!t.keepIsValid&&p()},P=({disabled:e,name:t})=>{(qe(e)&&o.mount||e||l.disabled.has(t))&&(e?l.disabled.add(t):l.disabled.delete(t))},$=(e,t={})=>{let r=Be(n,e);const a=qe(t.disabled)||qe(s.disabled);return Me(n,e,{...r||{},_f:{...r&&r._f?r._f:{ref:{name:e}},name:e,mount:!0,...t}}),l.mount.add(e),r?P({disabled:qe(t.disabled)?t.disabled:s.disabled,name:e}):g(e,!0,t.value),{...a?{disabled:t.disabled||s.disabled}:{},...s.progressive?{required:!!t.required,min:Nt(t.min),max:Nt(t.max),minLength:Nt(t.minLength),maxLength:Nt(t.maxLength),pattern:Nt(t.pattern)}:{},name:e,onChange:T,onBlur:T,ref:a=>{if(a){$(e,t),r=Be(n,e);const s=Le(a.value)&&a.querySelectorAll&&a.querySelectorAll("input,select,textarea")[0]||a,o=(e=>gt(e)||Ce(e))(s),l=r._f.refs||[];if(o?l.find(e=>e===s):s===r._f.ref)return;Me(n,e,{_f:{...r._f,...o?{refs:[...l.filter(yt),s,...Array.isArray(Be(i,e))?[{}]:[]],ref:{type:s.type,name:e}}:{ref:s}}}),g(e,!1,void 0,s)}else r=Be(n,e,{}),r._f&&(r._f.mount=!1),(s.shouldUnregister||t.shouldUnregister)&&(!((e,t)=>e.has((e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e)(t)))(l.array,e)||!o.action)&&l.unMount.add(e)}}},D=()=>s.shouldFocusError&&Dt(n,E,l.mount),U=(e,t)=>async i=>{let o;i&&(i.preventDefault&&i.preventDefault(),i.persist&&i.persist());let c=De(a);if(h.state.next({isSubmitting:!0}),s.resolver){const{errors:e,values:t}=await b();r.errors=e,c=De(t)}else await _(n);if(l.disabled.size)for(const e of l.disabled)vt(c,e);if(vt(r.errors,"root"),ut(r.errors)){h.state.next({errors:{}});try{await e(c,i)}catch(d){o=d}}else t&&await t({...r.errors},i),D(),setTimeout(D);if(h.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:ut(r.errors)&&!o,submitCount:r.submitCount+1,errors:r.errors}),o)throw o},L=(e,t={})=>{const c=e?De(e):i,u=De(c),f=ut(e),p=f?i:u;if(t.keepDefaultValues||(i=c),!t.keepValues){if(t.keepDirtyValues){const e=new Set([...l.mount,...Object.keys(kt(i,a))]);for(const t of Array.from(e))Be(r.dirtyFields,t)?Me(p,t,Be(a,t)):S(t,Be(p,t))}else{if($e&&Le(e))for(const e of l.mount){const t=Be(n,e);if(t&&t._f){const e=Array.isArray(t._f.refs)?t._f.refs[0]:t._f.ref;if(pt(e)){const t=e.closest("form");if(t){t.reset();break}}}}if(t.keepFieldsRef)for(const e of l.mount)S(e,Be(p,e));else n={}}a=s.shouldUnregister?t.keepDefaultValues?De(i):{}:De(p),h.array.next({values:{...p}}),h.state.next({values:{...p}})}l={mount:t.keepDirtyValues?l.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},o.mount=!d.isValid||!!t.keepIsValid||!!t.keepDirtyValues,o.watch=!!s.shouldUnregister,h.state.next({submitCount:t.keepSubmitCount?r.submitCount:0,isDirty:!f&&(t.keepDirty?r.isDirty:!(!t.keepDefaultValues||ot(e,i))),isSubmitted:!!t.keepIsSubmitted&&r.isSubmitted,dirtyFields:f?{}:t.keepDirtyValues?t.keepDefaultValues&&a?kt(i,a):r.dirtyFields:t.keepDefaultValues&&e?kt(i,e):t.keepDirty?r.dirtyFields:{},touchedFields:t.keepTouched?r.touchedFields:{},errors:t.keepErrors?r.errors:{},isSubmitSuccessful:!!t.keepIsSubmitSuccessful&&r.isSubmitSuccessful,isSubmitting:!1})},V=(e,t)=>L(ft(e)?e(a):e,t),F=e=>{r={...r,...e}},B={control:{register:$,unregister:I,getFieldState:C,handleSubmit:U,setError:N,_subscribe:R,_runSchema:b,_focusError:D,_getWatch:k,_getDirty:w,_setValid:p,_setFieldArray:(e,t=[],l,c,f=!0,p=!0)=>{if(c&&l&&!s.disabled){if(o.action=!0,p&&Array.isArray(Be(n,e))){const t=l(Be(n,e),c.argA,c.argB);f&&Me(n,e,t)}if(p&&Array.isArray(Be(r.errors,e))){const t=l(Be(r.errors,e),c.argA,c.argB);f&&Me(r.errors,e,t),((e,t)=>{!Ve(Be(e,t)).length&&vt(e,t)})(r.errors,e)}if((d.touchedFields||u.touchedFields)&&p&&Array.isArray(Be(r.touchedFields,e))){const t=l(Be(r.touchedFields,e),c.argA,c.argB);f&&Me(r.touchedFields,e,t)}(d.dirtyFields||u.dirtyFields)&&(r.dirtyFields=kt(i,a)),h.state.next({name:e,isDirty:w(e,t),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else Me(a,e,t)},_setDisabledField:P,_setErrors:e=>{r.errors=e,h.state.next({errors:r.errors,isValid:!1})},_getFieldArray:e=>Ve(Be(o.mount?a:i,e,s.shouldUnregister?Be(i,e,[]):[])),_reset:L,_resetDefaultValues:()=>ft(s.defaultValues)&&s.defaultValues().then(e=>{V(e,s.resetOptions),h.state.next({isLoading:!1})}),_removeUnmounted:()=>{for(const e of l.unMount){const t=Be(n,e);t&&(t._f.refs?t._f.refs.every(e=>!yt(e)):!yt(t._f.ref))&&I(e)}l.unMount=new Set},_disableForm:e=>{qe(e)&&(h.state.next({disabled:e}),Dt(n,(t,s)=>{const r=Be(n,s);r&&(t.disabled=r._f.disabled||e,Array.isArray(r._f.refs)&&r._f.refs.forEach(t=>{t.disabled=r._f.disabled||e}))},0,!1))},_subjects:h,_proxyFormState:d,get _fields(){return n},get _formValues(){return a},get _state(){return o},set _state(e){o=e},get _defaultValues(){return i},get _names(){return l},set _names(e){l=e},get _formState(){return r},get _options(){return s},set _options(e){s={...s,...e}}},subscribe:e=>(o.mount=!0,u={...u,...e.formState},R({...e,formState:u})),trigger:O,register:$,handleSubmit:U,watch:(e,t)=>ft(e)?h.state.subscribe({next:s=>"values"in s&&e(k(void 0,t),s)}):k(e,t,!0),setValue:S,getValues:A,reset:V,resetField:(e,t={})=>{Be(n,e)&&(Le(t.defaultValue)?S(e,De(Be(i,e))):(S(e,t.defaultValue),Me(i,e,De(t.defaultValue))),t.keepTouched||vt(r.touchedFields,e),t.keepDirty||(vt(r.dirtyFields,e),r.isDirty=t.defaultValue?w(e,De(Be(i,e))):w()),t.keepError||(vt(r.errors,e),d.isValid&&p()),h.state.next({...r}))},clearErrors:e=>{e&&ct(e).forEach(e=>vt(r.errors,e)),h.state.next({errors:e?r.errors:{}})},unregister:I,setError:N,setFocus:(e,t={})=>{const s=Be(n,e),r=s&&s._f;if(r){const e=r.refs?r.refs[0]:r.ref;e.focus&&(e.focus(),t.shouldSelect&&ft(e.select)&&e.select())}},getFieldState:C};return{...B,formControl:B}}function Wt(e={}){const t=U.useRef(void 0),s=U.useRef(void 0),[r,n]=U.useState({isDirty:!1,isValidating:!1,isLoading:ft(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,isReady:!1,defaultValues:ft(e.defaultValues)?void 0:e.defaultValues});if(!t.current)if(e.formControl)t.current={...e.formControl,formState:r},e.defaultValues&&!ft(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:s,...n}=zt(e);t.current={...n,formState:r}}const i=t.current.control;return i._options=e,nt(()=>{const e=i._subscribe({formState:i._proxyFormState,callback:()=>n({...i._formState}),reRenderRoot:!0});return n(e=>({...e,isReady:!0})),i._formState.isReady=!0,e},[i]),U.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),U.useEffect(()=>{e.mode&&(i._options.mode=e.mode),e.reValidateMode&&(i._options.reValidateMode=e.reValidateMode)},[i,e.mode,e.reValidateMode]),U.useEffect(()=>{e.errors&&(i._setErrors(e.errors),i._focusError())},[i,e.errors]),U.useEffect(()=>{e.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,e.shouldUnregister]),U.useEffect(()=>{if(i._proxyFormState.isDirty){const e=i._getDirty();e!==r.isDirty&&i._subjects.state.next({isDirty:e})}},[i,r.isDirty]),U.useEffect(()=>{e.values&&!ot(e.values,s.current)?(i._reset(e.values,{keepFieldsRef:!0,...i._options.resetOptions}),s.current=e.values,n(e=>({...e}))):i._resetDefaultValues()},[i,e.values]),U.useEffect(()=>{i._state.mount||(i._setValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=((e,t,s,r=!0)=>{const n={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(n,i,{get:()=>{const s=i;return t._proxyFormState[s]!==Ge&&(t._proxyFormState[s]=!r||Ge),e[s]}});return n})(r,i),t.current}const Zt=(e,t,s)=>{if(e&&"reportValidity"in e){const r=Be(s,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},Kt=(e,t)=>{for(const s in t.fields){const r=t.fields[s];r&&r.ref&&"reportValidity"in r.ref?Zt(r.ref,s,e):r.refs&&r.refs.forEach(t=>Zt(t,s,e))}},Jt=(e,t)=>{t.shouldUseNativeValidation&&Kt(e,t);const s={};for(const r in e){const n=Be(t.fields,r),i=Object.assign(e[r]||{},{ref:n&&n.ref});if(Ht(t.names||Object.keys(e),r)){const e=Object.assign({},Be(s,r));Me(e,"root",i),Me(s,r,e)}else Me(s,r,i)}return s},Ht=(e,t)=>e.some(e=>e.startsWith(t+"."));var Gt,Yt,Qt,Xt=function(e,t){for(var s={};e.length;){var r=e[0],n=r.code,i=r.message,a=r.path.join(".");if(!s[a])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];s[a]={message:o.message,type:o.code}}else s[a]={message:i,type:n};if("unionErrors"in r&&r.unionErrors.forEach(function(t){return t.errors.forEach(function(t){return e.push(t)})}),t){var l=s[a].types,c=l&&l[r.code];s[a]=lt(a,t,s,n,c?[].concat(c,r.message):r.message)}e.shift()}return s},es=function(e,t,s){return void 0===s&&(s={}),function(r,n,i){try{return Promise.resolve(function(n,a){try{var o=Promise.resolve(e["sync"===s.mode?"parse":"parseAsync"](r,t)).then(function(e){return i.shouldUseNativeValidation&&Kt({},i),{errors:{},values:s.raw?r:e}})}catch(l){return a(l)}return o&&o.then?o.then(void 0,a):o}(0,function(e){if(t=e,Array.isArray(null==t?void 0:t.errors))return{values:{},errors:Jt(Xt(e.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)};var t;throw e}))}catch(a){return Promise.reject(a)}}};(Yt=Gt||(Gt={})).assertEqual=e=>{},Yt.assertIs=function(e){},Yt.assertNever=function(e){throw new Error},Yt.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},Yt.getValidEnumValues=e=>{const t=Yt.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),s={};for(const r of t)s[r]=e[r];return Yt.objectValues(s)},Yt.objectValues=e=>Yt.objectKeys(e).map(function(t){return e[t]}),Yt.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},Yt.find=(e,t)=>{for(const s of e)if(t(s))return s},Yt.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,Yt.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},Yt.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(Qt||(Qt={})).mergeShapes=(e,t)=>({...e,...t});const ts=Gt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ss=e=>{switch(typeof e){case"undefined":return ts.undefined;case"string":return ts.string;case"number":return Number.isNaN(e)?ts.nan:ts.number;case"boolean":return ts.boolean;case"function":return ts.function;case"bigint":return ts.bigint;case"symbol":return ts.symbol;case"object":return Array.isArray(e)?ts.array:null===e?ts.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?ts.promise:"undefined"!=typeof Map&&e instanceof Map?ts.map:"undefined"!=typeof Set&&e instanceof Set?ts.set:"undefined"!=typeof Date&&e instanceof Date?ts.date:ts.object;default:return ts.unknown}},rs=Gt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ns extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},s={_errors:[]},r=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(r);else if("invalid_return_type"===n.code)r(n.returnTypeError);else if("invalid_arguments"===n.code)r(n.argumentsError);else if(0===n.path.length)s._errors.push(t(n));else{let e=s,r=0;for(;r<n.path.length;){const s=n.path[r];r===n.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(n))):e[s]=e[s]||{_errors:[]},e=e[s],r++}}};return r(this),s}static assert(e){if(!(e instanceof ns))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Gt.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},s=[];for(const r of this.issues)if(r.path.length>0){const s=r.path[0];t[s]=t[s]||[],t[s].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}ns.create=e=>new ns(e);const is=(e,t)=>{let s;switch(e.code){case rs.invalid_type:s=e.received===ts.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case rs.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,Gt.jsonStringifyReplacer)}`;break;case rs.unrecognized_keys:s=`Unrecognized key(s) in object: ${Gt.joinValues(e.keys,", ")}`;break;case rs.invalid_union:s="Invalid input";break;case rs.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${Gt.joinValues(e.options)}`;break;case rs.invalid_enum_value:s=`Invalid enum value. Expected ${Gt.joinValues(e.options)}, received '${e.received}'`;break;case rs.invalid_arguments:s="Invalid function arguments";break;case rs.invalid_return_type:s="Invalid function return type";break;case rs.invalid_date:s="Invalid date";break;case rs.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:Gt.assertNever(e.validation):s="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case rs.too_small:s="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case rs.too_big:s="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case rs.custom:s="Invalid input";break;case rs.invalid_intersection_types:s="Intersection results could not be merged";break;case rs.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case rs.not_finite:s="Number must be finite";break;default:s=t.defaultError,Gt.assertNever(e)}return{message:s}};let as=is;function os(e,t){const s=as,r=(e=>{const{data:t,path:s,errorMaps:r,issueData:n}=e,i=[...s,...n.path||[]],a={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const l=r.filter(e=>!!e).slice().reverse();for(const c of l)o=c(a,{data:t,defaultError:o}).message;return{...n,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===is?void 0:is].filter(e=>!!e)});e.common.issues.push(r)}class ls{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const r of t){if("aborted"===r.status)return cs;"dirty"===r.status&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const r of t){const e=await r.key,t=await r.value;s.push({key:e,value:t})}return ls.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const r of t){const{key:t,value:n}=r;if("aborted"===t.status)return cs;if("aborted"===n.status)return cs;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!r.alwaysSet||(s[t.value]=n.value)}return{status:e.value,value:s}}}const cs=Object.freeze({status:"aborted"}),ds=e=>({status:"dirty",value:e}),us=e=>({status:"valid",value:e}),hs=e=>"aborted"===e.status,fs=e=>"dirty"===e.status,ps=e=>"valid"===e.status,ms=e=>"undefined"!=typeof Promise&&e instanceof Promise;var gs,ys;(ys=gs||(gs={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},ys.toString=e=>"string"==typeof e?e:e?.message;class vs{constructor(e,t,s,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const bs=(e,t)=>{if(ps(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ns(e.common.issues);return this._error=t,this._error}}};function _s(e){if(!e)return{};const{errorMap:t,invalid_type_error:s,required_error:r,description:n}=e;if(t&&(s||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??r??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??s??n.defaultError}},description:n}}class ws{get description(){return this._def.description}_getType(e){return ss(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ss(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ls,ctx:{common:e.parent.common,data:e.data,parsedType:ss(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ms(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)},r=this._parseSync({data:e,path:s.path,parent:s});return bs(s,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return ps(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ps(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ss(e)},r=this._parse({data:e,path:s.path,parent:s}),n=await(ms(r)?r:Promise.resolve(r));return bs(s,n)}refine(e,t){const s=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const n=e(t),i=()=>r.addIssue({code:rs.custom,...s(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(i(),!1)):!!n||(i(),!1)})}refinement(e,t){return this._refinement((s,r)=>!!e(s)||(r.addIssue("function"==typeof t?t(s,r):t),!1))}_refinement(e){return new _r({schema:this,typeName:Ar.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return wr.create(this,this._def)}nullable(){return kr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return nr.create(this)}promise(){return br.create(this,this._def)}or(e){return or.create([this,e],this._def)}and(e){return cr.create(this,e,this._def)}transform(e){return new _r({..._s(this._def),schema:this,typeName:Ar.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new xr({..._s(this._def),innerType:this,defaultValue:t,typeName:Ar.ZodDefault})}brand(){return new Tr({typeName:Ar.ZodBranded,type:this,..._s(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new jr({..._s(this._def),innerType:this,catchValue:t,typeName:Ar.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Er.create(this,e)}readonly(){return Or.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ks=/^c[^\s-]{8,}$/i,xs=/^[0-9a-z]+$/,js=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ss=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ts=/^[a-z0-9_-]{21}$/i,Es=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Os=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,As=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Cs;const Ns=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Rs=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Is=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ps=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,$s=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ds=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Us="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ls=new RegExp(`^${Us}$`);function Vs(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function Fs(e){return new RegExp(`^${Vs(e)}$`)}function Bs(e){let t=`${Us}T${Vs(e)}`;const s=[];return s.push(e.local?"Z?":"Z"),e.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function qs(e,t){return!("v4"!==t&&t||!Ns.test(e))||!("v6"!==t&&t||!Is.test(e))}function Ms(e,t){if(!Es.test(e))return!1;try{const[s]=e.split(".");if(!s)return!1;const r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),n=JSON.parse(atob(r));return"object"==typeof n&&null!==n&&((!("typ"in n)||"JWT"===n?.typ)&&(!!n.alg&&(!t||n.alg===t)))}catch{return!1}}function zs(e,t){return!("v4"!==t&&t||!Rs.test(e))||!("v6"!==t&&t||!Ps.test(e))}class Ws extends ws{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==ts.string){const t=this._getOrReturnCtx(e);return os(t,{code:rs.invalid_type,expected:ts.string,received:t.parsedType}),cs}const t=new ls;let s;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(s=this._getOrReturnCtx(e,s),os(s,{code:rs.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("max"===r.kind)e.data.length>r.value&&(s=this._getOrReturnCtx(e,s),os(s,{code:rs.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("length"===r.kind){const n=e.data.length>r.value,i=e.data.length<r.value;(n||i)&&(s=this._getOrReturnCtx(e,s),n?os(s,{code:rs.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):i&&os(s,{code:rs.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)As.test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"email",code:rs.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)Cs||(Cs=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Cs.test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"emoji",code:rs.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)Ss.test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"uuid",code:rs.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)Ts.test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"nanoid",code:rs.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)ks.test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"cuid",code:rs.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)xs.test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"cuid2",code:rs.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)js.test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"ulid",code:rs.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),os(s,{validation:"url",code:rs.invalid_string,message:r.message}),t.dirty()}else if("regex"===r.kind){r.regex.lastIndex=0;r.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"regex",code:rs.invalid_string,message:r.message}),t.dirty())}else if("trim"===r.kind)e.data=e.data.trim();else if("includes"===r.kind)e.data.includes(r.value,r.position)||(s=this._getOrReturnCtx(e,s),os(s,{code:rs.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty());else if("toLowerCase"===r.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===r.kind)e.data=e.data.toUpperCase();else if("startsWith"===r.kind)e.data.startsWith(r.value)||(s=this._getOrReturnCtx(e,s),os(s,{code:rs.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty());else if("endsWith"===r.kind)e.data.endsWith(r.value)||(s=this._getOrReturnCtx(e,s),os(s,{code:rs.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty());else if("datetime"===r.kind){Bs(r).test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{code:rs.invalid_string,validation:"datetime",message:r.message}),t.dirty())}else if("date"===r.kind){Ls.test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{code:rs.invalid_string,validation:"date",message:r.message}),t.dirty())}else if("time"===r.kind){Fs(r).test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{code:rs.invalid_string,validation:"time",message:r.message}),t.dirty())}else"duration"===r.kind?Os.test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"duration",code:rs.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?qs(e.data,r.version)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"ip",code:rs.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?Ms(e.data,r.alg)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"jwt",code:rs.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?zs(e.data,r.version)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"cidr",code:rs.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?$s.test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"base64",code:rs.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?Ds.test(e.data)||(s=this._getOrReturnCtx(e,s),os(s,{validation:"base64url",code:rs.invalid_string,message:r.message}),t.dirty()):Gt.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement(t=>e.test(t),{validation:t,code:rs.invalid_string,...gs.errToObj(s)})}_addCheck(e){return new Ws({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...gs.errToObj(e)})}url(e){return this._addCheck({kind:"url",...gs.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...gs.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...gs.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...gs.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...gs.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...gs.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...gs.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...gs.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...gs.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...gs.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...gs.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...gs.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...gs.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...gs.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...gs.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...gs.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...gs.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...gs.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...gs.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...gs.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...gs.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...gs.errToObj(t)})}nonempty(e){return this.min(1,gs.errToObj(e))}trim(){return new Ws({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ws({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ws({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function Zs(e,t){const s=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,n=s>r?s:r;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}Ws.create=e=>new Ws({checks:[],typeName:Ar.ZodString,coerce:e?.coerce??!1,..._s(e)});class Ks extends ws{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==ts.number){const t=this._getOrReturnCtx(e);return os(t,{code:rs.invalid_type,expected:ts.number,received:t.parsedType}),cs}let t;const s=new ls;for(const r of this._def.checks)if("int"===r.kind)Gt.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),os(t,{code:rs.invalid_type,expected:"integer",received:"float",message:r.message}),s.dirty());else if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),os(t,{code:rs.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),os(t,{code:rs.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty())}else"multipleOf"===r.kind?0!==Zs(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),os(t,{code:rs.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),os(t,{code:rs.not_finite,message:r.message}),s.dirty()):Gt.assertNever(r);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,gs.toString(t))}gt(e,t){return this.setLimit("min",e,!1,gs.toString(t))}lte(e,t){return this.setLimit("max",e,!0,gs.toString(t))}lt(e,t){return this.setLimit("max",e,!1,gs.toString(t))}setLimit(e,t,s,r){return new Ks({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:gs.toString(r)}]})}_addCheck(e){return new Ks({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:gs.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:gs.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:gs.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:gs.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:gs.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:gs.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:gs.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:gs.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:gs.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&Gt.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if("finite"===s.kind||"int"===s.kind||"multipleOf"===s.kind)return!0;"min"===s.kind?(null===t||s.value>t)&&(t=s.value):"max"===s.kind&&(null===e||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Ks.create=e=>new Ks({checks:[],typeName:Ar.ZodNumber,coerce:e?.coerce||!1,..._s(e)});class Js extends ws{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ts.bigint)return this._getInvalidInput(e);let t;const s=new ls;for(const r of this._def.checks)if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),os(t,{code:rs.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),os(t,{code:rs.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty())}else"multipleOf"===r.kind?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),os(t,{code:rs.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()):Gt.assertNever(r);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return os(t,{code:rs.invalid_type,expected:ts.bigint,received:t.parsedType}),cs}gte(e,t){return this.setLimit("min",e,!0,gs.toString(t))}gt(e,t){return this.setLimit("min",e,!1,gs.toString(t))}lte(e,t){return this.setLimit("max",e,!0,gs.toString(t))}lt(e,t){return this.setLimit("max",e,!1,gs.toString(t))}setLimit(e,t,s,r){return new Js({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:gs.toString(r)}]})}_addCheck(e){return new Js({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:gs.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:gs.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:gs.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:gs.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:gs.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Js.create=e=>new Js({checks:[],typeName:Ar.ZodBigInt,coerce:e?.coerce??!1,..._s(e)});class Hs extends ws{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==ts.boolean){const t=this._getOrReturnCtx(e);return os(t,{code:rs.invalid_type,expected:ts.boolean,received:t.parsedType}),cs}return us(e.data)}}Hs.create=e=>new Hs({typeName:Ar.ZodBoolean,coerce:e?.coerce||!1,..._s(e)});class Gs extends ws{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==ts.date){const t=this._getOrReturnCtx(e);return os(t,{code:rs.invalid_type,expected:ts.date,received:t.parsedType}),cs}if(Number.isNaN(e.data.getTime())){return os(this._getOrReturnCtx(e),{code:rs.invalid_date}),cs}const t=new ls;let s;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(s=this._getOrReturnCtx(e,s),os(s,{code:rs.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),t.dirty()):"max"===r.kind?e.data.getTime()>r.value&&(s=this._getOrReturnCtx(e,s),os(s,{code:rs.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):Gt.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Gs({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:gs.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:gs.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Gs.create=e=>new Gs({checks:[],coerce:e?.coerce||!1,typeName:Ar.ZodDate,..._s(e)});class Ys extends ws{_parse(e){if(this._getType(e)!==ts.symbol){const t=this._getOrReturnCtx(e);return os(t,{code:rs.invalid_type,expected:ts.symbol,received:t.parsedType}),cs}return us(e.data)}}Ys.create=e=>new Ys({typeName:Ar.ZodSymbol,..._s(e)});class Qs extends ws{_parse(e){if(this._getType(e)!==ts.undefined){const t=this._getOrReturnCtx(e);return os(t,{code:rs.invalid_type,expected:ts.undefined,received:t.parsedType}),cs}return us(e.data)}}Qs.create=e=>new Qs({typeName:Ar.ZodUndefined,..._s(e)});class Xs extends ws{_parse(e){if(this._getType(e)!==ts.null){const t=this._getOrReturnCtx(e);return os(t,{code:rs.invalid_type,expected:ts.null,received:t.parsedType}),cs}return us(e.data)}}Xs.create=e=>new Xs({typeName:Ar.ZodNull,..._s(e)});class er extends ws{constructor(){super(...arguments),this._any=!0}_parse(e){return us(e.data)}}er.create=e=>new er({typeName:Ar.ZodAny,..._s(e)});class tr extends ws{constructor(){super(...arguments),this._unknown=!0}_parse(e){return us(e.data)}}tr.create=e=>new tr({typeName:Ar.ZodUnknown,..._s(e)});class sr extends ws{_parse(e){const t=this._getOrReturnCtx(e);return os(t,{code:rs.invalid_type,expected:ts.never,received:t.parsedType}),cs}}sr.create=e=>new sr({typeName:Ar.ZodNever,..._s(e)});class rr extends ws{_parse(e){if(this._getType(e)!==ts.undefined){const t=this._getOrReturnCtx(e);return os(t,{code:rs.invalid_type,expected:ts.void,received:t.parsedType}),cs}return us(e.data)}}rr.create=e=>new rr({typeName:Ar.ZodVoid,..._s(e)});class nr extends ws{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),r=this._def;if(t.parsedType!==ts.array)return os(t,{code:rs.invalid_type,expected:ts.array,received:t.parsedType}),cs;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,n=t.data.length<r.exactLength.value;(e||n)&&(os(t,{code:e?rs.too_big:rs.too_small,minimum:n?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(os(t,{code:rs.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(os(t,{code:rs.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((e,s)=>r.type._parseAsync(new vs(t,e,t.path,s)))).then(e=>ls.mergeArray(s,e));const n=[...t.data].map((e,s)=>r.type._parseSync(new vs(t,e,t.path,s)));return ls.mergeArray(s,n)}get element(){return this._def.type}min(e,t){return new nr({...this._def,minLength:{value:e,message:gs.toString(t)}})}max(e,t){return new nr({...this._def,maxLength:{value:e,message:gs.toString(t)}})}length(e,t){return new nr({...this._def,exactLength:{value:e,message:gs.toString(t)}})}nonempty(e){return this.min(1,e)}}function ir(e){if(e instanceof ar){const t={};for(const s in e.shape){const r=e.shape[s];t[s]=wr.create(ir(r))}return new ar({...e._def,shape:()=>t})}return e instanceof nr?new nr({...e._def,type:ir(e.element)}):e instanceof wr?wr.create(ir(e.unwrap())):e instanceof kr?kr.create(ir(e.unwrap())):e instanceof dr?dr.create(e.items.map(e=>ir(e))):e}nr.create=(e,t)=>new nr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ar.ZodArray,..._s(t)});class ar extends ws{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=Gt.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ts.object){const t=this._getOrReturnCtx(e);return os(t,{code:rs.invalid_type,expected:ts.object,received:t.parsedType}),cs}const{status:t,ctx:s}=this._processInputParams(e),{shape:r,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof sr&&"strip"===this._def.unknownKeys))for(const o in s.data)n.includes(o)||i.push(o);const a=[];for(const o of n){const e=r[o],t=s.data[o];a.push({key:{status:"valid",value:o},value:e._parse(new vs(s,t,s.path,o)),alwaysSet:o in s.data})}if(this._def.catchall instanceof sr){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of i)a.push({key:{status:"valid",value:t},value:{status:"valid",value:s.data[t]}});else if("strict"===e)i.length>0&&(os(s,{code:rs.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const r=s.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new vs(s,r,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of a){const s=await t.key,r=await t.value;e.push({key:s,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>ls.mergeObjectSync(t,e)):ls.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return gs.errToObj,new ar({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,s)=>{const r=this._def.errorMap?.(t,s).message??s.defaultError;return"unrecognized_keys"===t.code?{message:gs.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new ar({...this._def,unknownKeys:"strip"})}passthrough(){return new ar({...this._def,unknownKeys:"passthrough"})}extend(e){return new ar({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ar({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ar.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ar({...this._def,catchall:e})}pick(e){const t={};for(const s of Gt.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new ar({...this._def,shape:()=>t})}omit(e){const t={};for(const s of Gt.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new ar({...this._def,shape:()=>t})}deepPartial(){return ir(this)}partial(e){const t={};for(const s of Gt.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?t[s]=r:t[s]=r.optional()}return new ar({...this._def,shape:()=>t})}required(e){const t={};for(const s of Gt.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let e=this.shape[s];for(;e instanceof wr;)e=e._def.innerType;t[s]=e}return new ar({...this._def,shape:()=>t})}keyof(){return gr(Gt.objectKeys(this.shape))}}ar.create=(e,t)=>new ar({shape:()=>e,unknownKeys:"strip",catchall:sr.create(),typeName:Ar.ZodObject,..._s(t)}),ar.strictCreate=(e,t)=>new ar({shape:()=>e,unknownKeys:"strict",catchall:sr.create(),typeName:Ar.ZodObject,..._s(t)}),ar.lazycreate=(e,t)=>new ar({shape:e,unknownKeys:"strip",catchall:sr.create(),typeName:Ar.ZodObject,..._s(t)});class or extends ws{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;if(t.common.async)return Promise.all(s.map(async e=>{const s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const s=e.map(e=>new ns(e.ctx.common.issues));return os(t,{code:rs.invalid_union,unionErrors:s}),cs});{let e;const r=[];for(const i of s){const s={...t,common:{...t.common,issues:[]},parent:null},n=i._parseSync({data:t.data,path:t.path,parent:s});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:s}),s.common.issues.length&&r.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=r.map(e=>new ns(e));return os(t,{code:rs.invalid_union,unionErrors:n}),cs}}get options(){return this._def.options}}function lr(e,t){const s=ss(e),r=ss(t);if(e===t)return{valid:!0,data:e};if(s===ts.object&&r===ts.object){const s=Gt.objectKeys(t),r=Gt.objectKeys(e).filter(e=>-1!==s.indexOf(e)),n={...e,...t};for(const i of r){const s=lr(e[i],t[i]);if(!s.valid)return{valid:!1};n[i]=s.data}return{valid:!0,data:n}}if(s===ts.array&&r===ts.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let r=0;r<e.length;r++){const n=lr(e[r],t[r]);if(!n.valid)return{valid:!1};s.push(n.data)}return{valid:!0,data:s}}return s===ts.date&&r===ts.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}or.create=(e,t)=>new or({options:e,typeName:Ar.ZodUnion,..._s(t)});class cr extends ws{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=(e,r)=>{if(hs(e)||hs(r))return cs;const n=lr(e.value,r.value);return n.valid?((fs(e)||fs(r))&&t.dirty(),{status:t.value,value:n.data}):(os(s,{code:rs.invalid_intersection_types}),cs)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}cr.create=(e,t,s)=>new cr({left:e,right:t,typeName:Ar.ZodIntersection,..._s(s)});class dr extends ws{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ts.array)return os(s,{code:rs.invalid_type,expected:ts.array,received:s.parsedType}),cs;if(s.data.length<this._def.items.length)return os(s,{code:rs.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),cs;!this._def.rest&&s.data.length>this._def.items.length&&(os(s,{code:rs.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...s.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new vs(s,e,s.path,t)):null}).filter(e=>!!e);return s.common.async?Promise.all(r).then(e=>ls.mergeArray(t,e)):ls.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new dr({...this._def,rest:e})}}dr.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new dr({items:e,typeName:Ar.ZodTuple,rest:null,..._s(t)})};class ur extends ws{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ts.object)return os(s,{code:rs.invalid_type,expected:ts.object,received:s.parsedType}),cs;const r=[],n=this._def.keyType,i=this._def.valueType;for(const a in s.data)r.push({key:n._parse(new vs(s,a,s.path,a)),value:i._parse(new vs(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?ls.mergeObjectAsync(t,r):ls.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,s){return new ur(t instanceof ws?{keyType:e,valueType:t,typeName:Ar.ZodRecord,..._s(s)}:{keyType:Ws.create(),valueType:e,typeName:Ar.ZodRecord,..._s(t)})}}class hr extends ws{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ts.map)return os(s,{code:rs.invalid_type,expected:ts.map,received:s.parsedType}),cs;const r=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map(([e,t],i)=>({key:r._parse(new vs(s,e,s.path,[i,"key"])),value:n._parse(new vs(s,t,s.path,[i,"value"]))}));if(s.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const s of i){const r=await s.key,n=await s.value;if("aborted"===r.status||"aborted"===n.status)return cs;"dirty"!==r.status&&"dirty"!==n.status||t.dirty(),e.set(r.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const s of i){const r=s.key,n=s.value;if("aborted"===r.status||"aborted"===n.status)return cs;"dirty"!==r.status&&"dirty"!==n.status||t.dirty(),e.set(r.value,n.value)}return{status:t.value,value:e}}}}hr.create=(e,t,s)=>new hr({valueType:t,keyType:e,typeName:Ar.ZodMap,..._s(s)});class fr extends ws{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==ts.set)return os(s,{code:rs.invalid_type,expected:ts.set,received:s.parsedType}),cs;const r=this._def;null!==r.minSize&&s.data.size<r.minSize.value&&(os(s,{code:rs.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&s.data.size>r.maxSize.value&&(os(s,{code:rs.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const s=new Set;for(const r of e){if("aborted"===r.status)return cs;"dirty"===r.status&&t.dirty(),s.add(r.value)}return{status:t.value,value:s}}const a=[...s.data.values()].map((e,t)=>n._parse(new vs(s,e,s.path,t)));return s.common.async?Promise.all(a).then(e=>i(e)):i(a)}min(e,t){return new fr({...this._def,minSize:{value:e,message:gs.toString(t)}})}max(e,t){return new fr({...this._def,maxSize:{value:e,message:gs.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}fr.create=(e,t)=>new fr({valueType:e,minSize:null,maxSize:null,typeName:Ar.ZodSet,..._s(t)});class pr extends ws{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}pr.create=(e,t)=>new pr({getter:e,typeName:Ar.ZodLazy,..._s(t)});class mr extends ws{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return os(t,{received:t.data,code:rs.invalid_literal,expected:this._def.value}),cs}return{status:"valid",value:e.data}}get value(){return this._def.value}}function gr(e,t){return new yr({values:e,typeName:Ar.ZodEnum,..._s(t)})}mr.create=(e,t)=>new mr({value:e,typeName:Ar.ZodLiteral,..._s(t)});class yr extends ws{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return os(t,{expected:Gt.joinValues(s),received:t.parsedType,code:rs.invalid_type}),cs}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return os(t,{received:t.data,code:rs.invalid_enum_value,options:s}),cs}return us(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return yr.create(e,{...this._def,...t})}exclude(e,t=this._def){return yr.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}yr.create=gr;class vr extends ws{_parse(e){const t=Gt.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==ts.string&&s.parsedType!==ts.number){const e=Gt.objectValues(t);return os(s,{expected:Gt.joinValues(e),received:s.parsedType,code:rs.invalid_type}),cs}if(this._cache||(this._cache=new Set(Gt.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=Gt.objectValues(t);return os(s,{received:s.data,code:rs.invalid_enum_value,options:e}),cs}return us(e.data)}get enum(){return this._def.values}}vr.create=(e,t)=>new vr({values:e,typeName:Ar.ZodNativeEnum,..._s(t)});class br extends ws{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ts.promise&&!1===t.common.async)return os(t,{code:rs.invalid_type,expected:ts.promise,received:t.parsedType}),cs;const s=t.parsedType===ts.promise?t.data:Promise.resolve(t.data);return us(s.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}br.create=(e,t)=>new br({type:e,typeName:Ar.ZodPromise,..._s(t)});class _r extends ws{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ar.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=this._def.effect||null,n={addIssue:e=>{os(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===r.type){const e=r.transform(s.data,n);if(s.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return cs;const r=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===r.status?cs:"dirty"===r.status||"dirty"===t.value?ds(r.value):r});{if("aborted"===t.value)return cs;const r=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===r.status?cs:"dirty"===r.status||"dirty"===t.value?ds(r.value):r}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,n);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===s.common.async){const r=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===r.status?cs:("dirty"===r.status&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(s=>"aborted"===s.status?cs:("dirty"===s.status&&t.dirty(),e(s.value).then(()=>({status:t.value,value:s.value}))))}if("transform"===r.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!ps(e))return cs;const i=r.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>ps(e)?Promise.resolve(r.transform(e.value,n)).then(e=>({status:t.value,value:e})):cs)}Gt.assertNever(r)}}_r.create=(e,t,s)=>new _r({schema:e,typeName:Ar.ZodEffects,effect:t,..._s(s)}),_r.createWithPreprocess=(e,t,s)=>new _r({schema:t,effect:{type:"preprocess",transform:e},typeName:Ar.ZodEffects,..._s(s)});class wr extends ws{_parse(e){return this._getType(e)===ts.undefined?us(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}wr.create=(e,t)=>new wr({innerType:e,typeName:Ar.ZodOptional,..._s(t)});class kr extends ws{_parse(e){return this._getType(e)===ts.null?us(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}kr.create=(e,t)=>new kr({innerType:e,typeName:Ar.ZodNullable,..._s(t)});class xr extends ws{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===ts.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}xr.create=(e,t)=>new xr({innerType:e,typeName:Ar.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,..._s(t)});class jr extends ws{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return ms(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new ns(s.common.issues)},input:s.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new ns(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}jr.create=(e,t)=>new jr({innerType:e,typeName:Ar.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,..._s(t)});class Sr extends ws{_parse(e){if(this._getType(e)!==ts.nan){const t=this._getOrReturnCtx(e);return os(t,{code:rs.invalid_type,expected:ts.nan,received:t.parsedType}),cs}return{status:"valid",value:e.data}}}Sr.create=e=>new Sr({typeName:Ar.ZodNaN,..._s(e)});class Tr extends ws{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class Er extends ws{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?cs:"dirty"===e.status?(t.dirty(),ds(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})()}{const e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?cs:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(e,t){return new Er({in:e,out:t,typeName:Ar.ZodPipeline})}}class Or extends ws{_parse(e){const t=this._def.innerType._parse(e),s=e=>(ps(e)&&(e.value=Object.freeze(e.value)),e);return ms(t)?t.then(e=>s(e)):s(t)}unwrap(){return this._def.innerType}}var Ar,Cr;Or.create=(e,t)=>new Or({innerType:e,typeName:Ar.ZodReadonly,..._s(t)}),ar.lazycreate,(Cr=Ar||(Ar={})).ZodString="ZodString",Cr.ZodNumber="ZodNumber",Cr.ZodNaN="ZodNaN",Cr.ZodBigInt="ZodBigInt",Cr.ZodBoolean="ZodBoolean",Cr.ZodDate="ZodDate",Cr.ZodSymbol="ZodSymbol",Cr.ZodUndefined="ZodUndefined",Cr.ZodNull="ZodNull",Cr.ZodAny="ZodAny",Cr.ZodUnknown="ZodUnknown",Cr.ZodNever="ZodNever",Cr.ZodVoid="ZodVoid",Cr.ZodArray="ZodArray",Cr.ZodObject="ZodObject",Cr.ZodUnion="ZodUnion",Cr.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Cr.ZodIntersection="ZodIntersection",Cr.ZodTuple="ZodTuple",Cr.ZodRecord="ZodRecord",Cr.ZodMap="ZodMap",Cr.ZodSet="ZodSet",Cr.ZodFunction="ZodFunction",Cr.ZodLazy="ZodLazy",Cr.ZodLiteral="ZodLiteral",Cr.ZodEnum="ZodEnum",Cr.ZodEffects="ZodEffects",Cr.ZodNativeEnum="ZodNativeEnum",Cr.ZodOptional="ZodOptional",Cr.ZodNullable="ZodNullable",Cr.ZodDefault="ZodDefault",Cr.ZodCatch="ZodCatch",Cr.ZodPromise="ZodPromise",Cr.ZodBranded="ZodBranded",Cr.ZodPipeline="ZodPipeline",Cr.ZodReadonly="ZodReadonly";const Nr=Ws.create,Rr=Ks.create;Sr.create,Js.create;const Ir=Hs.create;Gs.create,Ys.create,Qs.create,Xs.create,er.create,tr.create,sr.create,rr.create;const Pr=nr.create,$r=ar.create;ar.strictCreate;const Dr=or.create;cr.create,dr.create;const Ur=ur.create;hr.create,fr.create,pr.create;const Lr=mr.create,Vr=yr.create;vr.create,br.create,_r.create,wr.create,kr.create,_r.createWithPreprocess;const Fr=a,Br=o,qr=l,Mr=D.forwardRef(({className:s,...r},n)=>e.jsx(t,{ref:n,className:W("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...r}));Mr.displayName=t.displayName;const zr=D.forwardRef(({className:t,children:n,...i},a)=>e.jsxs(qr,{children:[e.jsx(Mr,{}),e.jsxs(s,{ref:a,className:W("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...i,children:[n,e.jsxs(r,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-accent data-[state=open]:text-muted-foreground hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[e.jsx(Z,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));zr.displayName=s.displayName;const Wr=({className:t,...s})=>e.jsx("div",{className:W("flex flex-col space-y-1.5 text-center sm:text-left",t),...s});Wr.displayName="DialogHeader";const Zr=D.forwardRef(({className:t,...s},r)=>e.jsx(n,{ref:r,className:W("text-lg font-semibold leading-none tracking-tight",t),...s}));Zr.displayName=n.displayName;const Kr=D.forwardRef(({className:t,...s},r)=>e.jsx(i,{ref:r,className:W("text-sm text-muted-foreground",t),...s}));Kr.displayName=i.displayName;const Jr=D.forwardRef(({className:t,...s},r)=>e.jsx("textarea",{className:W("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),ref:r,...s}));Jr.displayName="Textarea";var Hr="Radio",[Gr,Yr]=w(Hr),[Qr,Xr]=Gr(Hr),en=D.forwardRef((t,s)=>{const{__scopeRadio:r,name:n,checked:i=!1,required:a,disabled:o,value:l="on",onCheck:c,form:d,...u}=t,[h,f]=D.useState(null),p=k(s,e=>f(e)),m=D.useRef(!1),g=!h||(d||!!h.closest("form"));return e.jsxs(Qr,{scope:r,checked:i,disabled:o,children:[e.jsx(x.button,{type:"button",role:"radio","aria-checked":i,"data-state":nn(i),"data-disabled":o?"":void 0,disabled:o,value:l,...u,ref:p,onClick:j(t.onClick,e=>{i||c?.(),g&&(m.current=e.isPropagationStopped(),m.current||e.stopPropagation())})}),g&&e.jsx(rn,{control:h,bubbles:!m.current,name:n,value:l,checked:i,required:a,disabled:o,form:d,style:{transform:"translateX(-100%)"}})]})});en.displayName=Hr;var tn="RadioIndicator",sn=D.forwardRef((t,s)=>{const{__scopeRadio:r,forceMount:n,...i}=t,a=Xr(tn,r);return e.jsx(S,{present:n||a.checked,children:e.jsx(x.span,{"data-state":nn(a.checked),"data-disabled":a.disabled?"":void 0,...i,ref:s})})});sn.displayName=tn;var rn=D.forwardRef(({__scopeRadio:t,control:s,checked:r,bubbles:n=!0,...i},a)=>{const o=D.useRef(null),l=k(o,a),c=T(r),d=E(s);return D.useEffect(()=>{const e=o.current;if(!e)return;const t=window.HTMLInputElement.prototype,s=Object.getOwnPropertyDescriptor(t,"checked").set;if(c!==r&&s){const t=new Event("click",{bubbles:n});s.call(e,r),e.dispatchEvent(t)}},[c,r,n]),e.jsx(x.input,{type:"radio","aria-hidden":!0,defaultChecked:r,...i,tabIndex:-1,ref:l,style:{...i.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});function nn(e){return e?"checked":"unchecked"}rn.displayName="RadioBubbleInput";var an=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],on="RadioGroup",[ln,cn]=w(on,[O,Yr]),dn=O(),un=Yr(),[hn,fn]=ln(on),pn=D.forwardRef((t,s)=>{const{__scopeRadioGroup:r,name:n,defaultValue:i,value:a,required:o=!1,disabled:l=!1,orientation:c,dir:d,loop:u=!0,onValueChange:h,...f}=t,p=dn(r),m=A(d),[g,y]=C({prop:a,defaultProp:i??null,onChange:h,caller:on});return e.jsx(hn,{scope:r,name:n,required:o,disabled:l,value:g,onValueChange:y,children:e.jsx(N,{asChild:!0,...p,orientation:c,dir:m,loop:u,children:e.jsx(x.div,{role:"radiogroup","aria-required":o,"aria-orientation":c,"data-disabled":l?"":void 0,dir:m,...f,ref:s})})})});pn.displayName=on;var mn="RadioGroupItem",gn=D.forwardRef((t,s)=>{const{__scopeRadioGroup:r,disabled:n,...i}=t,a=fn(mn,r),o=a.disabled||n,l=dn(r),c=un(r),d=D.useRef(null),u=k(s,d),h=a.value===i.value,f=D.useRef(!1);return D.useEffect(()=>{const e=e=>{an.includes(e.key)&&(f.current=!0)},t=()=>f.current=!1;return document.addEventListener("keydown",e),document.addEventListener("keyup",t),()=>{document.removeEventListener("keydown",e),document.removeEventListener("keyup",t)}},[]),e.jsx(R,{asChild:!0,...l,focusable:!o,active:h,children:e.jsx(en,{disabled:o,required:a.required,checked:h,...c,...i,name:a.name,ref:u,onCheck:()=>a.onValueChange(i.value),onKeyDown:j(e=>{"Enter"===e.key&&e.preventDefault()}),onFocus:j(i.onFocus,()=>{f.current&&d.current?.click()})})})});gn.displayName=mn;var yn=D.forwardRef((t,s)=>{const{__scopeRadioGroup:r,...n}=t,i=un(r);return e.jsx(sn,{...i,...n,ref:s})});yn.displayName="RadioGroupIndicator";var vn=pn,bn=gn,_n=yn;const wn=D.forwardRef(({className:t,...s},r)=>e.jsx(vn,{className:W("grid gap-2",t),...s,ref:r}));wn.displayName=vn.displayName;const kn=D.forwardRef(({className:t,...s},r)=>e.jsx(bn,{ref:r,className:W("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(_n,{className:"flex items-center justify-center",children:e.jsx(le,{className:"h-2.5 w-2.5 fill-current text-current"})})}));kn.displayName=bn.displayName;class xn extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class jn extends xn{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Sn extends xn{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Tn extends xn{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var En,On;(On=En||(En={})).Any="any",On.ApNortheast1="ap-northeast-1",On.ApNortheast2="ap-northeast-2",On.ApSouth1="ap-south-1",On.ApSoutheast1="ap-southeast-1",On.ApSoutheast2="ap-southeast-2",On.CaCentral1="ca-central-1",On.EuCentral1="eu-central-1",On.EuWest1="eu-west-1",On.EuWest2="eu-west-2",On.EuWest3="eu-west-3",On.SaEast1="sa-east-1",On.UsEast1="us-east-1",On.UsWest1="us-west-1",On.UsWest2="us-west-2";class An{constructor(e,{headers:t={},customFetch:s,region:r=En.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=(e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>J(async()=>{const{default:e}=await Promise.resolve().then(()=>Mn);return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)})(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return I(this,arguments,void 0,function*(e,t={}){var s;try{const{headers:r,method:n,body:i,signal:a}=t;let o={},{region:l}=t;l||(l=this.region);const c=new URL(`${this.url}/${e}`);let d;l&&"any"!==l&&(o["x-region"]=l,c.searchParams.set("forceFunctionRegion",l)),i&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)?"undefined"!=typeof Blob&&i instanceof Blob||i instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",d=i):"string"==typeof i?(o["Content-Type"]="text/plain",d=i):"undefined"!=typeof FormData&&i instanceof FormData?d=i:(o["Content-Type"]="application/json",d=JSON.stringify(i)):d=i;const u=yield this.fetch(c.toString(),{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),r),body:d,signal:a}).catch(e=>{if("AbortError"===e.name)throw e;throw new jn(e)}),h=u.headers.get("x-relay-error");if(h&&"true"===h)throw new Sn(u);if(!u.ok)throw new Tn(u);let f,p=(null!==(s=u.headers.get("Content-Type"))&&void 0!==s?s:"text/plain").split(";")[0].trim();return f="application/json"===p?yield u.json():"application/octet-stream"===p||"application/pdf"===p?yield u.blob():"text/event-stream"===p?u:"multipart/form-data"===p?yield u.formData():yield u.text(),{data:f,error:null,response:u}}catch(r){return r instanceof Error&&"AbortError"===r.name?{data:null,error:new jn(r)}:{data:null,error:r,response:r instanceof Tn||r instanceof Sn?r.context:void 0}}})}}var Cn={};const Nn=L(P);var Rn={},In={},Pn={},$n={},Dn={},Un=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("unable to locate global object")}();const Ln=Un.fetch,Vn=Un.fetch.bind(Un),Fn=Un.Headers,Bn=Un.Request,qn=Un.Response,Mn=Object.freeze(Object.defineProperty({__proto__:null,Headers:Fn,Request:Bn,Response:qn,default:Vn,fetch:Ln},Symbol.toStringTag,{value:"Module"})),zn=L(Mn);var Wn,Zn,Kn,Jn,Hn,Gn,Yn={};function Qn(){if(Wn)return Yn;Wn=1,Object.defineProperty(Yn,"__esModule",{value:!0});class e extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}}return Yn.default=e,Yn}function Xn(){if(Zn)return Dn;Zn=1,Object.defineProperty(Dn,"__esModule",{value:!0});const e=Nn,t=e.__importDefault(zn),s=e.__importDefault(Qn());return Dn.default=class{constructor(e){var s,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(s=e.shouldThrowOnError)&&void 0!==s&&s,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,e.fetch?this.fetch=e.fetch:"undefined"==typeof fetch?this.fetch=t.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let r=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{var t,r,n,i;let a=null,o=null,l=null,c=e.status,d=e.statusText;if(e.ok){if("HEAD"!==this.method){const s=await e.text();""===s||(o="text/csv"===this.headers.get("Accept")||this.headers.get("Accept")&&(null===(t=this.headers.get("Accept"))||void 0===t?void 0:t.includes("application/vnd.pgrst.plan+text"))?s:JSON.parse(s))}const s=null===(r=this.headers.get("Prefer"))||void 0===r?void 0:r.match(/count=(exact|planned|estimated)/),i=null===(n=e.headers.get("content-range"))||void 0===n?void 0:n.split("/");s&&i&&i.length>1&&(l=parseInt(i[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,l=null,c=406,d="Not Acceptable"):o=1===o.length?o[0]:null)}else{const t=await e.text();try{a=JSON.parse(t),Array.isArray(a)&&404===e.status&&(o=[],a=null,c=200,d="OK")}catch(u){404===e.status&&""===t?(c=204,d="No Content"):a={message:t}}if(a&&this.isMaybeSingle&&(null===(i=null==a?void 0:a.details)||void 0===i?void 0:i.includes("0 rows"))&&(a=null,c=200,d="OK"),a&&this.shouldThrowOnError)throw new s.default(a)}return{error:a,data:o,count:l,status:c,statusText:d}});return this.shouldThrowOnError||(r=r.catch(e=>{var t,s,r;return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:`${null!==(s=null==e?void 0:e.stack)&&void 0!==s?s:""}`,hint:"",code:`${null!==(r=null==e?void 0:e.code)&&void 0!==r?r:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}returns(){return this}overrideTypes(){return this}},Dn}function ei(){if(Kn)return $n;Kn=1,Object.defineProperty($n,"__esModule",{value:!0});const e=Nn.__importDefault(Xn());class t extends e.default{select(e){let t=!1;const s=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",s),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:r,referencedTable:n=r}={}){const i=n?`${n}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===s?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){const r=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){const n=void 0===r?"offset":`${r}.offset`,i=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(i,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:r=!1,wal:n=!1,format:i="text"}={}){var a;const o=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=null!==(a=this.headers.get("Accept"))&&void 0!==a?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${o};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}}return $n.default=t,$n}function ti(){if(Jn)return Pn;Jn=1,Object.defineProperty(Pn,"__esModule",{value:!0});const e=Nn.__importDefault(ei()),t=new RegExp("[,()]");class s extends e.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,s){const r=Array.from(new Set(s)).map(e=>"string"==typeof e&&t.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return"string"==typeof t?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"string"==typeof t?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"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:s,type:r}={}){let n="";"plain"===r?n="pl":"phrase"===r?n="ph":"websearch"===r&&(n="w");const i=void 0===s?"":`(${s})`;return this.url.searchParams.append(e,`${n}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t,referencedTable:s=t}={}){const r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}}return Pn.default=s,Pn}function si(){if(Hn)return In;Hn=1,Object.defineProperty(In,"__esModule",{value:!0});const e=Nn.__importDefault(ti());return In.default=class{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=new Headers(t),this.schema=s,this.fetch=r}select(t,s){const{head:r=!1,count:n}=null!=s?s:{},i=r?"HEAD":"GET";let a=!1;const o=(null!=t?t:"*").split("").map(e=>/\s/.test(e)&&!a?"":('"'===e&&(a=!a),e)).join("");return this.url.searchParams.set("select",o),n&&this.headers.append("Prefer",`count=${n}`),new e.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(t,{count:s,defaultToNull:r=!0}={}){var n;if(s&&this.headers.append("Prefer",`count=${s}`),r||this.headers.append("Prefer","missing=default"),Array.isArray(t)){const e=t.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(e.length>0){const t=[...new Set(e)].map(e=>`"${e}"`);this.url.searchParams.set("columns",t.join(","))}}return new e.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch})}upsert(t,{onConflict:s,ignoreDuplicates:r=!1,count:n,defaultToNull:i=!0}={}){var a;if(this.headers.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==s&&this.url.searchParams.set("on_conflict",s),n&&this.headers.append("Prefer",`count=${n}`),i||this.headers.append("Prefer","missing=default"),Array.isArray(t)){const e=t.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(e.length>0){const t=[...new Set(e)].map(e=>`"${e}"`);this.url.searchParams.set("columns",t.join(","))}}return new e.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:null!==(a=this.fetch)&&void 0!==a?a:fetch})}update(t,{count:s}={}){var r;return s&&this.headers.append("Prefer",`count=${s}`),new e.default({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}delete({count:t}={}){var s;return t&&this.headers.append("Prefer",`count=${t}`),new e.default({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:null!==(s=this.fetch)&&void 0!==s?s:fetch})}},In}Object.defineProperty(Cn,"__esModule",{value:!0});var ri=Cn.PostgrestError=Cn.PostgrestBuilder=Cn.PostgrestTransformBuilder=Cn.PostgrestFilterBuilder=Cn.PostgrestQueryBuilder=Cn.PostgrestClient=void 0;const ni=Nn,ii=ni.__importDefault(function(){if(Gn)return Rn;Gn=1,Object.defineProperty(Rn,"__esModule",{value:!0});const e=Nn,t=e.__importDefault(si()),s=e.__importDefault(ti());class r{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=new Headers(t),this.schemaName=s,this.fetch=r}from(e){const s=new URL(`${this.url}/${e}`);return new t.default(s,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:n=!1,count:i}={}){var a;let o;const l=new URL(`${this.url}/rpc/${e}`);let c;r||n?(o=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{l.searchParams.append(e,t)})):(o="POST",c=t);const d=new Headers(this.headers);return i&&d.set("Prefer",`count=${i}`),new s.default({method:o,url:l,headers:d,schema:this.schemaName,body:c,fetch:null!==(a=this.fetch)&&void 0!==a?a:fetch})}}return Rn.default=r,Rn}());var ai=Cn.PostgrestClient=ii.default;const oi=ni.__importDefault(si());var li=Cn.PostgrestQueryBuilder=oi.default;const ci=ni.__importDefault(ti());var di=Cn.PostgrestFilterBuilder=ci.default;const ui=ni.__importDefault(ei());var hi=Cn.PostgrestTransformBuilder=ui.default;const fi=ni.__importDefault(Xn());var pi=Cn.PostgrestBuilder=fi.default;const mi=ni.__importDefault(Qn());ri=Cn.PostgrestError=mi.default;var gi=Cn.default={PostgrestClient:ii.default,PostgrestQueryBuilder:oi.default,PostgrestFilterBuilder:ci.default,PostgrestTransformBuilder:ui.default,PostgrestBuilder:fi.default,PostgrestError:mi.default};const yi=ie({__proto__:null,get PostgrestBuilder(){return pi},get PostgrestClient(){return ai},get PostgrestError(){return ri},get PostgrestFilterBuilder(){return di},get PostgrestQueryBuilder(){return li},get PostgrestTransformBuilder(){return hi},default:gi},[Cn]),{PostgrestClient:vi,PostgrestQueryBuilder:bi,PostgrestFilterBuilder:_i,PostgrestTransformBuilder:wi,PostgrestBuilder:ki,PostgrestError:xi}=gi||yi;class ji{static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",constructor:WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if("undefined"!=typeof global&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&globalThis.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if("undefined"!=typeof process){const e=process.versions;if(e&&e.node){const t=e.node,s=parseInt(t.replace(/^v/,"").split(".")[0]);return s>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}const Si=1e4;var Ti,Ei,Oi,Ai,Ci,Ni,Ri,Ii,Pi,$i,Di;(Ei=Ti||(Ti={}))[Ei.connecting=0]="connecting",Ei[Ei.open=1]="open",Ei[Ei.closing=2]="closing",Ei[Ei.closed=3]="closed",(Ai=Oi||(Oi={})).closed="closed",Ai.errored="errored",Ai.joined="joined",Ai.joining="joining",Ai.leaving="leaving",(Ni=Ci||(Ci={})).close="phx_close",Ni.error="phx_error",Ni.join="phx_join",Ni.reply="phx_reply",Ni.leave="phx_leave",Ni.access_token="access_token",(Ri||(Ri={})).websocket="websocket",(Pi=Ii||(Ii={})).Connecting="connecting",Pi.Open="open",Pi.Closing="closing",Pi.Closed="closed";class Ui{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t("string"==typeof e?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){const r=t.getUint8(1),n=t.getUint8(2);let i=this.HEADER_LENGTH+2;const a=s.decode(e.slice(i,i+r));i+=r;const o=s.decode(e.slice(i,i+n));i+=n;return{ref:null,topic:a,event:o,payload:JSON.parse(s.decode(e.slice(i,e.byteLength)))}}}class Li{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}(Di=$i||($i={})).abstime="abstime",Di.bool="bool",Di.date="date",Di.daterange="daterange",Di.float4="float4",Di.float8="float8",Di.int2="int2",Di.int4="int4",Di.int4range="int4range",Di.int8="int8",Di.int8range="int8range",Di.json="json",Di.jsonb="jsonb",Di.money="money",Di.numeric="numeric",Di.oid="oid",Di.reltime="reltime",Di.text="text",Di.time="time",Di.timestamp="timestamp",Di.timestamptz="timestamptz",Di.timetz="timetz",Di.tsrange="tsrange",Di.tstzrange="tstzrange";const Vi=(e,t,s={})=>{var r;const n=null!==(r=s.skipTypes)&&void 0!==r?r:[];return t?Object.keys(t).reduce((s,r)=>(s[r]=Fi(r,e,t,n),s),{}):{}},Fi=(e,t,s,r)=>{const n=t.find(t=>t.name===e),i=null==n?void 0:n.type,a=s[e];return i&&!r.includes(i)?Bi(i,a):qi(a)},Bi=(e,t)=>{if("_"===e.charAt(0)){const s=e.slice(1,e.length);return Zi(t,s)}switch(e){case $i.bool:return Mi(t);case $i.float4:case $i.float8:case $i.int2:case $i.int4:case $i.int8:case $i.numeric:case $i.oid:return zi(t);case $i.json:case $i.jsonb:return Wi(t);case $i.timestamp:return Ki(t);case $i.abstime:case $i.date:case $i.daterange:case $i.int4range:case $i.int8range:case $i.money:case $i.reltime:case $i.text:case $i.time:case $i.timestamptz:case $i.timetz:case $i.tsrange:case $i.tstzrange:default:return qi(t)}},qi=e=>e,Mi=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},zi=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},Wi=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}return e},Zi=(e,t)=>{if("string"!=typeof e)return e;const s=e.length-1,r=e[s];if("{"===e[0]&&"}"===r){let r;const i=e.slice(1,s);try{r=JSON.parse("["+i+"]")}catch(n){r=i?i.split(","):[]}return r.map(e=>Bi(t,e))}return e},Ki=e=>"string"==typeof e?e.replace(" ","T"):e,Ji=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class Hi{constructor(e,t,s={},r=1e4){this.channel=e,this.event=t,this.payload=s,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t(null===(s=this.receivedResp)||void 0===s?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(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(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var Gi,Yi,Qi,Xi,ea,ta,sa,ra;(Yi=Gi||(Gi={})).SYNC="sync",Yi.JOIN="join",Yi.LEAVE="leave";class na{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},e=>{const{onJoin:t,onLeave:s,onSync:r}=this.caller;this.joinRef=this.channel._joinRef(),this.state=na.syncState(this.state,e,t,s),this.pendingDiffs.forEach(e=>{this.state=na.syncDiff(this.state,e,t,s)}),this.pendingDiffs=[],r()}),this.channel._on(s.diff,{},e=>{const{onJoin:t,onLeave:s,onSync:r}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=na.syncDiff(this.state,e,t,s),r())}),this.onJoin((e,t,s)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:s})}),this.onLeave((e,t,s)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:s})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,r){const n=this.cloneDeep(e),i=this.transformState(t),a={},o={};return this.map(n,(e,t)=>{i[e]||(o[e]=t)}),this.map(i,(e,t)=>{const s=n[e];if(s){const r=t.map(e=>e.presence_ref),n=s.map(e=>e.presence_ref),i=t.filter(e=>n.indexOf(e.presence_ref)<0),l=s.filter(e=>r.indexOf(e.presence_ref)<0);i.length>0&&(a[e]=i),l.length>0&&(o[e]=l)}else a[e]=t}),this.syncDiff(n,{joins:a,leaves:o},s,r)}static syncDiff(e,t,s,r){const{joins:n,leaves:i}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(n,(t,r)=>{var n;const i=null!==(n=e[t])&&void 0!==n?n:[];if(e[t]=this.cloneDeep(r),i.length>0){const s=e[t].map(e=>e.presence_ref),r=i.filter(e=>s.indexOf(e.presence_ref)<0);e[t].unshift(...r)}s(t,i,r)}),this.map(i,(t,s)=>{let n=e[t];if(!n)return;const i=s.map(e=>e.presence_ref);n=n.filter(e=>i.indexOf(e.presence_ref)<0),e[t]=n,r(t,n,s),0===n.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{const r=e[s];return t[s]="metas"in r?r.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):r,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}(Xi=Qi||(Qi={})).ALL="*",Xi.INSERT="INSERT",Xi.UPDATE="UPDATE",Xi.DELETE="DELETE",(ta=ea||(ea={})).BROADCAST="broadcast",ta.PRESENCE="presence",ta.POSTGRES_CHANGES="postgres_changes",ta.SYSTEM="system",(ra=sa||(sa={})).SUBSCRIBED="SUBSCRIBED",ra.TIMED_OUT="TIMED_OUT",ra.CLOSED="CLOSED",ra.CHANNEL_ERROR="CHANNEL_ERROR";class ia{constructor(e,t={config:{}},s){var r,n;if(this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=Oi.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new Hi(this,Ci.join,this.params,this.timeout),this.rejoinTimer=new Li(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Oi.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=Oi.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=Oi.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Oi.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=Oi.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Ci.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new na(this),this.broadcastEndpointURL=Ji(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null===(n=null===(r=this.params.config)||void 0===r?void 0:r.broadcast)||void 0===n?void 0:n.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var s,r,n;if(this.socket.isConnected()||this.socket.connect(),this.state==Oi.closed){const{config:{broadcast:i,presence:a,private:o}}=this.params,l=null!==(r=null===(s=this.bindings.postgres_changes)||void 0===s?void 0:s.map(e=>e.filter))&&void 0!==r?r:[],c=!!this.bindings[ea.PRESENCE]&&this.bindings[ea.PRESENCE].length>0||!0===(null===(n=this.params.config.presence)||void 0===n?void 0:n.enabled),d={},u={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:l,private:o};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(sa.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(sa.CLOSED)),this.updateJoinPayload(Object.assign({config:u},d)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var s;if(this.socket.setAuth(),void 0!==t){const r=this.bindings.postgres_changes,n=null!==(s=null==r?void 0:r.length)&&void 0!==s?s:0,i=[];for(let s=0;s<n;s++){const n=r[s],{filter:{event:a,schema:o,table:l,filter:c}}=n,d=t&&t[s];if(!d||d.event!==a||d.schema!==o||d.table!==l||d.filter!==c)return this.unsubscribe(),this.state=Oi.errored,void(null==e||e(sa.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));i.push(Object.assign(Object.assign({},n),{id:d.id}))}return this.bindings.postgres_changes=i,void(e&&e(sa.SUBSCRIBED))}null==e||e(sa.SUBSCRIBED)}).receive("error",t=>{this.state=Oi.errored,null==e||e(sa.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(sa.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this.state===Oi.joined&&e===ea.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,t,s)}async httpSend(e,t,s={}){var r;const n=this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"";if(null==t)return Promise.reject("Payload is required for httpSend()");const i={method:"POST",headers:{Authorization:n,apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,null!==(r=s.timeout)&&void 0!==r?r:this.timeout);if(202===a.status)return{success:!0};let o=a.statusText;try{const e=await a.json();o=e.error||e.message||o}catch(l){}return Promise.reject(new Error(o))}async send(e,t={}){var s,r;if(this._canPush()||"broadcast"!==e.type)return new Promise(s=>{var r,n,i;const a=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(i=null===(n=null===(r=this.params)||void 0===r?void 0:r.config)||void 0===n?void 0:n.broadcast)||void 0===i?void 0:i.ack)||s("ok"),a.receive("ok",()=>s("ok")),a.receive("error",()=>s("error")),a.receive("timeout",()=>s("timed out"))});{const{event:i,payload:a}=e,o={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:a,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,null!==(s=t.timeout)&&void 0!==s?s:this.timeout);return await(null===(r=e.body)||void 0===r?void 0:r.cancel()),e.ok?"ok":"error"}catch(n){return"AbortError"===n.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=Oi.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Ci.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(r=>{s=new Hi(this,Ci.leave,{},e),s.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{null==s||s.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Oi.closed,this.bindings={}}async _fetchWithTimeout(e,t,s){const r=new AbortController,n=setTimeout(()=>r.abort(),s),i=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(n),i}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new Hi(this,e,t,s);return this._canPush()?r.send():this._addToPushBuffer(r),r}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){const e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,n;const i=e.toLocaleLowerCase(),{close:a,error:o,leave:l,join:c}=Ci;if(s&&[a,o,l,c].indexOf(i)>=0&&s!==this._joinRef())return;let d=this._onMessage(i,t,s);if(t&&!d)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(i)?null===(r=this.bindings.postgres_changes)||void 0===r||r.filter(e=>{var t,s,r;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(r=null===(s=e.filter)||void 0===s?void 0:s.event)||void 0===r?void 0:r.toLocaleLowerCase())===i}).map(e=>e.callback(d,s)):null===(n=this.bindings[i])||void 0===n||n.filter(e=>{var s,r,n,a,o,l;if(["broadcast","presence","postgres_changes"].includes(i)){if("id"in e){const i=e.id,a=null===(s=e.filter)||void 0===s?void 0:s.event;return i&&(null===(r=t.ids)||void 0===r?void 0:r.includes(i))&&("*"===a||(null==a?void 0:a.toLocaleLowerCase())===(null===(n=t.data)||void 0===n?void 0:n.type.toLocaleLowerCase()))}{const s=null===(o=null===(a=null==e?void 0:e.filter)||void 0===a?void 0:a.event)||void 0===o?void 0:o.toLocaleLowerCase();return"*"===s||s===(null===(l=null==t?void 0:t.event)||void 0===l?void 0:l.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===i}).map(e=>{if("object"==typeof d&&"ids"in d){const e=d.data,{schema:t,table:s,commit_timestamp:r,type:n,errors:i}=e,a={schema:t,table:s,commit_timestamp:r,eventType:n,new:{},old:{},errors:i};d=Object.assign(Object.assign({},a),this._getPayloadRecords(e))}e.callback(d,s)})}_isClosed(){return this.state===Oi.closed}_isJoined(){return this.state===Oi.joined}_isJoining(){return this.state===Oi.joining}_isLeaving(){return this.state===Oi.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){const r=e.toLocaleLowerCase(),n={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(n):this.bindings[r]=[n],this}_off(e,t){const s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(e=>{var r;return!((null===(r=e.type)||void 0===r?void 0:r.toLocaleLowerCase())===s&&ia.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Ci.close,{},e)}_onError(e){this._on(Ci.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Oi.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=Vi(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=Vi(e.columns,e.old_record)),t}}const aa=()=>{},oa=25e3,la=10,ca=100,da=[1e3,2e3,5e3,1e4];class ua{constructor(e,t){var s;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=Si,this.transport=null,this.heartbeatIntervalMs=oa,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=aa,this.ref=0,this.reconnectTimer=null,this.logger=aa,this.conn=null,this.sendBuffer=[],this.serializer=new Ui,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>J(async()=>{const{default:e}=await Promise.resolve().then(()=>Mn);return{default:e}},void 0).then(({default:t})=>t(...e)).catch(e=>{throw new Error(`Failed to load @supabase/node-fetch: ${e.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):fetch),(...e)=>t(...e)},!(null===(s=null==t?void 0:t.params)||void 0===s?void 0:s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Ri.websocket}`,this.httpEndpoint=Ji(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=ji.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;if(t.includes("Node.js"))throw new Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n  npm install ws\n\n  import ws from "ws"\n  const client = new RealtimeClient(url, {\n    ...options,\n    transport: ws\n  })`);throw new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:"1.0.0"}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const s=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(s),this._setConnectionState("disconnected")},e?this.conn.close(e,null!=t?t:""):this.conn.close(),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case Ti.connecting:return Ii.Connecting;case Ti.open:return Ii.Open;case Ti.closing:return Ii.Closing;default:return Ii.Closed}}isConnected(){return this.connectionState()===Ii.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){const s=`realtime:${e}`,r=this.getChannels().find(e=>e.topic===s);if(r)return r;{const s=new ia(`realtime:${e}`,t,this);return this.channels.push(s),s}}push(e){const{topic:t,event:s,payload:r,ref:n}=e,i=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${s} (${n})`,r),this.isConnected()?i():this.sendBuffer.push(i)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}return this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),void setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},ca)}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}else try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}}onHeartbeat(e){this.heartbeatCallback=e}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(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event)try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error")}catch(o){this.log("error","error in heartbeat callback",o)}e.ref&&e.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:t,event:s,payload:r,ref:n}=e,i=n?`(${n})`:"",a=r.status||"";this.log("receive",`${a} ${t} ${s} ${i}`.trim(),r),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(s,r,n)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null===(t=this.reconnectTimer)||void 0===t||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){this.conn&&(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null),this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this.workerRef.terminate()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null===(t=this.reconnectTimer)||void 0===t||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(Ci.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const s=e.match(/\?/)?"&":"?";return`${e}${s}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n  addEventListener("message", (e) => {\n    if (e.data.event === "start") {\n      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n    }\n  });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;t=e||(this.accessToken?await this.accessToken():this.accessTokenValue),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{const s={access_token:t,version:"realtime-js/2.77.0"};t&&e.updateJoinPayload(s),e.joinedOnce&&e._isJoined()&&e._push(Ci.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this.setAuth().catch(t=>{this.log("error",`error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(s=>{try{s(t)}catch(r){this.log("error",`error in ${e} callback`,r)}})}catch(s){this.log("error",`error triggering ${e} callbacks`,s)}}_setupReconnectionTimer(){this.reconnectTimer=new Li(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},la)},this.reconnectAfterMs)}_initializeOptions(e){var t,s,r,n,i,a,o,l,c;if(this.transport=null!==(t=null==e?void 0:e.transport)&&void 0!==t?t:null,this.timeout=null!==(s=null==e?void 0:e.timeout)&&void 0!==s?s:Si,this.heartbeatIntervalMs=null!==(r=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==r?r:oa,this.worker=null!==(n=null==e?void 0:e.worker)&&void 0!==n&&n,this.accessToken=null!==(i=null==e?void 0:e.accessToken)&&void 0!==i?i:null,this.heartbeatCallback=null!==(a=null==e?void 0:e.heartbeatCallback)&&void 0!==a?a:aa,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!==(o=null==e?void 0:e.reconnectAfterMs)&&void 0!==o?o:e=>da[e-1]||1e4,this.encode=null!==(l=null==e?void 0:e.encode)&&void 0!==l?l:(e,t)=>t(JSON.stringify(e)),this.decode=null!==(c=null==e?void 0:e.decode)&&void 0!==c?c:this.serializer.decode.bind(this.serializer),this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}class ha extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function fa(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class pa extends ha{constructor(e,t,s){super(e),this.name="StorageApiError",this.status=t,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class ma extends ha{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}const ga=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>J(async()=>{const{default:e}=await Promise.resolve().then(()=>Mn);return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},ya=e=>{if(Array.isArray(e))return e.map(e=>ya(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,s])=>{const r=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[r]=ya(s)}),t},va=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),ba=(e,t,s)=>I(void 0,void 0,void 0,function*(){const r=yield I(void 0,void 0,void 0,function*(){return"undefined"==typeof Response?(yield J(()=>Promise.resolve().then(()=>Mn),void 0)).Response:Response});e instanceof r&&!(null==s?void 0:s.noResolveJson)?e.json().then(s=>{const r=e.status||500,n=(null==s?void 0:s.statusCode)||r+"";t(new pa(va(s),r,n))}).catch(e=>{t(new ma(va(e),e))}):t(new ma(va(e),e))}),_a=(e,t,s,r)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&r?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(r)?(n.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),n.body=JSON.stringify(r)):n.body=r,(null==t?void 0:t.duplex)&&(n.duplex=t.duplex),Object.assign(Object.assign({},n),s)):n};function wa(e,t,s,r,n,i){return I(this,void 0,void 0,function*(){return new Promise((a,o)=>{e(s,_a(t,r,n,i)).then(e=>{if(!e.ok)throw e;return(null==r?void 0:r.noResolveJson)?e:e.json()}).then(e=>a(e)).catch(e=>ba(e,o,r))})})}function ka(e,t,s,r){return I(this,void 0,void 0,function*(){return wa(e,"GET",t,s,r)})}function xa(e,t,s,r,n){return I(this,void 0,void 0,function*(){return wa(e,"POST",t,r,n,s)})}function ja(e,t,s,r,n){return I(this,void 0,void 0,function*(){return wa(e,"PUT",t,r,n,s)})}function Sa(e,t,s,r,n){return I(this,void 0,void 0,function*(){return wa(e,"DELETE",t,r,n,s)})}class Ta{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return I(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(fa(e))return{data:null,error:e};throw e}})}}var Ea;class Oa{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Ea]="BlobDownloadBuilder",this.promise=null}asStream(){return new Ta(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}execute(){return I(this,void 0,void 0,function*(){try{const e=yield this.downloadFn();return{data:yield e.blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(fa(e))return{data:null,error:e};throw e}})}}Ea=Symbol.toStringTag;const Aa={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ca={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Na{constructor(e,t={},s,r){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=s,this.fetch=ga(r)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,s,r){return I(this,void 0,void 0,function*(){try{let n;const i=Object.assign(Object.assign({},Ca),r);let a=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(i.upsert)});const o=i.metadata;"undefined"!=typeof Blob&&s instanceof Blob?(n=new FormData,n.append("cacheControl",i.cacheControl),o&&n.append("metadata",this.encodeMetadata(o)),n.append("",s)):"undefined"!=typeof FormData&&s instanceof FormData?(n=s,n.append("cacheControl",i.cacheControl),o&&n.append("metadata",this.encodeMetadata(o))):(n=s,a["cache-control"]=`max-age=${i.cacheControl}`,a["content-type"]=i.contentType,o&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(o)))),(null==r?void 0:r.headers)&&(a=Object.assign(Object.assign({},a),r.headers));const l=this._removeEmptyFolders(t),c=this._getFinalPath(l),d=yield("PUT"==e?ja:xa)(this.fetch,`${this.url}/object/${c}`,n,Object.assign({headers:a},(null==i?void 0:i.duplex)?{duplex:i.duplex}:{}));return{data:{path:l,id:d.Id,fullPath:d.Key},error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(fa(n))return{data:null,error:n};throw n}})}upload(e,t,s){return I(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,s)})}uploadToSignedUrl(e,t,s,r){return I(this,void 0,void 0,function*(){const n=this._removeEmptyFolders(e),i=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${i}`);a.searchParams.set("token",t);try{let e;const t=Object.assign({upsert:Ca.upsert},r),i=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});"undefined"!=typeof Blob&&s instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",s)):"undefined"!=typeof FormData&&s instanceof FormData?(e=s,e.append("cacheControl",t.cacheControl)):(e=s,i["cache-control"]=`max-age=${t.cacheControl}`,i["content-type"]=t.contentType);return{data:{path:n,fullPath:(yield ja(this.fetch,a.toString(),e,{headers:i})).Key},error:null}}catch(o){if(this.shouldThrowOnError)throw o;if(fa(o))return{data:null,error:o};throw o}})}createSignedUploadUrl(e,t){return I(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e);const r=Object.assign({},this.headers);(null==t?void 0:t.upsert)&&(r["x-upsert"]="true");const n=yield xa(this.fetch,`${this.url}/object/upload/sign/${s}`,{},{headers:r}),i=new URL(this.url+n.url),a=i.searchParams.get("token");if(!a)throw new ha("No token returned by API");return{data:{signedUrl:i.toString(),path:e,token:a},error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(fa(s))return{data:null,error:s};throw s}})}update(e,t,s){return I(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,s)})}move(e,t,s){return I(this,void 0,void 0,function*(){try{return{data:yield xa(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==s?void 0:s.destinationBucket},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(fa(r))return{data:null,error:r};throw r}})}copy(e,t,s){return I(this,void 0,void 0,function*(){try{return{data:{path:(yield xa(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==s?void 0:s.destinationBucket},{headers:this.headers})).Key},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(fa(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,s){return I(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),n=yield xa(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},(null==s?void 0:s.transform)?{transform:s.transform}:{}),{headers:this.headers});const i=(null==s?void 0:s.download)?`&download=${!0===s.download?"":s.download}`:"";return n={signedUrl:encodeURI(`${this.url}${n.signedURL}${i}`)},{data:n,error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(fa(r))return{data:null,error:r};throw r}})}createSignedUrls(e,t,s){return I(this,void 0,void 0,function*(){try{const r=yield xa(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),n=(null==s?void 0:s.download)?`&download=${!0===s.download?"":s.download}`:"";return{data:r.map(e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${n}`):null})),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(fa(r))return{data:null,error:r};throw r}})}download(e,t){const s=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",r=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),n=r?`?${r}`:"",i=this._getFinalPath(e);return new Oa(()=>ka(this.fetch,`${this.url}/${s}/${i}${n}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}info(e){return I(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const e=yield ka(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:ya(e),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(fa(s))return{data:null,error:s};throw s}})}exists(e){return I(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield function(e,t,s,r){return I(this,void 0,void 0,function*(){return wa(e,"HEAD",t,Object.assign(Object.assign({},s),{noResolveJson:!0}),r)})}(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(fa(s)&&s instanceof ma){const e=s.originalError;if([400,404].includes(null==e?void 0:e.status))return{data:!1,error:s}}throw s}})}getPublicUrl(e,t){const s=this._getFinalPath(e),r=[],n=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==n&&r.push(n);const i=void 0!==(null==t?void 0:t.transform)?"render/image":"object",a=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==a&&r.push(a);let o=r.join("&");return""!==o&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${s}${o}`)}}}remove(e){return I(this,void 0,void 0,function*(){try{return{data:yield Sa(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(fa(t))return{data:null,error:t};throw t}})}list(e,t,s){return I(this,void 0,void 0,function*(){try{const r=Object.assign(Object.assign(Object.assign({},Aa),t),{prefix:e||""});return{data:yield xa(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(fa(r))return{data:null,error:r};throw r}})}listV2(e,t){return I(this,void 0,void 0,function*(){try{const s=Object.assign({},e);return{data:yield xa(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,s,{headers:this.headers},t),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(fa(s))return{data:null,error:s};throw s}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const Ra="2.77.0",Ia={"X-Client-Info":`storage-js/${Ra}`};class Pa{constructor(e,t={},s,r){this.shouldThrowOnError=!1;const n=new URL(e);if(null==r?void 0:r.useNewHostname){/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."))}this.url=n.href.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Ia),t),this.fetch=ga(s)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(e){return I(this,void 0,void 0,function*(){try{const t=this.listBucketOptionsToQueryString(e);return{data:yield ka(this.fetch,`${this.url}/bucket${t}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(fa(t))return{data:null,error:t};throw t}})}getBucket(e){return I(this,void 0,void 0,function*(){try{return{data:yield ka(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(fa(t))return{data:null,error:t};throw t}})}createBucket(e){return I(this,arguments,void 0,function*(e,t={public:!1}){try{return{data:yield xa(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(fa(s))return{data:null,error:s};throw s}})}updateBucket(e,t){return I(this,void 0,void 0,function*(){try{return{data:yield ja(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(fa(s))return{data:null,error:s};throw s}})}emptyBucket(e){return I(this,void 0,void 0,function*(){try{return{data:yield xa(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(fa(t))return{data:null,error:t};throw t}})}deleteBucket(e){return I(this,void 0,void 0,function*(){try{return{data:yield Sa(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(fa(t))return{data:null,error:t};throw t}})}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}}class $a{constructor(e,t={},s){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Ia),t),this.fetch=ga(s)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return I(this,void 0,void 0,function*(){try{return{data:yield xa(this.fetch,`${this.url}/bucket`,{name:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(fa(t))return{data:null,error:t};throw t}})}listBuckets(e){return I(this,void 0,void 0,function*(){try{const t=new URLSearchParams;void 0!==(null==e?void 0:e.limit)&&t.set("limit",e.limit.toString()),void 0!==(null==e?void 0:e.offset)&&t.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&t.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&t.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&t.set("search",e.search);const s=t.toString(),r=s?`${this.url}/bucket?${s}`:`${this.url}/bucket`;return{data:yield ka(this.fetch,r,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(fa(t))return{data:null,error:t};throw t}})}deleteBucket(e){return I(this,void 0,void 0,function*(){try{return{data:yield Sa(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(fa(t))return{data:null,error:t};throw t}})}}const Da={"X-Client-Info":`storage-js/${Ra}`,"Content-Type":"application/json"};class Ua extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}}function La(e){return"object"==typeof e&&null!==e&&"__isStorageVectorsError"in e}class Va extends Ua{constructor(e,t,s){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class Fa extends Ua{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}}var Ba,qa;(qa=Ba||(Ba={})).InternalError="InternalError",qa.S3VectorConflictException="S3VectorConflictException",qa.S3VectorNotFoundException="S3VectorNotFoundException",qa.S3VectorBucketNotEmpty="S3VectorBucketNotEmpty",qa.S3VectorMaxBucketsExceeded="S3VectorMaxBucketsExceeded",qa.S3VectorMaxIndexesExceeded="S3VectorMaxIndexesExceeded";const Ma=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>J(async()=>{const{default:e}=await Promise.resolve().then(()=>Mn);return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},za=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Wa=(e,t,s,r)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return r?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(r)?(n.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),n.body=JSON.stringify(r)):n.body=r,Object.assign(Object.assign({},n),s)):n};function Za(e,t,s,r,n,i){return I(this,void 0,void 0,function*(){return new Promise((a,o)=>{e(s,Wa(t,r,n,i)).then(e=>{if(!e.ok)throw e;if(null==r?void 0:r.noResolveJson)return e;const t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}}).then(e=>a(e)).catch(e=>((e,t,s)=>I(void 0,void 0,void 0,function*(){if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==s?void 0:s.noResolveJson)){const s=e.status||500,r=e;if("function"==typeof r.json)r.json().then(e=>{const r=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||s+"";t(new Va(za(e),s,r))}).catch(()=>{const e=s+"",n=r.statusText||`HTTP ${s} error`;t(new Va(n,s,e))});else{const e=s+"",n=r.statusText||`HTTP ${s} error`;t(new Va(n,s,e))}}else t(new Fa(za(e),e))}))(e,o,r))})})}function Ka(e,t,s,r,n){return I(this,void 0,void 0,function*(){return Za(e,"POST",t,r,n,s)})}class Ja{constructor(e,t={},s){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Da),t),this.fetch=Ma(s)}throwOnError(){return this.shouldThrowOnError=!0,this}createIndex(e){return I(this,void 0,void 0,function*(){try{return{data:(yield Ka(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(La(t))return{data:null,error:t};throw t}})}getIndex(e,t){return I(this,void 0,void 0,function*(){try{return{data:yield Ka(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(La(s))return{data:null,error:s};throw s}})}listIndexes(e){return I(this,void 0,void 0,function*(){try{return{data:yield Ka(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(La(t))return{data:null,error:t};throw t}})}deleteIndex(e,t){return I(this,void 0,void 0,function*(){try{return{data:(yield Ka(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}))||{},error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(La(s))return{data:null,error:s};throw s}})}}class Ha{constructor(e,t={},s){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Da),t),this.fetch=Ma(s)}throwOnError(){return this.shouldThrowOnError=!0,this}putVectors(e){return I(this,void 0,void 0,function*(){try{if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:(yield Ka(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(La(t))return{data:null,error:t};throw t}})}getVectors(e){return I(this,void 0,void 0,function*(){try{return{data:yield Ka(this.fetch,`${this.url}/GetVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(La(t))return{data:null,error:t};throw t}})}listVectors(e){return I(this,void 0,void 0,function*(){try{if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return{data:yield Ka(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(La(t))return{data:null,error:t};throw t}})}queryVectors(e){return I(this,void 0,void 0,function*(){try{return{data:yield Ka(this.fetch,`${this.url}/QueryVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(La(t))return{data:null,error:t};throw t}})}deleteVectors(e){return I(this,void 0,void 0,function*(){try{if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:(yield Ka(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(La(t))return{data:null,error:t};throw t}})}}class Ga{constructor(e,t={},s){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Da),t),this.fetch=Ma(s)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return I(this,void 0,void 0,function*(){try{return{data:(yield Ka(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(La(t))return{data:null,error:t};throw t}})}getBucket(e){return I(this,void 0,void 0,function*(){try{return{data:yield Ka(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(La(t))return{data:null,error:t};throw t}})}listBuckets(){return I(this,arguments,void 0,function*(e={}){try{return{data:yield Ka(this.fetch,`${this.url}/ListVectorBuckets`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(La(t))return{data:null,error:t};throw t}})}deleteBucket(e){return I(this,void 0,void 0,function*(){try{return{data:(yield Ka(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(La(t))return{data:null,error:t};throw t}})}}class Ya extends Ga{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Qa(this.url,this.headers,e,this.fetch)}}class Qa extends Ja{constructor(e,t,s,r){super(e,t,r),this.vectorBucketName=s}createIndex(e){const t=Object.create(null,{createIndex:{get:()=>super.createIndex}});return I(this,void 0,void 0,function*(){return t.createIndex.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName}))})}listIndexes(){const e=Object.create(null,{listIndexes:{get:()=>super.listIndexes}});return I(this,arguments,void 0,function*(t={}){return e.listIndexes.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName}))})}getIndex(e){const t=Object.create(null,{getIndex:{get:()=>super.getIndex}});return I(this,void 0,void 0,function*(){return t.getIndex.call(this,this.vectorBucketName,e)})}deleteIndex(e){const t=Object.create(null,{deleteIndex:{get:()=>super.deleteIndex}});return I(this,void 0,void 0,function*(){return t.deleteIndex.call(this,this.vectorBucketName,e)})}index(e){return new Xa(this.url,this.headers,this.vectorBucketName,e,this.fetch)}}class Xa extends Ha{constructor(e,t,s,r,n){super(e,t,n),this.vectorBucketName=s,this.indexName=r}putVectors(e){const t=Object.create(null,{putVectors:{get:()=>super.putVectors}});return I(this,void 0,void 0,function*(){return t.putVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}getVectors(e){const t=Object.create(null,{getVectors:{get:()=>super.getVectors}});return I(this,void 0,void 0,function*(){return t.getVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}listVectors(){const e=Object.create(null,{listVectors:{get:()=>super.listVectors}});return I(this,arguments,void 0,function*(t={}){return e.listVectors.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}queryVectors(e){const t=Object.create(null,{queryVectors:{get:()=>super.queryVectors}});return I(this,void 0,void 0,function*(){return t.queryVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}deleteVectors(e){const t=Object.create(null,{deleteVectors:{get:()=>super.deleteVectors}});return I(this,void 0,void 0,function*(){return t.deleteVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}}class eo extends Pa{constructor(e,t={},s,r){super(e,t,s,r)}from(e){return new Na(this.url,this.headers,e,this.fetch)}get vectors(){return new Ya(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new $a(this.url+"/iceberg",this.headers,this.fetch)}}let to="";to="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";const so={headers:{"X-Client-Info":`supabase-js-${to}/2.77.0`}},ro={schema:"public"},no={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},io={},ao=(e,t,s)=>{const r=(e=>{let t;return t=e||("undefined"==typeof fetch?Vn:fetch),(...e)=>t(...e)})(s),n="undefined"==typeof Headers?Fn:Headers;return async(s,i)=>{var a;const o=null!==(a=await t())&&void 0!==a?a:e;let l=new n(null==i?void 0:i.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${o}`),r(s,Object.assign(Object.assign({},i),{headers:l}))}};const oo="2.77.0",lo=3e4,co=9e4,uo={"X-Client-Info":`gotrue-js/${oo}`},ho="X-Supabase-Api-Version",fo={timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"},po=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class mo extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function go(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class yo extends mo{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}class vo extends mo{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class bo extends mo{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}}class _o extends bo{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class wo extends bo{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ko extends bo{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class xo extends bo{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}}}class jo extends bo{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 So extends bo{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function To(e){return go(e)&&"AuthRetryableFetchError"===e.name}class Eo extends bo{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class Oo extends bo{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Ao="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Co=" \t\n\r=".split(""),No=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<Co.length;t+=1)e[Co[t].charCodeAt(0)]=-2;for(let t=0;t<Ao.length;t+=1)e[Ao[t].charCodeAt(0)]=t;return e})();function Ro(e,t,s){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;s(Ao[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;s(Ao[e]),t.queuedBits-=6}}function Io(e,t,s){const r=No[e];if(!(r>-1)){if(-2===r)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)s(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function Po(e){const t=[],s=e=>{t.push(String.fromCodePoint(e))},r={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=e=>{!function(e,t,s){if(0===t.utf8seq){if(e<=127)return void s(e);for(let s=1;s<6;s+=1)if(!(e>>7-s&1)){t.utf8seq=s;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&s(t.codepoint)}}(e,r,s)};for(let a=0;a<e.length;a+=1)Io(e.charCodeAt(a),n,i);return t.join("")}function $o(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function Do(e){const t=[],s={queue:0,queuedBits:0},r=e=>{t.push(e)};for(let n=0;n<e.length;n+=1)Io(e.charCodeAt(n),s,r);return new Uint8Array(t)}function Uo(e){const t=[];return function(e,t){for(let s=0;s<e.length;s+=1){let r=e.charCodeAt(s);if(r>55295&&r<=56319){const t=1024*(r-55296)&65535;r=65536+(e.charCodeAt(s+1)-56320&65535|t),s+=1}$o(r,t)}}(e,e=>t.push(e)),new Uint8Array(t)}function Lo(e){const t=[],s={queue:0,queuedBits:0},r=e=>{t.push(e)};return e.forEach(e=>Ro(e,s,r)),Ro(null,s,r),t.join("")}const Vo=()=>"undefined"!=typeof window&&"undefined"!=typeof document,Fo={tested:!1,writable:!1},Bo=()=>{if(!Vo())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(t){return!1}if(Fo.tested)return Fo.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Fo.tested=!0,Fo.writable=!0}catch(t){Fo.tested=!0,Fo.writable=!1}return Fo.writable};const qo=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>J(async()=>{const{default:e}=await Promise.resolve().then(()=>Mn);return{default:e}},void 0).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},Mo=async(e,t,s)=>{await e.setItem(t,JSON.stringify(s))},zo=async(e,t)=>{const s=await e.getItem(t);if(!s)return null;try{return JSON.parse(s)}catch(r){return s}},Wo=async(e,t)=>{await e.removeItem(t)};class Zo{constructor(){this.promise=new Zo.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function Ko(e){const t=e.split(".");if(3!==t.length)throw new Oo("Invalid JWT structure");for(let s=0;s<t.length;s++)if(!po.test(t[s]))throw new Oo("JWT not in base64url format");return{header:JSON.parse(Po(t[0])),payload:JSON.parse(Po(t[1])),signature:Do(t[2]),raw:{header:t[0],payload:t[1]}}}function Jo(e){return("0"+e.toString(16)).substr(-2)}async function Ho(e){if(!("undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder))return e;const t=await async function(e){const t=(new TextEncoder).encode(e),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map(e=>String.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Go(e,t,s=!1){const r=function(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let s="";for(let r=0;r<56;r++)s+=e.charAt(Math.floor(Math.random()*t));return s}return crypto.getRandomValues(e),Array.from(e,Jo).join("")}();let n=r;s&&(n+="/PASSWORD_RECOVERY"),await Mo(e,`${t}-code-verifier`,n);const i=await Ho(r);return[i,r===i?"plain":"s256"]}Zo.promiseConstructor=Promise;const Yo=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;const Qo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Xo(e){if(!Qo.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function el(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function tl(e){return JSON.parse(JSON.stringify(e))}const sl=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),rl=[502,503,504];async function nl(e){var t,s;if(!("object"==typeof(s=e)&&null!==s&&"status"in s&&"ok"in s&&"json"in s&&"function"==typeof s.json))throw new So(sl(e),0);if(rl.includes(e.status))throw new So(sl(e),e.status);let r,n;try{r=await e.json()}catch(a){throw new vo(sl(a),a)}const i=function(e){const t=e.headers.get(ho);if(!t)return null;if(!t.match(Yo))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(a){return null}}(e);if(i&&i.getTime()>=fo.timestamp&&"object"==typeof r&&r&&"string"==typeof r.code?n=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(n=r.error_code),n){if("weak_password"===n)throw new Eo(sl(r),e.status,(null===(t=r.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===n)throw new _o}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new Eo(sl(r),e.status,r.weak_password.reasons);throw new yo(sl(r),e.status||500,n)}async function il(e,t,s,r){var n;const i=Object.assign({},null==r?void 0:r.headers);i[ho]||(i[ho]=fo.name),(null==r?void 0:r.jwt)&&(i.Authorization=`Bearer ${r.jwt}`);const a=null!==(n=null==r?void 0:r.query)&&void 0!==n?n:{};(null==r?void 0:r.redirectTo)&&(a.redirect_to=r.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await async function(e,t,s,r,n,i){const a=((e,t,s,r)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),n.body=JSON.stringify(r),Object.assign(Object.assign({},n),s))})(t,r,n,i);let o;try{o=await e(s,Object.assign({},a))}catch(l){throw new So(sl(l),0)}o.ok||await nl(o);if(null==r?void 0:r.noResolveJson)return o;try{return await o.json()}catch(l){await nl(l)}}(e,t,s+o,{headers:i,noResolveJson:null==r?void 0:r.noResolveJson},{},null==r?void 0:r.body);return(null==r?void 0:r.xform)?null==r?void 0:r.xform(l):{data:Object.assign({},l),error:null}}function al(e){var t;let s=null;var r;(function(e){return e.access_token&&e.refresh_token&&e.expires_in})(e)&&(s=Object.assign({},e),e.expires_at||(s.expires_at=(r=e.expires_in,Math.round(Date.now()/1e3)+r)));return{data:{session:s,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function ol(e){const t=al(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function ll(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function cl(e){return{data:e,error:null}}function dl(e){const{action_link:t,email_otp:s,hashed_token:r,redirect_to:n,verification_type:i}=e,a=$(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:t,email_otp:s,hashed_token:r,redirect_to:n,verification_type:i},user:Object.assign({},a)},error:null}}function ul(e){return e}const hl=["global","local","others"];class fl{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=qo(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=hl[0]){if(hl.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${hl.join(", ")}`);try{return await il(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(go(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await il(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ll})}catch(s){if(go(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:t}=e,s=$(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=null==s?void 0:s.newEmail,delete r.newEmail),await il(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:dl,redirectTo:null==t?void 0:t.redirectTo})}catch(t){if(go(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await il(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ll})}catch(t){if(go(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,r,n,i,a,o;try{const l={nextPage:null,lastPage:0,total:0},c=await il(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(s=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==s?s:"",per_page:null!==(n=null===(r=null==e?void 0:e.perPage)||void 0===r?void 0:r.toString())&&void 0!==n?n:""},xform:ul});if(c.error)throw c.error;const d=await c.json(),u=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,h=null!==(o=null===(a=c.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return h.length>0&&(h.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),s=JSON.parse(e.split(";")[1].split("=")[1]);l[`${s}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(go(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){Xo(e);try{return await il(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ll})}catch(t){if(go(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){Xo(e);try{return await il(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ll})}catch(s){if(go(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){Xo(e);try{return await il(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ll})}catch(s){if(go(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){Xo(e.userId);try{const{data:t,error:s}=await il(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:s}}catch(t){if(go(t))return{data:null,error:t};throw t}}async _deleteFactor(e){Xo(e.userId),Xo(e.id);try{return{data:await il(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(go(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,s,r,n,i,a,o;try{const l={nextPage:null,lastPage:0,total:0},c=await il(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(s=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==s?s:"",per_page:null!==(n=null===(r=null==e?void 0:e.perPage)||void 0===r?void 0:r.toString())&&void 0!==n?n:""},xform:ul});if(c.error)throw c.error;const d=await c.json(),u=null!==(i=c.headers.get("x-total-count"))&&void 0!==i?i:0,h=null!==(o=null===(a=c.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return h.length>0&&(h.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),s=JSON.parse(e.split(";")[1].split("=")[1]);l[`${s}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},d),l),error:null}}catch(l){if(go(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(e){try{return await il(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(go(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await il(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(go(t))return{data:null,error:t};throw t}}async _deleteOAuthClient(e){try{return await il(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(go(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await il(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(t){if(go(t))return{data:null,error:t};throw t}}}function pl(e={}){return{getItem:t=>e[t]||null,setItem:(t,s)=>{e[t]=s},removeItem:t=>{delete e[t]}}}const ml=!!(globalThis&&Bo()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"));class gl extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class yl extends gl{}async function vl(e,t,s){const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort()},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async r=>{if(!r){if(0===t)throw new yl(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(ml)try{await globalThis.navigator.locks.query()}catch(n){}return await s()}try{return await s()}finally{}}))}function bl(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function _l(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class wl extends Error{constructor({message:e,code:t,cause:s,name:r}){var n;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=null!==(n=null!=r?r:s instanceof Error?s.name:void 0)&&void 0!==n?n:"Unknown Error",this.code=t}}class kl extends wl{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function xl({error:e,options:t}){var s,r,n;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new wl({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(s=i.authenticatorSelection)||void 0===s?void 0:s.requireResidentKey))return new wl({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(r=i.authenticatorSelection)||void 0===r?void 0:r.userVerification))return new wl({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(n=i.authenticatorSelection)||void 0===n?void 0:n.userVerification))return new wl({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new wl({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new wl({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name){return 0===i.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new wl({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new wl({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}if("SecurityError"===e.name){const t=window.location.hostname;if(!Cl(t))return new wl({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(i.rp.id!==t)return new wl({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new wl({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new wl({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new wl({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function jl({error:e,options:t}){const{publicKey:s}=t;if(!s)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new wl({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new wl({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!Cl(t))return new wl({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(s.rpId!==t)return new wl({message:`The RP ID "${s.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new wl({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new wl({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const Sl=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function Tl(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:s,excludeCredentials:r}=e,n=$(e,["challenge","user","excludeCredentials"]),i=Do(t).buffer,a=Object.assign(Object.assign({},s),{id:Do(s.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:i,user:a});if(r&&r.length>0){o.excludeCredentials=new Array(r.length);for(let e=0;e<r.length;e++){const t=r[e];o.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:Do(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function El(e){if(!e)throw new Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:t,allowCredentials:s}=e,r=$(e,["challenge","allowCredentials"]),n=Do(t).buffer,i=Object.assign(Object.assign({},r),{challenge:n});if(s&&s.length>0){i.allowCredentials=new Array(s.length);for(let e=0;e<s.length;e++){const t=s[e];i.allowCredentials[e]=Object.assign(Object.assign({},t),{id:Do(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return i}function Ol(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const s=e;return{id:e.id,rawId:e.id,response:{attestationObject:Lo(new Uint8Array(e.response.attestationObject)),clientDataJSON:Lo(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=s.authenticatorAttachment)&&void 0!==t?t:void 0}}function Al(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const s=e,r=e.getClientExtensionResults(),n=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:Lo(new Uint8Array(n.authenticatorData)),clientDataJSON:Lo(new Uint8Array(n.clientDataJSON)),signature:Lo(new Uint8Array(n.signature)),userHandle:n.userHandle?Lo(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!==(t=s.authenticatorAttachment)&&void 0!==t?t:void 0}}function Cl(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function Nl(){var e,t;return!!(Vo()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}const Rl={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"none"},Il={userVerification:"preferred",hints:["security-key"]};function Pl(...e){const t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),s=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),r={};for(const n of e)if(n)for(const e in n){const i=n[e];if(void 0!==i)if(Array.isArray(i))r[e]=i;else if(s(i))r[e]=i;else if(t(i)){const s=r[e];t(s)?r[e]=Pl(s,i):r[e]=Pl(i)}else r[e]=i}return r}class $l{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:s,signal:r},n){try{const{data:i,error:a}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!i)return{data:null,error:a};const o=null!=r?r:Sl.createNewAbortSignal();if("create"===i.webauthn.type){const{user:e}=i.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${s}`),e.displayName||(e.displayName=e.name)}switch(i.webauthn.type){case"create":{const t=function(e,t){return Pl(Rl,e,t||{})}(i.webauthn.credential_options.publicKey,null==n?void 0:n.create),{data:s,error:r}=await async function(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new kl("Browser returned unexpected credential type",t)}:{data:null,error:new kl("Empty credential response",t)}}catch(t){return{data:null,error:xl({error:t,options:e})}}}({publicKey:t,signal:o});return s?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:s}},error:null}:{data:null,error:r}}case"request":{const t=function(e,t){return Pl(Il,e,t||{})}(i.webauthn.credential_options.publicKey,null==n?void 0:n.request),{data:s,error:r}=await async function(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new kl("Browser returned unexpected credential type",t)}:{data:null,error:new kl("Empty credential response",t)}}catch(t){return{data:null,error:jl({error:t,options:e})}}}(Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:t,signal:o}));return s?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:s}},error:null}:{data:null,error:r}}}}catch(i){return go(i)?{data:null,error:i}:{data:null,error:new vo("Unexpected error in challenge",i)}}}async _verify({challengeId:e,factorId:t,webauthn:s}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:s=("undefined"!=typeof window?[window.location.origin]:void 0),signal:r}},n){if(!t)return{data:null,error:new mo("rpId is required for WebAuthn authentication")};try{if(!Nl())return{data:null,error:new vo("Browser does not support WebAuthn",null)};const{data:i,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:s},signal:r},{request:n});if(!i)return{data:null,error:a};const{webauthn:o}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:s,credential_response:o.credential_response}})}catch(i){return go(i)?{data:null,error:i}:{data:null,error:new vo("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:s=("undefined"!=typeof window?[window.location.origin]:void 0),signal:r},n){if(!t)return{data:null,error:new mo("rpId is required for WebAuthn registration")};try{if(!Nl())return{data:null,error:new vo("Browser does not support WebAuthn",null)};const{data:i,error:a}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(t=>{var s;return null===(s=t.data)||void 0===s?void 0:s.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:a};const{data:o,error:l}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:t,rpOrigins:s},signal:r},{create:n});return o?this._verify({factorId:i.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:s,type:o.webauthn.type,credential_response:o.webauthn.credential_response}}):{data:null,error:l}}catch(i){return go(i)?{data:null,error:i}:{data:null,error:new vo("Unexpected error in register",i)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const Dl={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:uo,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Ul(e,t,s){return await s()}const Ll={};class Vl{get jwks(){var e,t;return null!==(t=null===(e=Ll[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){Ll[this.storageKey]=Object.assign(Object.assign({},Ll[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=Ll[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ll[this.storageKey]=Object.assign(Object.assign({},Ll[this.storageKey]),{cachedAt:e})}constructor(e){var t,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=Vl.nextInstanceID,Vl.nextInstanceID+=1,this.instanceID>0&&Vo();const r=Object.assign(Object.assign({},Dl),e);if(this.logDebugMessages=!!r.debug,"function"==typeof r.debug&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new fl({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=qo(r.fetch),this.lock=r.lock||Ul,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:Vo()&&(null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===t?void 0:t.locks)?this.lock=vl:this.lock=Ul,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new $l(this)},this.persistSession?(r.storage?this.storage=r.storage:Bo()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=pl(this.memoryStorage)),r.userStorage&&(this.userStorage=r.userStorage)):(this.memoryStorage={},this.storage=pl(this.memoryStorage)),Vo()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(n){}null===(s=this.broadcastChannel)||void 0===s||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${oo}) ${(new Date).toISOString()}`,...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{const t=function(e){const t={},s=new URL(e);if(s.hash&&"#"===s.hash[0])try{new URLSearchParams(s.hash.substring(1)).forEach((e,s)=>{t[s]=e})}catch(r){}return s.searchParams.forEach((e,s)=>{t[s]=e}),t}(window.location.href);let s="none";if(this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce"),Vo()&&this.detectSessionInUrl&&"none"!==s){const{data:r,error:n}=await this._getSessionFromURL(t,s);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),function(e){return go(e)&&"AuthImplicitGrantRedirectError"===e.name}(n)){const t=null===(e=n.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:n}}return await this._removeSession(),{error:n}}const{session:i,redirectType:a}=r;return this._debug("#_initialize()","detected session in URL",i,"redirect type",a),await this._saveSession(i),setTimeout(async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return go(t)?{error:t}:{error:new vo("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{const n=await il(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(s=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==s?s:{},gotrue_meta_security:{captcha_token:null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken}},xform:al}),{data:i,error:a}=n;if(a||!i)return{data:{user:null,session:null},error:a};const o=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",o)),{data:{user:l,session:o},error:null}}catch(n){if(go(n))return{data:{user:null,session:null},error:n};throw n}}async signUp(e){var t,s,r;try{let n;if("email"in e){const{email:s,password:r,options:i}=e;let a=null,o=null;"pkce"===this.flowType&&([a,o]=await Go(this.storage,this.storageKey)),n=await il(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==i?void 0:i.emailRedirectTo,body:{email:s,password:r,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:a,code_challenge_method:o},xform:al})}else{if(!("phone"in e))throw new ko("You must provide either an email or phone number and a password");{const{phone:t,password:i,options:a}=e;n=await il(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:i,data:null!==(s=null==a?void 0:a.data)&&void 0!==s?s:{},channel:null!==(r=null==a?void 0:a.channel)&&void 0!==r?r:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:al})}}const{data:i,error:a}=n;if(a||!i)return{data:{user:null,session:null},error:a};const o=i.session,l=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",o)),{data:{user:l,session:o},error:null}}catch(n){if(go(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithPassword(e){try{let t;if("email"in e){const{email:s,password:r,options:n}=e;t=await il(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:r,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:ol})}else{if(!("phone"in e))throw new ko("You must provide either an email or phone number and a password");{const{phone:s,password:r,options:n}=e;t=await il(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:r,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:ol})}}const{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:s&&s.session&&s.user?(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r}):{data:{user:null,session:null},error:new wo}}catch(t){if(go(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,s,r,n;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(s=e.options)||void 0===s?void 0:s.scopes,queryParams:null===(r=e.options)||void 0===r?void 0:r.queryParams,skipBrowserRedirect:null===(n=e.options)||void 0===n?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,s,r,n,i,a,o,l,c,d,u;let h,f;if("message"in e)h=e.message,f=e.signature;else{const{chain:d,wallet:u,statement:p,options:m}=e;let g;if(Vo())if("object"==typeof u)g=u;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.");g=e.ethereum}else{if("object"!=typeof u||!(null==m?void 0:m.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");g=u}const y=new URL(null!==(t=null==m?void 0:m.url)&&void 0!==t?t:window.location.href),v=await g.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!v||0===v.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const b=bl(v[0]);let _=null===(s=null==m?void 0:m.signInWithEthereum)||void 0===s?void 0:s.chainId;if(!_){const e=await g.request({method:"eth_chainId"});_=parseInt(e,16)}h=function(e){var t;const{chainId:s,domain:r,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:l,resources:c,scheme:d,uri:u,version:h}=e;if(!Number.isInteger(s))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${s}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==h)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const f=`${d?`${d}://${r}`:r} wants you to sign in with your Ethereum account:\n${bl(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let p=`URI: ${u}\nVersion: ${h}\nChain ID: ${s}${a?`\nNonce: ${a}`:""}\nIssued At: ${i.toISOString()}`;if(n&&(p+=`\nExpiration Time: ${n.toISOString()}`),o&&(p+=`\nNot Before: ${o.toISOString()}`),l&&(p+=`\nRequest ID: ${l}`),c){let e="\nResources:";for(const t of c){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}p+=e}return`${f}\n${p}`}({domain:y.host,address:b,statement:p,uri:y.href,version:"1",chainId:_,nonce:null===(r=null==m?void 0:m.signInWithEthereum)||void 0===r?void 0:r.nonce,issuedAt:null!==(i=null===(n=null==m?void 0:m.signInWithEthereum)||void 0===n?void 0:n.issuedAt)&&void 0!==i?i:new Date,expirationTime:null===(a=null==m?void 0:m.signInWithEthereum)||void 0===a?void 0:a.expirationTime,notBefore:null===(o=null==m?void 0:m.signInWithEthereum)||void 0===o?void 0:o.notBefore,requestId:null===(l=null==m?void 0:m.signInWithEthereum)||void 0===l?void 0:l.requestId,resources:null===(c=null==m?void 0:m.signInWithEthereum)||void 0===c?void 0:c.resources}),f=await g.request({method:"personal_sign",params:[_l(h),b]})}try{const{data:t,error:s}=await il(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:f},(null===(d=e.options)||void 0===d?void 0:d.captchaToken)?{gotrue_meta_security:{captcha_token:null===(u=e.options)||void 0===u?void 0:u.captchaToken}}:null),xform:al});if(s)throw s;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign({},t),error:s}):{data:{user:null,session:null},error:new wo}}catch(p){if(go(p))return{data:{user:null,session:null},error:p};throw p}}async signInWithSolana(e){var t,s,r,n,i,a,o,l,c,d,u,h;let f,p;if("message"in e)f=e.message,p=e.signature;else{const{chain:u,wallet:h,statement:m,options:g}=e;let y;if(Vo())if("object"==typeof h)y=h;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");y=e.solana}else{if("object"!=typeof h||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=h}const v=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href);if("signIn"in y&&y.signIn){const e=await y.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==g?void 0:g.signInWithSolana),{version:"1",domain:v.host,uri:v.href}),m?{statement:m}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");f="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),p=t.signature}else{if(!("signMessage"in y&&"function"==typeof y.signMessage&&"publicKey"in y&&"object"==typeof y&&y.publicKey&&"toBase58"in y.publicKey&&"function"==typeof y.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${v.host} wants you to sign in with your Solana account:`,y.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1",`URI: ${v.href}`,`Issued At: ${null!==(r=null===(s=null==g?void 0:g.signInWithSolana)||void 0===s?void 0:s.issuedAt)&&void 0!==r?r:(new Date).toISOString()}`,...(null===(n=null==g?void 0:g.signInWithSolana)||void 0===n?void 0:n.notBefore)?[`Not Before: ${g.signInWithSolana.notBefore}`]:[],...(null===(i=null==g?void 0:g.signInWithSolana)||void 0===i?void 0:i.expirationTime)?[`Expiration Time: ${g.signInWithSolana.expirationTime}`]:[],...(null===(a=null==g?void 0:g.signInWithSolana)||void 0===a?void 0:a.chainId)?[`Chain ID: ${g.signInWithSolana.chainId}`]:[],...(null===(o=null==g?void 0:g.signInWithSolana)||void 0===o?void 0:o.nonce)?[`Nonce: ${g.signInWithSolana.nonce}`]:[],...(null===(l=null==g?void 0:g.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${g.signInWithSolana.requestId}`]:[],...(null===(d=null===(c=null==g?void 0:g.signInWithSolana)||void 0===c?void 0:c.resources)||void 0===d?void 0:d.length)?["Resources",...g.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await y.signMessage((new TextEncoder).encode(f),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");p=e}}try{const{data:t,error:s}=await il(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:Lo(p)},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(h=e.options)||void 0===h?void 0:h.captchaToken}}:null),xform:al});if(s)throw s;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign({},t),error:s}):{data:{user:null,session:null},error:new wo}}catch(m){if(go(m))return{data:{user:null,session:null},error:m};throw m}}async _exchangeCodeForSession(e){const t=await zo(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(null!=t?t:"").split("/");try{const{data:t,error:n}=await il(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:al});if(await Wo(this.storage,`${this.storageKey}-code-verifier`),n)throw n;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign(Object.assign({},t),{redirectType:null!=r?r:null}),error:n}):{data:{user:null,session:null,redirectType:null},error:new wo}}catch(n){if(go(n))return{data:{user:null,session:null,redirectType:null},error:n};throw n}}async signInWithIdToken(e){try{const{options:t,provider:s,token:r,access_token:n,nonce:i}=e,a=await il(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:n,nonce:i,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:al}),{data:o,error:l}=a;return l?{data:{user:null,session:null},error:l}:o&&o.session&&o.user?(o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),{data:o,error:l}):{data:{user:null,session:null},error:new wo}}catch(t){if(go(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,s,r,n,i;try{if("email"in e){const{email:r,options:n}=e;let i=null,a=null;"pkce"===this.flowType&&([i,a]=await Go(this.storage,this.storageKey));const{error:o}=await il(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:r,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},create_user:null===(s=null==n?void 0:n.shouldCreateUser)||void 0===s||s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:i,code_challenge_method:a},redirectTo:null==n?void 0:n.emailRedirectTo});return{data:{user:null,session:null},error:o}}if("phone"in e){const{phone:t,options:s}=e,{data:a,error:o}=await il(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(r=null==s?void 0:s.data)&&void 0!==r?r:{},create_user:null===(n=null==s?void 0:s.shouldCreateUser)||void 0===n||n,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken},channel:null!==(i=null==s?void 0:s.channel)&&void 0!==i?i:"sms"}});return{data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o}}throw new ko("You must provide either an email or phone number.")}catch(a){if(go(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,s;try{let r,n;"options"in e&&(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo,n=null===(s=e.options)||void 0===s?void 0:s.captchaToken);const{data:i,error:a}=await il(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:r,xform:al});if(a)throw a;if(!i)throw new Error("An error occurred on token verification.");const o=i.session,l=i.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),{data:{user:l,session:o},error:null}}catch(r){if(go(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithSSO(e){var t,s,r;try{let n=null,i=null;return"pkce"===this.flowType&&([n,i]=await Go(this.storage,this.storageKey)),await il(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:null!==(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==s?s:void 0}),(null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:i}),headers:this.headers,xform:cl})}catch(n){if(go(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:s}=e;if(s)throw s;if(!t)throw new _o;const{error:r}=await il(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(go(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:s,type:r,options:n}=e,{error:i}=await il(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},redirectTo:null==n?void 0:n.emailRedirectTo});return{data:{user:null,session:null},error:i}}if("phone"in e){const{phone:s,type:r,options:n}=e,{data:i,error:a}=await il(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}}});return{data:{user:null,session:null,messageId:null==i?void 0:i.message_id},error:a}}throw new ko("You must provide either an email or phone number and a type")}catch(t){if(go(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){await this.initializePromise;return await this._acquireLock(-1,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch(e){}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(t){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}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 zo(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=!!e.expires_at&&1e3*e.expires_at-Date.now()<co;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const t=await zo(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=el()}if(this.storage.isServer&&e.user){let t=this.suppressGetSessionWarning;e=new Proxy(e,{get:(e,s,r)=>(t||"user"!==s||(t=!0,this.suppressGetSessionWarning=!0),Reflect.get(e,s,r))})}return{data:{session:e},error:null}}const{data:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{session:null},error:n}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;return await this._acquireLock(-1,async()=>await this._getUser())}async _getUser(e){try{return e?await il(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ll}):await this._useSession(async e=>{var t,s,r;const{data:n,error:i}=e;if(i)throw i;return(null===(t=n.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await il(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(r=null===(s=n.session)||void 0===s?void 0:s.access_token)&&void 0!==r?r:void 0,xform:ll}):{data:{user:null},error:new _o}})}catch(t){if(go(t))return function(e){return go(e)&&"AuthSessionMissingError"===e.name}(t)&&(await this._removeSession(),await Wo(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{const{data:r,error:n}=s;if(n)throw n;if(!r.session)throw new _o;const i=r.session;let a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await Go(this.storage,this.storageKey));const{data:l,error:c}=await il(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:o}),jwt:i.access_token,xform:ll});if(c)throw c;return i.user=l.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),{data:{user:i.user},error:null}})}catch(s){if(go(s))return{data:{user:null},error:s};throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new _o;const t=Date.now()/1e3;let s=t,r=!0,n=null;const{payload:i}=Ko(e.access_token);if(i.exp&&(s=i.exp,r=s<=t),r){const{data:t,error:s}=await this._callRefreshToken(e.refresh_token);if(s)return{data:{user:null,session:null},error:s};if(!t)return{data:{user:null,session:null},error:null};n=t}else{const{data:r,error:i}=await this._getUser(e.access_token);if(i)throw i;n={access_token:e.access_token,refresh_token:e.refresh_token,user:r.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return{data:{user:n.user,session:n},error:null}}catch(t){if(go(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var s;if(!e){const{data:r,error:n}=t;if(n)throw n;e=null!==(s=r.session)&&void 0!==s?s:void 0}if(!(null==e?void 0:e.refresh_token))throw new _o;const{data:r,error:n}=await this._callRefreshToken(e.refresh_token);return n?{data:{user:null,session:null},error:n}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(go(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!Vo())throw new xo("No browser detected.");if(e.error||e.error_description||e.error_code)throw new xo(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new jo("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new xo("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new jo("No code detected.");const{data:t,error:s}=await this._exchangeCodeForSession(e.code);if(s)throw s;const r=new URL(window.location.href);return r.searchParams.delete("code"),window.history.replaceState(window.history.state,"",r.toString()),{data:{session:t.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:r,access_token:n,refresh_token:i,expires_in:a,expires_at:o,token_type:l}=e;if(!(n&&a&&i&&l))throw new xo("No session defined in URL");const c=Math.round(Date.now()/1e3),d=parseInt(a);let u=c+d;o&&(u=parseInt(o));const{data:h,error:f}=await this._getUser(n);if(f)throw f;const p={provider_token:s,provider_refresh_token:r,access_token:n,expires_in:d,expires_at:u,refresh_token:i,token_type:l,user:h.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:p,redirectType:e.type},error:null}}catch(s){if(go(s))return{data:{session:null,redirectType:null},error:s};throw s}}_isImplicitGrantCallback(e){return Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await zo(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var s;const{data:r,error:n}=t;if(n)return{error:n};const i=null===(s=r.session)||void 0===s?void 0:s.access_token;if(i){const{error:t}=await this.admin.signOut(i,e);if(t&&(!function(e){return go(e)&&"AuthApiError"===e.name}(t)||404!==t.status&&401!==t.status&&403!==t.status))return{error:t}}return"others"!==e&&(await this._removeSession(),await Wo(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>{await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,r;try{const{data:{session:r},error:n}=t;if(n)throw n;await(null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",r)),this._debug("INITIAL_SESSION","callback id",e,"session",r)}catch(n){await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",n)}})}async resetPasswordForEmail(e,t={}){let s=null,r=null;"pkce"===this.flowType&&([s,r]=await Go(this.storage,this.storageKey,!0));try{return await il(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(n){if(go(n))return{data:null,error:n};throw n}}async getUserIdentities(){var e;try{const{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null}}catch(t){if(go(t))return{data:null,error:t};throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:s,error:r}=await this._useSession(async t=>{var s,r,n,i,a;const{data:o,error:l}=t;if(l)throw l;const c=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(s=e.options)||void 0===s?void 0:s.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(n=e.options)||void 0===n?void 0:n.queryParams,skipBrowserRedirect:!0});return await il(this.fetch,"GET",c,{headers:this.headers,jwt:null!==(a=null===(i=o.session)||void 0===i?void 0:i.access_token)&&void 0!==a?a:void 0})});if(r)throw r;return Vo()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==s?void 0:s.url),{data:{provider:e.provider,url:null==s?void 0:s.url},error:null}}catch(s){if(go(s))return{data:{provider:e.provider,url:null},error:s};throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var s;try{const{error:r,data:{session:n}}=t;if(r)throw r;const{options:i,provider:a,token:o,access_token:l,nonce:c}=e,d=await il(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(s=null==n?void 0:n.access_token)&&void 0!==s?s:void 0,body:{provider:a,id_token:o,access_token:l,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:al}),{data:u,error:h}=d;return h?{data:{user:null,session:null},error:h}:u&&u.session&&u.user?(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),{data:u,error:h}):{data:{user:null,session:null},error:new wo}}catch(r){if(go(r))return{data:{user:null,session:null},error:r};throw r}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;const{data:n,error:i}=t;if(i)throw i;return await il(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(r=null===(s=n.session)||void 0===s?void 0:s.access_token)&&void 0!==r?r:void 0})})}catch(t){if(go(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const n=Date.now();return await(s=async s=>(s>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await il(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:al})),r=(e,t)=>{const s=200*Math.pow(2,e);return t&&To(t)&&Date.now()+s-n<lo},new Promise((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{const t=await s(i);if(!r(i,null,t))return void e(t)}catch(n){if(!r(i,n))return void t(n)}})()}))}catch(n){if(this._debug(t,"error",n),go(n))return{data:{session:null,user:null},error:n};throw n}finally{this._debug(t,"end")}var s,r}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),Vo()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,t;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await zo(this.storage,this.storageKey);if(n&&this.userStorage){let t=await zo(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:n.user},await Mo(this.userStorage,this.storageKey+"-user",t)),n.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:el()}else if(n&&!n.user&&!n.user){const e=await zo(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(n.user=e.user,await Wo(this.storage,this.storageKey+"-user"),await Mo(this.storage,this.storageKey,n)):n.user=el()}if(this._debug(s,"session from storage",n),!this._isValidSession(n))return this._debug(s,"session is not valid"),void(null!==n&&await this._removeSession());const i=1e3*(null!==(t=n.expires_at)&&void 0!==t?t:1/0)-Date.now()<co;if(this._debug(s,`session has${i?"":" not"} expired with margin of 90000s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:e}=await this._callRefreshToken(n.refresh_token);e&&(To(e)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(n.user&&!0===n.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(n.access_token);!t&&(null==e?void 0:e.user)?(n.user=e.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(r){this._debug(s,"error getting user data, skipping SIGNED_IN notification",r)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){return void this._debug(s,"error",n)}finally{this._debug(s,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new _o;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new Zo;const{data:t,error:s}=await this._refreshAccessToken(e);if(s)throw s;if(!t.session)throw new _o;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const r={data:t.session,error:null};return this.refreshingDeferred.resolve(r),r}catch(n){if(this._debug(r,"error",n),go(n)){const e={data:null,error:n};return To(n)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(e),e}throw null===(s=this.refreshingDeferred)||void 0===s||s.reject(n),n}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){const r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});const r=[],n=Array.from(this.stateChangeEmitters.values()).map(async s=>{try{await s.callback(e,t)}catch(n){r.push(n)}});if(await Promise.all(n),r.length>0){for(let e=0;e<r.length;e+=1);throw r[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const t=Object.assign({},e),s=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!s&&t.user&&await Mo(this.userStorage,this.storageKey+"-user",{user:t.user});const e=Object.assign({},t);delete e.user;const r=tl(e);await Mo(this.storage,this.storageKey,r)}else{const e=tl(t);await Mo(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),await Wo(this.storage,this.storageKey),await Wo(this.storage,this.storageKey+"-code-verifier"),await Wo(this.storage,this.storageKey+"-user"),this.userStorage&&await Wo(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Vo()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),lo);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&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 t=Date.now();try{return await this._useSession(async e=>{const{data:{session:s}}=e;if(!s||!s.refresh_token||!s.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const r=Math.floor((1e3*s.expires_at-t)/lo);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),r<=3&&await this._callRefreshToken(s.refresh_token)})}catch(e){}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e.isAcquireTimeout||e instanceof gl))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Vo()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,s){const r=[`provider=${encodeURIComponent(t)}`];if((null==s?void 0:s.redirectTo)&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),(null==s?void 0:s.scopes)&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),"pkce"===this.flowType){const[e,t]=await Go(this.storage,this.storageKey),s=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});r.push(s.toString())}if(null==s?void 0:s.queryParams){const e=new URLSearchParams(s.queryParams);r.push(e.toString())}return(null==s?void 0:s.skipBrowserRedirect)&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;const{data:r,error:n}=t;return n?{data:null,error:n}:await il(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(s=null==r?void 0:r.session)||void 0===s?void 0:s.access_token})})}catch(t){if(go(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,r;const{data:n,error:i}=t;if(i)return{data:null,error:i};const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:l}=await il(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:null===(s=null==n?void 0:n.session)||void 0===s?void 0:s.access_token});return l?{data:null,error:l}:("totp"===e.factorType&&"totp"===o.type&&(null===(r=null==o?void 0:o.totp)||void 0===r?void 0:r.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),{data:o,error:null})})}catch(t){if(go(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:r,error:n}=t;if(n)return{data:null,error:n};const i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?Ol(e.webauthn.credential_response):Al(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await il(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:null===(s=null==r?void 0:r.session)||void 0===s?void 0:s.access_token});return o?{data:null,error:o}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),{data:a,error:o})})}catch(t){if(go(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:r,error:n}=t;if(n)return{data:null,error:n};const i=await il(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(s=null==r?void 0:r.session)||void 0===s?void 0:s.access_token});if(i.error)return i;const{data:a}=i;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Tl(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:El(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(go(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){const{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:s}=await this.getUser();if(s)return{data:null,error:s};const r={all:[],phone:[],totp:[],webauthn:[]};for(const n of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])r.all.push(n),"verified"===n.status&&r[n.factor_type].push(n);return{data:r,error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,s;const{data:{session:r},error:n}=e;if(n)return{data:null,error:n};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:i}=Ko(r.access_token);let a=null;i.aal&&(a=i.aal);let o=a;(null!==(s=null===(t=r.user.factors)||void 0===t?void 0:t.filter(e=>"verified"===e.status))&&void 0!==s?s:[]).length>0&&(o="aal2");return{data:{currentLevel:a,nextLevel:o,currentAuthenticationMethods:i.amr||[]},error:null}}))}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(t=>t.kid===e);if(s)return s;const r=Date.now();if(s=this.jwks.keys.find(t=>t.kid===e),s&&this.jwks_cached_at+6e5>r)return s;const{data:n,error:i}=await il(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return n.keys&&0!==n.keys.length?(this.jwks=n,this.jwks_cached_at=r,s=n.keys.find(t=>t.kid===e),s||null):null}async getClaims(e,t={}){try{let s=e;if(!s){const{data:e,error:t}=await this.getSession();if(t||!e.session)return{data:null,error:t};s=e.session.access_token}const{header:r,payload:n,signature:i,raw:{header:a,payload:o}}=Ko(s);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(n.exp);const l=r.alg&&!r.alg.startsWith("HS")&&r.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(r.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!l){const{error:e}=await this.getUser(s);if(e)throw e;return{data:{claims:n,header:r,signature:i},error:null}}const c=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}(r.alg),d=await crypto.subtle.importKey("jwk",l,c,!0,["verify"]);if(!(await crypto.subtle.verify(c,d,i,Uo(`${a}.${o}`))))throw new Oo("Invalid JWT signature");return{data:{claims:n,header:r,signature:i},error:null}}catch(s){if(go(s))return{data:null,error:s};throw s}}}Vl.nextInstanceID=0;const Fl=Vl;class Bl extends Fl{constructor(e){super(e)}}class ql{constructor(e,t,s){var r,n,i;this.supabaseUrl=e,this.supabaseKey=t;const a=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL((s=t).endsWith("/")?s:s+"/")}catch(r){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}var s}(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const o=`sb-${a.hostname.split(".")[0]}-auth-token`,l=function(e,t){var s,r;const{db:n,auth:i,realtime:a,global:o}=e,{db:l,auth:c,realtime:d,global:u}=t,h={db:Object.assign(Object.assign({},l),n),auth:Object.assign(Object.assign({},c),i),realtime:Object.assign(Object.assign({},d),a),storage:{},global:Object.assign(Object.assign(Object.assign({},u),o),{headers:Object.assign(Object.assign({},null!==(s=null==u?void 0:u.headers)&&void 0!==s?s:{}),null!==(r=null==o?void 0:o.headers)&&void 0!==r?r:{})}),accessToken:async()=>""};return e.accessToken?h.accessToken=e.accessToken:delete h.accessToken,h}(null!=s?s:{},{db:ro,realtime:io,auth:Object.assign(Object.assign({},no),{storageKey:o}),global:so});this.storageKey=null!==(r=l.auth.storageKey)&&void 0!==r?r:"",this.headers=null!==(n=l.global.headers)&&void 0!==n?n:{},l.accessToken?(this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(i=l.auth)&&void 0!==i?i:{},this.headers,l.global.fetch),this.fetch=ao(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.rest=new vi(new URL("rest/v1",a).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this.storage=new eo(this.storageUrl.href,this.headers,this.fetch,null==s?void 0:s.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new An(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,s)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t;if(this.accessToken)return await this.accessToken();const{data:s}=await this.auth.getSession();return null!==(t=null===(e=s.session)||void 0===e?void 0:e.access_token)&&void 0!==t?t:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,userStorage:n,storageKey:i,flowType:a,lock:o,debug:l},c,d){const u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Bl({url:this.authUrl.href,headers:Object.assign(Object.assign({},u),c),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,userStorage:n,flowType:a,lock:o,debug:l,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new ua(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,s){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===s?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=s,this.realtime.setAuth(s))}}!function(){if("undefined"!=typeof window)return!1;if("undefined"==typeof process)return!1;const e=process.version;if(null==e)return!1;const t=e.match(/^v(\d+)\./);!!t&&parseInt(t[1],10)}();const Ml=(zl={auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}},new ql("https://zivvkvoaqggapqnpxtcs.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InppdnZrdm9hcWdnYXBxbnB4dGNzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE3ODE4NTIsImV4cCI6MjA3NzM1Nzg1Mn0.ZQ5S4uGnt2sJolruezkf3G5PxQL-8dfwb9tMEMAd-Js",zl));var zl;const Wl="/assets/amex-logo-NMAdbQ7R.png",Zl="/assets/bmc-logo-2jzedfbA.png",Kl="/assets/ge-logo-vy1X7H0d.png",Jl="/assets/novell-logo--1Ty88up.png",Hl=$r({name:Nr().min(2,"Name must be at least 2 characters").max(100,"Name must be less than 100 characters").regex(/^[a-zA-Z\s\-'.]+$/,"Name contains invalid characters"),email:Nr().email("Please enter a valid business email").max(255,"Email must be less than 255 characters").refine(e=>{const t=e.split("@")[1]?.toLowerCase();return!["gmail.com","yahoo.com","hotmail.com","outlook.com","aol.com","icloud.com"].includes(t)},{message:"Please use your business email address"}),company:Nr().min(2,"Company name is required").max(200,"Company name must be less than 200 characters"),phone:Nr().max(50,"Phone number is too long").optional().or(Lr("")),message:Nr().max(1e3,"Message must be less than 1000 characters").optional().or(Lr("")),intent:Vr(["demo","architect","inquiry"],{required_error:"Please select what you're looking for"})}),Gl={demo:{label:"Request a Demo",description:"See our platform capabilities in action",icon:re},architect:{label:"Talk to an Architect",description:"Discuss your technical requirements",icon:be},inquiry:{label:"General Inquiry",description:"Ask a question or explore options",icon:me}},Yl=[{src:Kl,alt:"GE logo",width:48},{src:Wl,alt:"American Express logo",width:56},{src:Zl,alt:"BMC Software logo",width:48},{src:Jl,alt:"Novell logo",width:52}];function Ql({open:t,onOpenChange:s,defaultIntent:r="demo",context:n={}}){const{toast:i}=H(),[a,o]=D.useState(!1),[l,c]=D.useState(!1),{register:d,handleSubmit:u,reset:h,setValue:f,watch:p,formState:{errors:m}}=Wt({resolver:es(Hl),defaultValues:{intent:r}}),g=p("intent");D.useEffect(()=>{f("intent",r)},[r,f]),D.useEffect(()=>{t&&G("demo_modal_open",{intent:r,source_page:n.sourcePage||window.location.pathname,source_button:n.sourceButton||"unknown",service_context:n.serviceContext,product_context:n.productContext,industry_context:n.industryContext})},[t,r,n]);const y=()=>{s(!1),setTimeout(()=>{h({intent:r}),c(!1)},300)};return l?e.jsx(Fr,{open:t,onOpenChange:y,children:e.jsx(zr,{className:"sm:max-w-md",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("div",{className:"rounded-full bg-green-100 p-3 mb-4",children:e.jsx(oe,{className:"h-8 w-8 text-green-600"})}),e.jsx(Zr,{className:"text-xl mb-2",children:"Request Received"}),e.jsx(Kr,{className:"text-base",children:"Thank you for your interest. A member of our team will reach out within 1 business day."})]})})}):e.jsx(Fr,{open:t,onOpenChange:y,children:e.jsxs(zr,{className:"sm:max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Wr,{children:[e.jsx(Zr,{className:"text-xl",children:"Let's Start a Conversation"}),e.jsx(Kr,{children:"Tell us about your needs and we'll connect you with the right team."})]}),e.jsxs("form",{onSubmit:u(async e=>{o(!0);try{const t=Y(),s={name:e.name.trim(),email:e.email.trim().toLowerCase(),company:e.company.trim(),phone:e.phone?.trim()||null,message:e.message?.trim()||null,intent:e.intent,intentLabel:Gl[e.intent].label,sourcePage:n.sourcePage||window.location.pathname,sourceButton:n.sourceButton||"unknown",serviceContext:n.serviceContext||null,productContext:n.productContext||null,industryContext:n.industryContext||null,resourceContext:n.resourceContext||null,utmSource:t.utm_source||null,utmMedium:t.utm_medium||null,utmCampaign:t.utm_campaign||null,userAgent:navigator.userAgent,referrer:document.referrer||null},{error:r}=await Ml.functions.invoke("demo-request",{body:s});if(r)throw r;G("demo_form_submit",{intent:e.intent,intent_label:Gl[e.intent].label,source_page:n.sourcePage||window.location.pathname,source_button:n.sourceButton||"unknown",service_context:n.serviceContext,product_context:n.productContext,industry_context:n.industryContext,has_phone:!!e.phone,has_message:!!e.message,status:"success"}),c(!0),i({title:"Request received",description:"We'll be in touch within 1 business day."}),setTimeout(()=>{y()},2500)}catch(t){G("demo_form_submit",{intent:e.intent,source_page:n.sourcePage||window.location.pathname,status:"error",error_message:t instanceof Error?t.message:"Unknown error"}),i({title:"Request failed",description:"Please try again or email sales@allerin.com directly.",variant:"destructive"})}finally{o(!1)}}),className:"space-y-5 mt-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs(B,{className:"text-sm font-medium",children:["What are you looking for? ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(wn,{value:g,onValueChange:e=>f("intent",e),className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:Object.keys(Gl).map(t=>{const s=Gl[t],r=s.icon,n=g===t;return e.jsxs("label",{className:`\n                      relative flex flex-col items-center p-4 rounded-lg border-2 cursor-pointer transition-all\n                      ${n?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-muted/50"}\n                    `,children:[e.jsx(kn,{value:t,id:`intent-${t}`,className:"sr-only"}),e.jsx(r,{className:"h-6 w-6 mb-2 "+(n?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:"text-sm font-medium text-center "+(n?"text-primary":""),children:s.label}),e.jsx("span",{className:"text-xs text-muted-foreground text-center mt-1 hidden sm:block",children:s.description})]},t)})}),m.intent&&e.jsx("p",{className:"text-sm text-destructive",children:m.intent.message})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(B,{htmlFor:"demo-name",children:["Full Name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(q,{id:"demo-name",placeholder:"Jane Smith",autoComplete:"name",...d("name"),className:m.name?"border-destructive":""}),m.name&&e.jsx("p",{className:"text-sm text-destructive",children:m.name.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(B,{htmlFor:"demo-email",children:["Business Email ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(q,{id:"demo-email",type:"email",placeholder:"jane@company.com",autoComplete:"email",...d("email"),className:m.email?"border-destructive":""}),m.email&&e.jsx("p",{className:"text-sm text-destructive",children:m.email.message})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(B,{htmlFor:"demo-company",children:["Company ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(q,{id:"demo-company",placeholder:"Acme Corporation",autoComplete:"organization",...d("company"),className:m.company?"border-destructive":""}),m.company&&e.jsx("p",{className:"text-sm text-destructive",children:m.company.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"demo-phone",children:"Phone (Optional)"}),e.jsx(q,{id:"demo-phone",type:"tel",placeholder:"+1 (555) 123-4567",autoComplete:"tel",...d("phone")})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(B,{htmlFor:"demo-message",children:"Tell us about your project (Optional)"}),e.jsx(Jr,{id:"demo-message",placeholder:"What challenges are you looking to solve? Any specific timeline or requirements?",rows:3,...d("message"),className:"resize-none"})]}),e.jsxs("div",{className:"pt-2 border-t border-border",children:[e.jsx("p",{className:"text-xs text-muted-foreground text-center mb-3",children:"Trusted by engineering leaders at Fortune 500 companies"}),e.jsx("div",{className:"flex items-center justify-center gap-6 opacity-60",children:Yl.map(t=>e.jsx("img",{src:t.src,alt:t.alt,width:t.width,height:24,className:"h-6 w-auto object-contain grayscale",loading:"lazy",style:{aspectRatio:`${t.width}/24`}},t.alt))})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx(F,{type:"button",variant:"outline",onClick:y,children:"Cancel"}),e.jsx(F,{type:"submit",disabled:a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(ue,{className:"mr-2 h-4 w-4 animate-spin"}),"Submitting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ye,{className:"mr-2 h-4 w-4"}),"Submit Request"]})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:["By submitting, you agree to our"," ",e.jsx("a",{href:"/privacy-policy",className:"underline hover:no-underline",children:"Privacy Policy"}),". We'll never share your information."]})]})]})})}const Xl=[{name:"Products & Solutions",href:"/products",hasDropdown:!0,items:[{name:"Products",href:"/products"},{name:"Solutions",href:"/solutions"}]},{name:"Services",href:"/services",hasDropdown:!0,items:[{name:"Services",href:"/services"},{name:"GCC-as-a-Service",href:"/gcc-as-a-service"}]},{name:"Industries",href:"/industries"},{name:"Resources",href:"/resources"},{name:"Blog",href:"https://www.allerin.com/blog",isExternal:!0},{name:"Company",href:"#company",hasDropdown:!0,items:[{name:"About",href:"/company"},{name:"Methodology",href:"/about/methodology"},{name:"Trust Center",href:"/trust"}]},{name:"ROI Calculator",href:"/roi-calculator",isPill:!0}],ec=()=>{const[t,s]=D.useState(!1),[r,n]=D.useState(!1),i=e=>{Q(e)},a=()=>{X({source:"header"}),n(!0)};return e.jsxs(e.Fragment,{children:[e.jsx("a",{href:"#main",className:"sr-only focus:not-sr-only focus:absolute focus:top-2 focus:left-2 focus:z-50 focus:px-4 focus:py-2 focus:bg-primary focus:text-primary-foreground focus:rounded-md focus:outline-none focus:ring-2 focus:ring-ring",children:"Skip to content"}),e.jsx("header",{className:"sticky top-0 z-50 clean-card backdrop-blur-md border-b border-outline/20",children:e.jsx("div",{className:"container mx-auto px-6",children:e.jsxs("div",{className:"flex items-center justify-between h-16",children:[e.jsx("div",{className:"flex items-center",children:e.jsx(V,{to:"/",onClick:()=>i("logo"),children:e.jsx("img",{src:M,alt:"Allerin Technologies, go to homepage",className:"h-8 w-auto",width:120,height:32,fetchPriority:"high"})})}),e.jsx("nav",{className:"hidden lg:flex items-center space-x-6",children:Xl.map(t=>t.isPill?e.jsxs(Te,{children:[e.jsxs(Ee,{className:"px-4 py-2 rounded-full border border-data-teal/30 text-sm font-medium text-foreground hover:border-data-teal/50 hover:bg-data-teal/5 transition-all inline-flex items-center gap-1 focus:outline-none focus:ring-2 focus:ring-ring",children:[t.name,e.jsx(ne,{className:"h-3 w-3"})]}),e.jsxs(Oe,{align:"end",children:[e.jsx(Ae,{asChild:!0,children:e.jsx(V,{to:"/roi-calculator",className:"cursor-pointer",onClick:()=>i("roi_quick"),children:"Quick Estimate"})}),e.jsx(Ae,{asChild:!0,children:e.jsx(V,{to:"/outcomes",className:"cursor-pointer",onClick:()=>i("roi_discovery"),children:"Outcome Discovery Engine"})})]})]},t.name):t.hasDropdown&&t.items?e.jsxs(Te,{children:[e.jsxs(Ee,{className:"text-foreground hover:text-data-teal transition-colors font-medium data-accent focus:outline-none focus:ring-2 focus:ring-ring rounded px-2 py-2 min-h-[44px] inline-flex items-center gap-1",children:[t.name,e.jsx(ne,{className:"h-3 w-3"})]}),e.jsx(Oe,{align:"start",children:t.items.map(t=>e.jsx(Ae,{asChild:!0,children:e.jsx(V,{to:t.href,className:"cursor-pointer",onClick:()=>i(t.name.toLowerCase()),children:t.name})},t.name))})]},t.name):"isExternal"in t&&t.isExternal?e.jsx("a",{href:t.href,target:"_blank",rel:"noopener noreferrer",onClick:()=>i(t.name.toLowerCase()),className:"text-foreground hover:text-data-teal transition-colors font-medium data-accent focus:outline-none focus:ring-2 focus:ring-ring rounded px-2 py-2 min-h-[44px] inline-flex items-center",children:t.name},t.name):t.href.startsWith("#")?e.jsx("a",{href:t.href,onClick:()=>i(t.name.toLowerCase().replace(" & ","_").replace(" ","_")),className:"text-foreground hover:text-data-teal transition-colors font-medium data-accent focus:outline-none focus:ring-2 focus:ring-ring rounded px-2 py-2 min-h-[44px] inline-flex items-center",children:t.name},t.name):e.jsx(V,{to:t.href,onClick:()=>i(t.name.toLowerCase().replace(" & ","_").replace(" ","_")),className:"text-foreground hover:text-data-teal transition-colors font-medium data-accent focus:outline-none focus:ring-2 focus:ring-ring rounded px-2 py-2 min-h-[44px] inline-flex items-center",children:t.name},t.name))}),e.jsxs("div",{className:"hidden lg:flex items-center gap-3",children:[e.jsx(F,{variant:"outline",className:"clean-card border-data-teal/30 hover:border-data-teal/50 hover:bg-data-teal/5 focus:outline-none focus:ring-2 focus:ring-ring min-h-[44px] min-w-[44px]",asChild:!0,children:e.jsx(V,{to:"/contact",children:"Contact"})}),e.jsx(F,{onClick:a,"aria-label":"Request a demo",className:"data-accent bg-gradient-to-r from-data-orange to-data-teal hover:from-data-teal hover:to-data-blue focus:outline-none focus:ring-2 focus:ring-ring min-h-[44px] min-w-[44px]",children:"Request Demo"})]}),e.jsxs(_e,{open:t,onOpenChange:s,children:[e.jsx(we,{asChild:!0,className:"lg:hidden",children:e.jsx(F,{variant:"ghost",size:"sm",className:"focus:outline-none focus:ring-2 focus:ring-ring",children:t?e.jsx(Z,{className:"h-6 w-6"}):e.jsx(pe,{className:"h-6 w-6"})})}),e.jsxs(Se,{side:"right",className:"w-[300px] sm:w-[400px] flex flex-col",children:[e.jsxs("nav",{className:"flex-1 space-y-4 pt-6",children:[Xl.map(t=>t.hasDropdown&&t.items?e.jsxs("div",{children:[e.jsx("div",{className:"block text-foreground font-semibold py-2 px-4",children:t.name}),t.items.map(t=>e.jsx(V,{to:t.href,className:"block text-muted-foreground hover:text-data-teal transition-colors py-2 px-6 rounded hover:bg-surface/50",onClick:()=>{i(t.name.toLowerCase()),s(!1)},children:t.name},t.name))]},t.name):t.href.startsWith("#")?e.jsx("a",{href:t.href,className:"block text-foreground hover:text-data-teal transition-colors font-medium py-2 px-4 rounded hover:bg-surface/50",onClick:()=>{i(t.name.toLowerCase().replace(" & ","_").replace(" ","_")),s(!1)},children:t.name},t.name):e.jsx(V,{to:t.href,className:"block text-foreground hover:text-data-teal transition-colors font-medium py-2 px-4 rounded hover:bg-surface/50",onClick:()=>{i(t.name.toLowerCase().replace(" & ","_").replace(" ","_")),s(!1)},children:t.name},t.name)),e.jsx("div",{className:"pt-4 px-4",children:e.jsx(F,{variant:"outline",className:"w-full mb-3 clean-card border-data-teal/30",asChild:!0,children:e.jsx(V,{to:"/contact",onClick:()=>s(!1),children:"Contact"})})})]}),e.jsx("div",{className:"border-t border-outline/20 pt-4",children:e.jsx(F,{onClick:()=>{a(),s(!1)},className:"w-full data-accent bg-gradient-to-r from-data-orange to-data-teal h-12 text-base font-semibold",children:"Request Demo"})})]})]})]})})}),e.jsx(Ql,{open:r,onOpenChange:n,defaultIntent:"demo",context:{sourcePage:window.location.pathname,sourceButton:"header_request_demo"}})]})};var tc="horizontal",sc=["horizontal","vertical"],rc=D.forwardRef((t,s)=>{const{decorative:r,orientation:n=tc,...i}=t,a=function(e){return sc.includes(e)}(n)?n:tc,o=r?{role:"none"}:{"aria-orientation":"vertical"===a?a:void 0,role:"separator"};return e.jsx(x.div,{"data-orientation":a,...o,...i,ref:s})});rc.displayName="Separator";var nc=rc;const ic=D.forwardRef(({className:t,orientation:s="horizontal",decorative:r=!0,...n},i)=>e.jsx(nc,{ref:i,decorative:r,orientation:s,className:W("shrink-0 bg-border","horizontal"===s?"h-[1px] w-full":"h-full w-[1px]",t),...n}));ic.displayName=nc.displayName;const ac=[{title:"Products & Solutions",links:[{label:"VISTA",href:"/solutions/vista"},{label:"SENTRA",href:"/solutions/sentra"},{label:"iPAM",href:"/solutions/ipam"},{label:"NeuroSight",href:"/solutions/neurosight"},{label:"SkyAide",href:"/products/skyaide"}]},{title:"Services",links:[{label:"Agentic AI",href:"/services/agentic-ai"},{label:"GenAI Accelerator",href:"/services/genai-accelerator"},{label:"CV FastTrack",href:"/services/cv-fasttrack"},{label:"Platform Modernization",href:"/services/platform-modernization"},{label:"MLOps",href:"/services/mlops"},{label:"Security & Compliance",href:"/services/security-compliance"}]},{title:"Industries",links:[{label:"Manufacturing",href:"/industries/manufacturing"},{label:"Warehousing & Logistics",href:"/industries/warehousing-logistics"},{label:"Retail",href:"/industries/retail"},{label:"Insurance & Government",href:"/industries/insurance-government"},{label:"View all",href:"/industries"}]},{title:"Resources",links:[{label:"ROI Calculator",href:"/roi-calculator"},{label:"How we measure",href:"/how-we-measure"},{label:"Customers",href:"/customers"},{label:"Resources",href:"/resources"},{label:"Blog",href:"https://blog.allerin.com"}]},{title:"Company",links:[{label:"About",href:"/about"},{label:"Careers",href:"/careers"},{label:"Trust Center",href:"/trust"},{label:"Component Library",href:"/component-library"},{label:"Contact",href:"mailto:analytics@allerin.com"}]}],oc=[{icon:e.jsx(ge,{className:"h-4 w-4"}),label:"+1-512-200-2416",href:"tel:+15122002416"},{icon:e.jsx(he,{className:"h-4 w-4"}),label:"analytics@allerin.com",href:"mailto:analytics@allerin.com"},{icon:e.jsx(fe,{className:"h-4 w-4"}),label:"2921 Prado Street, Unit A, Austin, TX 78702",href:"https://maps.google.com/?q=2921+Prado+Street+Unit+A+Austin+TX+78702"}],lc=[{icon:e.jsx(ve,{className:"h-5 w-5","aria-hidden":"true"}),href:"https://x.com/allerint",label:"Allerin on Twitter",external:!0},{icon:e.jsx(de,{className:"h-5 w-5","aria-hidden":"true"}),href:"https://www.linkedin.com/company/allerin/",label:"Allerin on LinkedIn",external:!0},{icon:e.jsx(ce,{className:"h-5 w-5","aria-hidden":"true"}),href:"https://github.com/allerin",label:"Allerin on GitHub",external:!0}],cc=()=>{const[t,s]=D.useState(""),[r,n]=D.useState(!1);return e.jsx("footer",{className:"relative mt-section-y",children:e.jsxs("div",{className:"bg-background",children:[e.jsx("div",{className:"container py-4xl",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-7 gap-3xl",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx("div",{className:"flex items-center mb-4",children:e.jsx("img",{src:M,alt:"Allerin Technologies",className:"h-10 w-auto",width:160,height:40,loading:"lazy",decoding:"async"})}),e.jsx("p",{className:"text-muted-foreground mb-xl leading-relaxed",children:"Allerin builds production-grade AI: agentic systems, computer vision, and analytics, shipped with KPI gates, reversible rollouts, and measurable outcomes."}),e.jsx("div",{className:"space-y-sm mb-xl",children:oc.map((t,s)=>e.jsxs("a",{href:t.href,className:"flex items-center text-muted-foreground hover:text-data-teal transition-colors group",children:[e.jsx("span",{className:"mr-sm text-data-orange group-hover:text-data-teal transition-colors",children:t.icon}),t.label]},s))}),e.jsx("div",{className:"flex gap-sm",children:lc.map((t,s)=>e.jsx(F,{variant:"ghost",size:"sm",className:"data-accent clean-card hover:bg-data-teal/10 hover:text-data-teal transition-all",asChild:!0,children:e.jsx("a",{href:t.href,"aria-label":t.label,rel:"me noopener",target:"_blank",onClick:()=>{t.label},children:t.icon})},s))})]}),ac.map(t=>e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-foreground mb-lg data-accent",children:t.title}),e.jsx("ul",{className:"space-y-sm",children:t.links.map(s=>{const r=s.href.startsWith("http")||s.href.startsWith("mailto:");return e.jsx("li",{children:r?e.jsx("a",{href:s.href,onClick:()=>(t.title,void s.label),className:"text-muted-foreground hover:text-data-teal transition-colors text-sm",target:s.href.startsWith("http")?"_blank":void 0,rel:s.href.startsWith("http")?"noopener noreferrer":void 0,children:s.label}):e.jsx(V,{to:s.href,onClick:()=>(t.title,void s.label),className:"text-muted-foreground hover:text-data-teal transition-colors text-sm",children:s.label})},s.label)})})]},t.title))]})}),e.jsx(ic,{className:"opacity-20"}),e.jsxs("div",{className:"container py-2xl",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2xl mb-xl",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-foreground mb-sm",children:"Stay Updated"}),e.jsxs("form",{onSubmit:async e=>{if(e.preventDefault(),t){n(!0);try{const{data:e,error:r}=await Ml.functions.invoke("newsletter-subscribe",{body:{email:t,source:"footer"}});if(r)throw r;te.success(e.message||"Thanks for subscribing!"),s("")}catch(r){te.error("Failed to subscribe. Please try again.")}finally{n(!1)}}else te.error("Please enter your email")},className:"flex gap-xs mb-xs",children:[e.jsx(q,{type:"email",placeholder:"Enter your email",value:t,onChange:e=>s(e.target.value),required:!0,disabled:r,className:"clean-card border-data-teal/30 focus:border-data-teal bg-background"}),e.jsx(F,{type:"submit",disabled:r,className:"bg-gradient-to-r from-data-orange to-data-teal whitespace-nowrap",children:r?"...":"Subscribe"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["By subscribing, you agree to our"," ",e.jsx(V,{to:"/privacy-policy",className:"underline hover:text-data-teal",onClick:()=>{},children:"Privacy Policy"}),". We respect your privacy and use double opt-in."]})]}),e.jsx("div",{className:"flex flex-col justify-end",children:e.jsxs("div",{className:"flex flex-wrap gap-lg text-sm text-muted-foreground justify-start md:justify-end",children:[e.jsx(V,{to:"/privacy-policy",onClick:()=>{},className:"hover:text-data-teal transition-colors",children:"Privacy Policy"}),e.jsx(V,{to:"/terms-of-service",onClick:()=>{},className:"hover:text-data-teal transition-colors",children:"Terms of Service"}),e.jsx(V,{to:"/cookies-policy",onClick:()=>{},className:"hover:text-data-teal transition-colors",children:"Cookies Policy"}),e.jsx("button",{onClick:()=>{ee()},className:"hover:text-data-teal transition-colors text-left",children:"Cookie Preferences"}),e.jsx(V,{to:"/disclaimer",onClick:()=>{},className:"hover:text-data-teal transition-colors",children:"Disclaimer"}),e.jsx(V,{to:"/dei",onClick:()=>{},className:"hover:text-data-teal transition-colors",children:"DEI Policy"})]})})]}),e.jsx(ic,{className:"opacity-20 mb-xl"}),e.jsx("div",{className:"text-center text-sm text-muted-foreground",children:e.jsxs("p",{children:["© ",(new Date).getFullYear()," Allerin. All rights reserved."]})})]})]})})};export{Vr as A,Ur as B,ae as C,Ql as D,Dr as E,cc as F,ce as G,ec as H,Pr as I,de as L,he as M,ge as P,wn as R,ye as S,ve as T,be as U,le as a,oe as b,ue as c,fe as d,pe as e,me as f,Nr as g,Ir as h,Fr as i,zr as j,Wr as k,Zr as l,Kr as m,Br as n,$r as o,Wl as p,Zl as q,Kl as r,Ml as s,es as t,Wt as u,Jl as v,Jr as w,ic as x,kn as y,Rr as z};