(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))a(l);new MutationObserver(l=>{for(const u of l)if(u.type==="childList")for(const c of u.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&a(c)}).observe(document,{childList:!0,subtree:!0});function s(l){const u={};return l.integrity&&(u.integrity=l.integrity),l.referrerPolicy&&(u.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?u.credentials="include":l.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function a(l){if(l.ep)return;l.ep=!0;const u=s(l);fetch(l.href,u)}})();var wh={exports:{}},ur={};/** * @license React * react-jsx-runtime.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var wy;function xS(){if(wy)return ur;wy=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function s(a,l,u){var c=null;if(u!==void 0&&(c=""+u),l.key!==void 0&&(c=""+l.key),"key"in l){u={};for(var d in l)d!=="key"&&(u[d]=l[d])}else u=l;return l=u.ref,{$$typeof:n,type:a,key:c,ref:l!==void 0?l:null,props:u}}return ur.Fragment=e,ur.jsx=s,ur.jsxs=s,ur}var xy;function _S(){return xy||(xy=1,wh.exports=xS()),wh.exports}var b=_S(),xh={exports:{}},ye={};/** * @license React * react.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var _y;function SS(){if(_y)return ye;_y=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),l=Symbol.for("react.profiler"),u=Symbol.for("react.consumer"),c=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),v=Symbol.for("react.activity"),w=Symbol.iterator;function _(A){return A===null||typeof A!="object"?null:(A=w&&A[w]||A["@@iterator"],typeof A=="function"?A:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,k={};function C(A,$,Q){this.props=A,this.context=$,this.refs=k,this.updater=Q||S}C.prototype.isReactComponent={},C.prototype.setState=function(A,$){if(typeof A!="object"&&typeof A!="function"&&A!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,A,$,"setState")},C.prototype.forceUpdate=function(A){this.updater.enqueueForceUpdate(this,A,"forceUpdate")};function N(){}N.prototype=C.prototype;function O(A,$,Q){this.props=A,this.context=$,this.refs=k,this.updater=Q||S}var z=O.prototype=new N;z.constructor=O,E(z,C.prototype),z.isPureReactComponent=!0;var F=Array.isArray;function J(){}var G={H:null,A:null,T:null,S:null},Y=Object.prototype.hasOwnProperty;function Z(A,$,Q){var ne=Q.ref;return{$$typeof:n,type:A,key:$,ref:ne!==void 0?ne:null,props:Q}}function te(A,$){return Z(A.type,$,A.props)}function de(A){return typeof A=="object"&&A!==null&&A.$$typeof===n}function fe(A){var $={"=":"=0",":":"=2"};return"$"+A.replace(/[=:]/g,function(Q){return $[Q]})}var qe=/\/+/g;function X(A,$){return typeof A=="object"&&A!==null&&A.key!=null?fe(""+A.key):$.toString(36)}function ue(A){switch(A.status){case"fulfilled":return A.value;case"rejected":throw A.reason;default:switch(typeof A.status=="string"?A.then(J,J):(A.status="pending",A.then(function($){A.status==="pending"&&(A.status="fulfilled",A.value=$)},function($){A.status==="pending"&&(A.status="rejected",A.reason=$)})),A.status){case"fulfilled":return A.value;case"rejected":throw A.reason}}throw A}function D(A,$,Q,ne,ge){var pe=typeof A;(pe==="undefined"||pe==="boolean")&&(A=null);var Ae=!1;if(A===null)Ae=!0;else switch(pe){case"bigint":case"string":case"number":Ae=!0;break;case"object":switch(A.$$typeof){case n:case e:Ae=!0;break;case g:return Ae=A._init,D(Ae(A._payload),$,Q,ne,ge)}}if(Ae)return ge=ge(A),Ae=ne===""?"."+X(A,0):ne,F(ge)?(Q="",Ae!=null&&(Q=Ae.replace(qe,"$&/")+"/"),D(ge,$,Q,"",function(Ui){return Ui})):ge!=null&&(de(ge)&&(ge=te(ge,Q+(ge.key==null||A&&A.key===ge.key?"":(""+ge.key).replace(qe,"$&/")+"/")+Ae)),$.push(ge)),1;Ae=0;var lt=ne===""?".":ne+":";if(F(A))for(var Ie=0;Ie>>1,me=D[re];if(0>>1;rel(Q,ee))nel(ge,Q)?(D[re]=ge,D[ne]=ee,re=ne):(D[re]=Q,D[$]=ee,re=$);else if(nel(ge,ee))D[re]=ge,D[ne]=ee,re=ne;else break e}}return I}function l(D,I){var ee=D.sortIndex-I.sortIndex;return ee!==0?ee:D.id-I.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var u=performance;n.unstable_now=function(){return u.now()}}else{var c=Date,d=c.now();n.unstable_now=function(){return c.now()-d}}var m=[],p=[],g=1,v=null,w=3,_=!1,S=!1,E=!1,k=!1,C=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,O=typeof setImmediate<"u"?setImmediate:null;function z(D){for(var I=s(p);I!==null;){if(I.callback===null)a(p);else if(I.startTime<=D)a(p),I.sortIndex=I.expirationTime,e(m,I);else break;I=s(p)}}function F(D){if(E=!1,z(D),!S)if(s(m)!==null)S=!0,J||(J=!0,fe());else{var I=s(p);I!==null&&ue(F,I.startTime-D)}}var J=!1,G=-1,Y=5,Z=-1;function te(){return k?!0:!(n.unstable_now()-ZD&&te());){var re=v.callback;if(typeof re=="function"){v.callback=null,w=v.priorityLevel;var me=re(v.expirationTime<=D);if(D=n.unstable_now(),typeof me=="function"){v.callback=me,z(D),I=!0;break t}v===s(m)&&a(m),z(D)}else a(m);v=s(m)}if(v!==null)I=!0;else{var A=s(p);A!==null&&ue(F,A.startTime-D),I=!1}}break e}finally{v=null,w=ee,_=!1}I=void 0}}finally{I?fe():J=!1}}}var fe;if(typeof O=="function")fe=function(){O(de)};else if(typeof MessageChannel<"u"){var qe=new MessageChannel,X=qe.port2;qe.port1.onmessage=de,fe=function(){X.postMessage(null)}}else fe=function(){C(de,0)};function ue(D,I){G=C(function(){D(n.unstable_now())},I)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(D){D.callback=null},n.unstable_forceFrameRate=function(D){0>D||125re?(D.sortIndex=ee,e(p,D),s(m)===null&&D===s(p)&&(E?(N(G),G=-1):E=!0,ue(F,ee-re))):(D.sortIndex=me,e(m,D),S||_||(S=!0,J||(J=!0,fe()))),D},n.unstable_shouldYield=te,n.unstable_wrapCallback=function(D){var I=w;return function(){var ee=w;w=I;try{return D.apply(this,arguments)}finally{w=ee}}}})(Th)),Th}var Ey;function ES(){return Ey||(Ey=1,Sh.exports=TS()),Sh.exports}var Eh={exports:{}},bt={};/** * @license React * react-dom.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Ay;function AS(){if(Ay)return bt;Ay=1;var n=Vd();function e(m){var p="https://react.dev/errors/"+m;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),Eh.exports=AS(),Eh.exports}/** * @license React * react-dom-client.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Cy;function CS(){if(Cy)return cr;Cy=1;var n=ES(),e=Vd(),s=RS();function a(t){var i="https://react.dev/errors/"+t;if(1me||(t.current=re[me],re[me]=null,me--)}function Q(t,i){me++,re[me]=t.current,t.current=i}var ne=A(null),ge=A(null),pe=A(null),Ae=A(null);function lt(t,i){switch(Q(pe,i),Q(ge,t),Q(ne,null),i.nodeType){case 9:case 11:t=(t=i.documentElement)&&(t=t.namespaceURI)?qg(t):0;break;default:if(t=i.tagName,i=i.namespaceURI)i=qg(i),t=Gg(i,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}$(ne),Q(ne,t)}function Ie(){$(ne),$(ge),$(pe)}function Ui(t){t.memoizedState!==null&&Q(Ae,t);var i=ne.current,r=Gg(i,t.type);i!==r&&(Q(ge,t),Q(ne,r))}function hs(t){ge.current===t&&($(ne),$(ge)),Ae.current===t&&($(Ae),ar._currentValue=ee)}var pa,Gr;function jn(t){if(pa===void 0)try{throw Error()}catch(r){var i=r.stack.trim().match(/\n( *(at )?)/);pa=i&&i[1]||"",Gr=-1)":-1h||T[o]!==U[h]){var V=` `+T[o].replace(" at new "," at ");return t.displayName&&V.includes("")&&(V=V.replace("",t.displayName)),V}while(1<=o&&0<=h);break}}}finally{ga=!1,Error.prepareStackTrace=r}return(r=t?t.displayName||t.name:"")?jn(r):""}function be(t,i){switch(t.tag){case 26:case 27:case 5:return jn(t.type);case 16:return jn("Lazy");case 13:return t.child!==i&&i!==null?jn("Suspense Fallback"):jn("Suspense");case 19:return jn("SuspenseList");case 0:case 15:return K(t.type,!1);case 11:return K(t.type.render,!1);case 1:return K(t.type,!0);case 31:return jn("Activity");default:return""}}function Ke(t){try{var i="",r=null;do i+=be(t,r),r=t,t=t.return;while(t);return i}catch(o){return` Error generating stack: `+o.message+` `+o.stack}}var Dt=Object.prototype.hasOwnProperty,On=n.unstable_scheduleCallback,Ir=n.unstable_cancelCallback,gn=n.unstable_shouldYield,Kr=n.unstable_requestPaint,De=n.unstable_now,yn=n.unstable_getCurrentPriorityLevel,xf=n.unstable_ImmediatePriority,_f=n.unstable_UserBlockingPriority,Fr=n.unstable_NormalPriority,nx=n.unstable_LowPriority,Sf=n.unstable_IdlePriority,ix=n.log,sx=n.unstable_setDisableYieldValue,ya=null,Mt=null;function ii(t){if(typeof ix=="function"&&sx(t),Mt&&typeof Mt.setStrictMode=="function")try{Mt.setStrictMode(ya,t)}catch{}}var Ut=Math.clz32?Math.clz32:ox,ax=Math.log,rx=Math.LN2;function ox(t){return t>>>=0,t===0?32:31-(ax(t)/rx|0)|0}var Yr=256,Xr=262144,Jr=4194304;function Bi(t){var i=t&42;if(i!==0)return i;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function Qr(t,i,r){var o=t.pendingLanes;if(o===0)return 0;var h=0,f=t.suspendedLanes,y=t.pingedLanes;t=t.warmLanes;var x=o&134217727;return x!==0?(o=x&~f,o!==0?h=Bi(o):(y&=x,y!==0?h=Bi(y):r||(r=x&~t,r!==0&&(h=Bi(r))))):(x=o&~f,x!==0?h=Bi(x):y!==0?h=Bi(y):r||(r=o&~t,r!==0&&(h=Bi(r)))),h===0?0:i!==0&&i!==h&&(i&f)===0&&(f=h&-h,r=i&-i,f>=r||f===32&&(r&4194048)!==0)?i:h}function va(t,i){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&i)===0}function lx(t,i){switch(t){case 1:case 2:case 4:case 8:case 64:return i+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return i+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Tf(){var t=Jr;return Jr<<=1,(Jr&62914560)===0&&(Jr=4194304),t}function lu(t){for(var i=[],r=0;31>r;r++)i.push(t);return i}function ba(t,i){t.pendingLanes|=i,i!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function ux(t,i,r,o,h,f){var y=t.pendingLanes;t.pendingLanes=r,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=r,t.entangledLanes&=r,t.errorRecoveryDisabledLanes&=r,t.shellSuspendCounter=0;var x=t.entanglements,T=t.expirationTimes,U=t.hiddenUpdates;for(r=y&~r;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var px=/[\n"\\]/g;function Kt(t){return t.replace(px,function(i){return"\\"+i.charCodeAt(0).toString(16)+" "})}function mu(t,i,r,o,h,f,y,x){t.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?t.type=y:t.removeAttribute("type"),i!=null?y==="number"?(i===0&&t.value===""||t.value!=i)&&(t.value=""+It(i)):t.value!==""+It(i)&&(t.value=""+It(i)):y!=="submit"&&y!=="reset"||t.removeAttribute("value"),i!=null?pu(t,y,It(i)):r!=null?pu(t,y,It(r)):o!=null&&t.removeAttribute("value"),h==null&&f!=null&&(t.defaultChecked=!!f),h!=null&&(t.checked=h&&typeof h!="function"&&typeof h!="symbol"),x!=null&&typeof x!="function"&&typeof x!="symbol"&&typeof x!="boolean"?t.name=""+It(x):t.removeAttribute("name")}function Lf(t,i,r,o,h,f,y,x){if(f!=null&&typeof f!="function"&&typeof f!="symbol"&&typeof f!="boolean"&&(t.type=f),i!=null||r!=null){if(!(f!=="submit"&&f!=="reset"||i!=null)){fu(t);return}r=r!=null?""+It(r):"",i=i!=null?""+It(i):r,x||i===t.value||(t.value=i),t.defaultValue=i}o=o??h,o=typeof o!="function"&&typeof o!="symbol"&&!!o,t.checked=x?t.checked:!!o,t.defaultChecked=!!o,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(t.name=y),fu(t)}function pu(t,i,r){i==="number"&&eo(t.ownerDocument)===t||t.defaultValue===""+r||(t.defaultValue=""+r)}function ys(t,i,r,o){if(t=t.options,i){i={};for(var h=0;h"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),wu=!1;if(Mn)try{var Sa={};Object.defineProperty(Sa,"passive",{get:function(){wu=!0}}),window.addEventListener("test",Sa,Sa),window.removeEventListener("test",Sa,Sa)}catch{wu=!1}var ai=null,xu=null,no=null;function Gf(){if(no)return no;var t,i=xu,r=i.length,o,h="value"in ai?ai.value:ai.textContent,f=h.length;for(t=0;t=Aa),Jf=" ",Qf=!1;function Zf(t,i){switch(t){case"keyup":return qx.indexOf(i.keyCode)!==-1;case"keydown":return i.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Wf(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var xs=!1;function Ix(t,i){switch(t){case"compositionend":return Wf(i);case"keypress":return i.which!==32?null:(Qf=!0,Jf);case"textInput":return t=i.data,t===Jf&&Qf?null:t;default:return null}}function Kx(t,i){if(xs)return t==="compositionend"||!Au&&Zf(t,i)?(t=Gf(),no=xu=ai=null,xs=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(i.ctrlKey||i.altKey||i.metaKey)||i.ctrlKey&&i.altKey){if(i.char&&1=i)return{node:r,offset:i-t};t=o}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=om(r)}}function um(t,i){return t&&i?t===i?!0:t&&t.nodeType===3?!1:i&&i.nodeType===3?um(t,i.parentNode):"contains"in t?t.contains(i):t.compareDocumentPosition?!!(t.compareDocumentPosition(i)&16):!1:!1}function cm(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var i=eo(t.document);i instanceof t.HTMLIFrameElement;){try{var r=typeof i.contentWindow.location.href=="string"}catch{r=!1}if(r)t=i.contentWindow;else break;i=eo(t.document)}return i}function ku(t){var i=t&&t.nodeName&&t.nodeName.toLowerCase();return i&&(i==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||i==="textarea"||t.contentEditable==="true")}var e_=Mn&&"documentMode"in document&&11>=document.documentMode,_s=null,ju=null,ja=null,Ou=!1;function hm(t,i,r){var o=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;Ou||_s==null||_s!==eo(o)||(o=_s,"selectionStart"in o&&ku(o)?o={start:o.selectionStart,end:o.selectionEnd}:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection(),o={anchorNode:o.anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset}),ja&&ka(ja,o)||(ja=o,o=Jo(ju,"onSelect"),0>=y,h-=y,vn=1<<32-Ut(i)+h|r<we?(Te=oe,oe=null):Te=oe.sibling;var Ce=B(j,oe,M[we],H);if(Ce===null){oe===null&&(oe=Te);break}t&&oe&&Ce.alternate===null&&i(j,oe),R=f(Ce,R,we),Re===null?le=Ce:Re.sibling=Ce,Re=Ce,oe=Te}if(we===M.length)return r(j,oe),Ee&&Bn(j,we),le;if(oe===null){for(;wewe?(Te=oe,oe=null):Te=oe.sibling;var Ri=B(j,oe,Ce.value,H);if(Ri===null){oe===null&&(oe=Te);break}t&&oe&&Ri.alternate===null&&i(j,oe),R=f(Ri,R,we),Re===null?le=Ri:Re.sibling=Ri,Re=Ri,oe=Te}if(Ce.done)return r(j,oe),Ee&&Bn(j,we),le;if(oe===null){for(;!Ce.done;we++,Ce=M.next())Ce=q(j,Ce.value,H),Ce!==null&&(R=f(Ce,R,we),Re===null?le=Ce:Re.sibling=Ce,Re=Ce);return Ee&&Bn(j,we),le}for(oe=o(oe);!Ce.done;we++,Ce=M.next())Ce=L(oe,j,we,Ce.value,H),Ce!==null&&(t&&Ce.alternate!==null&&oe.delete(Ce.key===null?we:Ce.key),R=f(Ce,R,we),Re===null?le=Ce:Re.sibling=Ce,Re=Ce);return t&&oe.forEach(function(wS){return i(j,wS)}),Ee&&Bn(j,we),le}function Be(j,R,M,H){if(typeof M=="object"&&M!==null&&M.type===E&&M.key===null&&(M=M.props.children),typeof M=="object"&&M!==null){switch(M.$$typeof){case _:e:{for(var le=M.key;R!==null;){if(R.key===le){if(le=M.type,le===E){if(R.tag===7){r(j,R.sibling),H=h(R,M.props.children),H.return=j,j=H;break e}}else if(R.elementType===le||typeof le=="object"&&le!==null&&le.$$typeof===Y&&Fi(le)===R.type){r(j,R.sibling),H=h(R,M.props),Ba(H,M),H.return=j,j=H;break e}r(j,R);break}else i(j,R);R=R.sibling}M.type===E?(H=$i(M.props.children,j.mode,H,M.key),H.return=j,j=H):(H=fo(M.type,M.key,M.props,null,j.mode,H),Ba(H,M),H.return=j,j=H)}return y(j);case S:e:{for(le=M.key;R!==null;){if(R.key===le)if(R.tag===4&&R.stateNode.containerInfo===M.containerInfo&&R.stateNode.implementation===M.implementation){r(j,R.sibling),H=h(R,M.children||[]),H.return=j,j=H;break e}else{r(j,R);break}else i(j,R);R=R.sibling}H=zu(M,j.mode,H),H.return=j,j=H}return y(j);case Y:return M=Fi(M),Be(j,R,M,H)}if(ue(M))return ie(j,R,M,H);if(fe(M)){if(le=fe(M),typeof le!="function")throw Error(a(150));return M=le.call(M),he(j,R,M,H)}if(typeof M.then=="function")return Be(j,R,wo(M),H);if(M.$$typeof===O)return Be(j,R,go(j,M),H);xo(j,M)}return typeof M=="string"&&M!==""||typeof M=="number"||typeof M=="bigint"?(M=""+M,R!==null&&R.tag===6?(r(j,R.sibling),H=h(R,M),H.return=j,j=H):(r(j,R),H=Lu(M,j.mode,H),H.return=j,j=H),y(j)):r(j,R)}return function(j,R,M,H){try{Ua=0;var le=Be(j,R,M,H);return Ds=null,le}catch(oe){if(oe===Ns||oe===vo)throw oe;var Re=Lt(29,oe,null,j.mode);return Re.lanes=H,Re.return=j,Re}finally{}}}var Xi=Mm(!0),Um=Mm(!1),ci=!1;function Ju(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Qu(t,i){t=t.updateQueue,i.updateQueue===t&&(i.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function hi(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function di(t,i,r){var o=t.updateQueue;if(o===null)return null;if(o=o.shared,(ke&2)!==0){var h=o.pending;return h===null?i.next=i:(i.next=h.next,h.next=i),o.pending=i,i=ho(t),vm(t,null,r),i}return co(t,o,i,r),ho(t)}function La(t,i,r){if(i=i.updateQueue,i!==null&&(i=i.shared,(r&4194048)!==0)){var o=i.lanes;o&=t.pendingLanes,r|=o,i.lanes=r,Af(t,r)}}function Zu(t,i){var r=t.updateQueue,o=t.alternate;if(o!==null&&(o=o.updateQueue,r===o)){var h=null,f=null;if(r=r.firstBaseUpdate,r!==null){do{var y={lane:r.lane,tag:r.tag,payload:r.payload,callback:null,next:null};f===null?h=f=y:f=f.next=y,r=r.next}while(r!==null);f===null?h=f=i:f=f.next=i}else h=f=i;r={baseState:o.baseState,firstBaseUpdate:h,lastBaseUpdate:f,shared:o.shared,callbacks:o.callbacks},t.updateQueue=r;return}t=r.lastBaseUpdate,t===null?r.firstBaseUpdate=i:t.next=i,r.lastBaseUpdate=i}var Wu=!1;function za(){if(Wu){var t=Os;if(t!==null)throw t}}function Va(t,i,r,o){Wu=!1;var h=t.updateQueue;ci=!1;var f=h.firstBaseUpdate,y=h.lastBaseUpdate,x=h.shared.pending;if(x!==null){h.shared.pending=null;var T=x,U=T.next;T.next=null,y===null?f=U:y.next=U,y=T;var V=t.alternate;V!==null&&(V=V.updateQueue,x=V.lastBaseUpdate,x!==y&&(x===null?V.firstBaseUpdate=U:x.next=U,V.lastBaseUpdate=T))}if(f!==null){var q=h.baseState;y=0,V=U=T=null,x=f;do{var B=x.lane&-536870913,L=B!==x.lane;if(L?(Se&B)===B:(o&B)===B){B!==0&&B===js&&(Wu=!0),V!==null&&(V=V.next={lane:0,tag:x.tag,payload:x.payload,callback:null,next:null});e:{var ie=t,he=x;B=i;var Be=r;switch(he.tag){case 1:if(ie=he.payload,typeof ie=="function"){q=ie.call(Be,q,B);break e}q=ie;break e;case 3:ie.flags=ie.flags&-65537|128;case 0:if(ie=he.payload,B=typeof ie=="function"?ie.call(Be,q,B):ie,B==null)break e;q=v({},q,B);break e;case 2:ci=!0}}B=x.callback,B!==null&&(t.flags|=64,L&&(t.flags|=8192),L=h.callbacks,L===null?h.callbacks=[B]:L.push(B))}else L={lane:B,tag:x.tag,payload:x.payload,callback:x.callback,next:null},V===null?(U=V=L,T=q):V=V.next=L,y|=B;if(x=x.next,x===null){if(x=h.shared.pending,x===null)break;L=x,x=L.next,L.next=null,h.lastBaseUpdate=L,h.shared.pending=null}}while(!0);V===null&&(T=q),h.baseState=T,h.firstBaseUpdate=U,h.lastBaseUpdate=V,f===null&&(h.shared.lanes=0),yi|=y,t.lanes=y,t.memoizedState=q}}function Bm(t,i){if(typeof t!="function")throw Error(a(191,t));t.call(i)}function Lm(t,i){var r=t.callbacks;if(r!==null)for(t.callbacks=null,t=0;tf?f:8;var y=D.T,x={};D.T=x,vc(t,!1,i,r);try{var T=h(),U=D.S;if(U!==null&&U(x,T),T!==null&&typeof T=="object"&&typeof T.then=="function"){var V=u_(T,o);$a(t,i,V,$t(t))}else $a(t,i,o,$t(t))}catch(q){$a(t,i,{then:function(){},status:"rejected",reason:q},$t())}finally{I.p=f,y!==null&&x.types!==null&&(y.types=x.types),D.T=y}}function p_(){}function gc(t,i,r,o){if(t.tag!==5)throw Error(a(476));var h=pp(t).queue;mp(t,h,i,ee,r===null?p_:function(){return gp(t),r(o)})}function pp(t){var i=t.memoizedState;if(i!==null)return i;i={memoizedState:ee,baseState:ee,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Pn,lastRenderedState:ee},next:null};var r={};return i.next={memoizedState:r,baseState:r,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Pn,lastRenderedState:r},next:null},t.memoizedState=i,t=t.alternate,t!==null&&(t.memoizedState=i),i}function gp(t){var i=pp(t);i.next===null&&(i=t.alternate.memoizedState),$a(t,i.next.queue,{},$t())}function yc(){return mt(ar)}function yp(){return Ze().memoizedState}function vp(){return Ze().memoizedState}function g_(t){for(var i=t.return;i!==null;){switch(i.tag){case 24:case 3:var r=$t();t=hi(r);var o=di(i,t,r);o!==null&&(Ot(o,i,r),La(o,i,r)),i={cache:Ku()},t.payload=i;return}i=i.return}}function y_(t,i,r){var o=$t();r={lane:o,revertLane:0,gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Oo(t)?wp(i,r):(r=Uu(t,i,r,o),r!==null&&(Ot(r,t,o),xp(r,i,o)))}function bp(t,i,r){var o=$t();$a(t,i,r,o)}function $a(t,i,r,o){var h={lane:o,revertLane:0,gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null};if(Oo(t))wp(i,h);else{var f=t.alternate;if(t.lanes===0&&(f===null||f.lanes===0)&&(f=i.lastRenderedReducer,f!==null))try{var y=i.lastRenderedState,x=f(y,r);if(h.hasEagerState=!0,h.eagerState=x,Bt(x,y))return co(t,i,h,0),Le===null&&uo(),!1}catch{}finally{}if(r=Uu(t,i,h,o),r!==null)return Ot(r,t,o),xp(r,i,o),!0}return!1}function vc(t,i,r,o){if(o={lane:2,revertLane:Jc(),gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Oo(t)){if(i)throw Error(a(479))}else i=Uu(t,r,o,2),i!==null&&Ot(i,t,2)}function Oo(t){var i=t.alternate;return t===ve||i!==null&&i===ve}function wp(t,i){Us=To=!0;var r=t.pending;r===null?i.next=i:(i.next=r.next,r.next=i),t.pending=i}function xp(t,i,r){if((r&4194048)!==0){var o=i.lanes;o&=t.pendingLanes,r|=o,i.lanes=r,Af(t,r)}}var qa={readContext:mt,use:Ro,useCallback:Fe,useContext:Fe,useEffect:Fe,useImperativeHandle:Fe,useLayoutEffect:Fe,useInsertionEffect:Fe,useMemo:Fe,useReducer:Fe,useRef:Fe,useState:Fe,useDebugValue:Fe,useDeferredValue:Fe,useTransition:Fe,useSyncExternalStore:Fe,useId:Fe,useHostTransitionStatus:Fe,useFormState:Fe,useActionState:Fe,useOptimistic:Fe,useMemoCache:Fe,useCacheRefresh:Fe};qa.useEffectEvent=Fe;var _p={readContext:mt,use:Ro,useCallback:function(t,i){return xt().memoizedState=[t,i===void 0?null:i],t},useContext:mt,useEffect:ap,useImperativeHandle:function(t,i,r){r=r!=null?r.concat([t]):null,ko(4194308,4,up.bind(null,i,t),r)},useLayoutEffect:function(t,i){return ko(4194308,4,t,i)},useInsertionEffect:function(t,i){ko(4,2,t,i)},useMemo:function(t,i){var r=xt();i=i===void 0?null:i;var o=t();if(Ji){ii(!0);try{t()}finally{ii(!1)}}return r.memoizedState=[o,i],o},useReducer:function(t,i,r){var o=xt();if(r!==void 0){var h=r(i);if(Ji){ii(!0);try{r(i)}finally{ii(!1)}}}else h=i;return o.memoizedState=o.baseState=h,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:h},o.queue=t,t=t.dispatch=y_.bind(null,ve,t),[o.memoizedState,t]},useRef:function(t){var i=xt();return t={current:t},i.memoizedState=t},useState:function(t){t=hc(t);var i=t.queue,r=bp.bind(null,ve,i);return i.dispatch=r,[t.memoizedState,r]},useDebugValue:mc,useDeferredValue:function(t,i){var r=xt();return pc(r,t,i)},useTransition:function(){var t=hc(!1);return t=mp.bind(null,ve,t.queue,!0,!1),xt().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,i,r){var o=ve,h=xt();if(Ee){if(r===void 0)throw Error(a(407));r=r()}else{if(r=i(),Le===null)throw Error(a(349));(Se&127)!==0||qm(o,i,r)}h.memoizedState=r;var f={value:r,getSnapshot:i};return h.queue=f,ap(Im.bind(null,o,f,t),[t]),o.flags|=2048,Ls(9,{destroy:void 0},Gm.bind(null,o,f,r,i),null),r},useId:function(){var t=xt(),i=Le.identifierPrefix;if(Ee){var r=bn,o=vn;r=(o&~(1<<32-Ut(o)-1)).toString(32)+r,i="_"+i+"R_"+r,r=Eo++,0<\/script>",f=f.removeChild(f.firstChild);break;case"select":f=typeof o.is=="string"?y.createElement("select",{is:o.is}):y.createElement("select"),o.multiple?f.multiple=!0:o.size&&(f.size=o.size);break;default:f=typeof o.is=="string"?y.createElement(h,{is:o.is}):y.createElement(h)}}f[dt]=i,f[Et]=o;e:for(y=i.child;y!==null;){if(y.tag===5||y.tag===6)f.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===i)break e;for(;y.sibling===null;){if(y.return===null||y.return===i)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}i.stateNode=f;e:switch(gt(f,h,o),h){case"button":case"input":case"select":case"textarea":o=!!o.autoFocus;break e;case"img":o=!0;break e;default:o=!1}o&&$n(i)}}return $e(i),Nc(i,i.type,t===null?null:t.memoizedProps,i.pendingProps,r),null;case 6:if(t&&i.stateNode!=null)t.memoizedProps!==o&&$n(i);else{if(typeof o!="string"&&i.stateNode===null)throw Error(a(166));if(t=pe.current,Cs(i)){if(t=i.stateNode,r=i.memoizedProps,o=null,h=ft,h!==null)switch(h.tag){case 27:case 5:o=h.memoizedProps}t[dt]=i,t=!!(t.nodeValue===r||o!==null&&o.suppressHydrationWarning===!0||Hg(t.nodeValue,r)),t||li(i,!0)}else t=Qo(t).createTextNode(o),t[dt]=i,i.stateNode=t}return $e(i),null;case 31:if(r=i.memoizedState,t===null||t.memoizedState!==null){if(o=Cs(i),r!==null){if(t===null){if(!o)throw Error(a(318));if(t=i.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(a(557));t[dt]=i}else qi(),(i.flags&128)===0&&(i.memoizedState=null),i.flags|=4;$e(i),t=!1}else r=$u(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=r),t=!0;if(!t)return i.flags&256?(Vt(i),i):(Vt(i),null);if((i.flags&128)!==0)throw Error(a(558))}return $e(i),null;case 13:if(o=i.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(h=Cs(i),o!==null&&o.dehydrated!==null){if(t===null){if(!h)throw Error(a(318));if(h=i.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(a(317));h[dt]=i}else qi(),(i.flags&128)===0&&(i.memoizedState=null),i.flags|=4;$e(i),h=!1}else h=$u(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=h),h=!0;if(!h)return i.flags&256?(Vt(i),i):(Vt(i),null)}return Vt(i),(i.flags&128)!==0?(i.lanes=r,i):(r=o!==null,t=t!==null&&t.memoizedState!==null,r&&(o=i.child,h=null,o.alternate!==null&&o.alternate.memoizedState!==null&&o.alternate.memoizedState.cachePool!==null&&(h=o.alternate.memoizedState.cachePool.pool),f=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(f=o.memoizedState.cachePool.pool),f!==h&&(o.flags|=2048)),r!==t&&r&&(i.child.flags|=8192),Bo(i,i.updateQueue),$e(i),null);case 4:return Ie(),t===null&&eh(i.stateNode.containerInfo),$e(i),null;case 10:return zn(i.type),$e(i),null;case 19:if($(Qe),o=i.memoizedState,o===null)return $e(i),null;if(h=(i.flags&128)!==0,f=o.rendering,f===null)if(h)Ia(o,!1);else{if(Ye!==0||t!==null&&(t.flags&128)!==0)for(t=i.child;t!==null;){if(f=So(t),f!==null){for(i.flags|=128,Ia(o,!1),t=f.updateQueue,i.updateQueue=t,Bo(i,t),i.subtreeFlags=0,t=r,r=i.child;r!==null;)bm(r,t),r=r.sibling;return Q(Qe,Qe.current&1|2),Ee&&Bn(i,o.treeForkCount),i.child}t=t.sibling}o.tail!==null&&De()>Ho&&(i.flags|=128,h=!0,Ia(o,!1),i.lanes=4194304)}else{if(!h)if(t=So(f),t!==null){if(i.flags|=128,h=!0,t=t.updateQueue,i.updateQueue=t,Bo(i,t),Ia(o,!0),o.tail===null&&o.tailMode==="hidden"&&!f.alternate&&!Ee)return $e(i),null}else 2*De()-o.renderingStartTime>Ho&&r!==536870912&&(i.flags|=128,h=!0,Ia(o,!1),i.lanes=4194304);o.isBackwards?(f.sibling=i.child,i.child=f):(t=o.last,t!==null?t.sibling=f:i.child=f,o.last=f)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=De(),t.sibling=null,r=Qe.current,Q(Qe,h?r&1|2:r&1),Ee&&Bn(i,o.treeForkCount),t):($e(i),null);case 22:case 23:return Vt(i),tc(),o=i.memoizedState!==null,t!==null?t.memoizedState!==null!==o&&(i.flags|=8192):o&&(i.flags|=8192),o?(r&536870912)!==0&&(i.flags&128)===0&&($e(i),i.subtreeFlags&6&&(i.flags|=8192)):$e(i),r=i.updateQueue,r!==null&&Bo(i,r.retryQueue),r=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),o=null,i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(o=i.memoizedState.cachePool.pool),o!==r&&(i.flags|=2048),t!==null&&$(Ki),null;case 24:return r=null,t!==null&&(r=t.memoizedState.cache),i.memoizedState.cache!==r&&(i.flags|=2048),zn(et),$e(i),null;case 25:return null;case 30:return null}throw Error(a(156,i.tag))}function __(t,i){switch(Pu(i),i.tag){case 1:return t=i.flags,t&65536?(i.flags=t&-65537|128,i):null;case 3:return zn(et),Ie(),t=i.flags,(t&65536)!==0&&(t&128)===0?(i.flags=t&-65537|128,i):null;case 26:case 27:case 5:return hs(i),null;case 31:if(i.memoizedState!==null){if(Vt(i),i.alternate===null)throw Error(a(340));qi()}return t=i.flags,t&65536?(i.flags=t&-65537|128,i):null;case 13:if(Vt(i),t=i.memoizedState,t!==null&&t.dehydrated!==null){if(i.alternate===null)throw Error(a(340));qi()}return t=i.flags,t&65536?(i.flags=t&-65537|128,i):null;case 19:return $(Qe),null;case 4:return Ie(),null;case 10:return zn(i.type),null;case 22:case 23:return Vt(i),tc(),t!==null&&$(Ki),t=i.flags,t&65536?(i.flags=t&-65537|128,i):null;case 24:return zn(et),null;case 25:return null;default:return null}}function Kp(t,i){switch(Pu(i),i.tag){case 3:zn(et),Ie();break;case 26:case 27:case 5:hs(i);break;case 4:Ie();break;case 31:i.memoizedState!==null&&Vt(i);break;case 13:Vt(i);break;case 19:$(Qe);break;case 10:zn(i.type);break;case 22:case 23:Vt(i),tc(),t!==null&&$(Ki);break;case 24:zn(et)}}function Ka(t,i){try{var r=i.updateQueue,o=r!==null?r.lastEffect:null;if(o!==null){var h=o.next;r=h;do{if((r.tag&t)===t){o=void 0;var f=r.create,y=r.inst;o=f(),y.destroy=o}r=r.next}while(r!==h)}}catch(x){Oe(i,i.return,x)}}function pi(t,i,r){try{var o=i.updateQueue,h=o!==null?o.lastEffect:null;if(h!==null){var f=h.next;o=f;do{if((o.tag&t)===t){var y=o.inst,x=y.destroy;if(x!==void 0){y.destroy=void 0,h=i;var T=r,U=x;try{U()}catch(V){Oe(h,T,V)}}}o=o.next}while(o!==f)}}catch(V){Oe(i,i.return,V)}}function Fp(t){var i=t.updateQueue;if(i!==null){var r=t.stateNode;try{Lm(i,r)}catch(o){Oe(t,t.return,o)}}}function Yp(t,i,r){r.props=Qi(t.type,t.memoizedProps),r.state=t.memoizedState;try{r.componentWillUnmount()}catch(o){Oe(t,i,o)}}function Fa(t,i){try{var r=t.ref;if(r!==null){switch(t.tag){case 26:case 27:case 5:var o=t.stateNode;break;case 30:o=t.stateNode;break;default:o=t.stateNode}typeof r=="function"?t.refCleanup=r(o):r.current=o}}catch(h){Oe(t,i,h)}}function wn(t,i){var r=t.ref,o=t.refCleanup;if(r!==null)if(typeof o=="function")try{o()}catch(h){Oe(t,i,h)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof r=="function")try{r(null)}catch(h){Oe(t,i,h)}else r.current=null}function Xp(t){var i=t.type,r=t.memoizedProps,o=t.stateNode;try{e:switch(i){case"button":case"input":case"select":case"textarea":r.autoFocus&&o.focus();break e;case"img":r.src?o.src=r.src:r.srcSet&&(o.srcset=r.srcSet)}}catch(h){Oe(t,t.return,h)}}function Dc(t,i,r){try{var o=t.stateNode;G_(o,t.type,r,i),o[Et]=i}catch(h){Oe(t,t.return,h)}}function Jp(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&_i(t.type)||t.tag===4}function Mc(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Jp(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&_i(t.type)||t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function Uc(t,i,r){var o=t.tag;if(o===5||o===6)t=t.stateNode,i?(r.nodeType===9?r.body:r.nodeName==="HTML"?r.ownerDocument.body:r).insertBefore(t,i):(i=r.nodeType===9?r.body:r.nodeName==="HTML"?r.ownerDocument.body:r,i.appendChild(t),r=r._reactRootContainer,r!=null||i.onclick!==null||(i.onclick=Dn));else if(o!==4&&(o===27&&_i(t.type)&&(r=t.stateNode,i=null),t=t.child,t!==null))for(Uc(t,i,r),t=t.sibling;t!==null;)Uc(t,i,r),t=t.sibling}function Lo(t,i,r){var o=t.tag;if(o===5||o===6)t=t.stateNode,i?r.insertBefore(t,i):r.appendChild(t);else if(o!==4&&(o===27&&_i(t.type)&&(r=t.stateNode),t=t.child,t!==null))for(Lo(t,i,r),t=t.sibling;t!==null;)Lo(t,i,r),t=t.sibling}function Qp(t){var i=t.stateNode,r=t.memoizedProps;try{for(var o=t.type,h=i.attributes;h.length;)i.removeAttributeNode(h[0]);gt(i,o,r),i[dt]=t,i[Et]=r}catch(f){Oe(t,t.return,f)}}var qn=!1,it=!1,Bc=!1,Zp=typeof WeakSet=="function"?WeakSet:Set,ct=null;function S_(t,i){if(t=t.containerInfo,ih=sl,t=cm(t),ku(t)){if("selectionStart"in t)var r={start:t.selectionStart,end:t.selectionEnd};else e:{r=(r=t.ownerDocument)&&r.defaultView||window;var o=r.getSelection&&r.getSelection();if(o&&o.rangeCount!==0){r=o.anchorNode;var h=o.anchorOffset,f=o.focusNode;o=o.focusOffset;try{r.nodeType,f.nodeType}catch{r=null;break e}var y=0,x=-1,T=-1,U=0,V=0,q=t,B=null;t:for(;;){for(var L;q!==r||h!==0&&q.nodeType!==3||(x=y+h),q!==f||o!==0&&q.nodeType!==3||(T=y+o),q.nodeType===3&&(y+=q.nodeValue.length),(L=q.firstChild)!==null;)B=q,q=L;for(;;){if(q===t)break t;if(B===r&&++U===h&&(x=y),B===f&&++V===o&&(T=y),(L=q.nextSibling)!==null)break;q=B,B=q.parentNode}q=L}r=x===-1||T===-1?null:{start:x,end:T}}else r=null}r=r||{start:0,end:0}}else r=null;for(sh={focusedElem:t,selectionRange:r},sl=!1,ct=i;ct!==null;)if(i=ct,t=i.child,(i.subtreeFlags&1028)!==0&&t!==null)t.return=i,ct=t;else for(;ct!==null;){switch(i=ct,f=i.alternate,t=i.flags,i.tag){case 0:if((t&4)!==0&&(t=i.updateQueue,t=t!==null?t.events:null,t!==null))for(r=0;r title"))),gt(f,o,r),f[dt]=t,ut(f),o=f;break e;case"link":var y=sy("link","href",h).get(o+(r.href||""));if(y){for(var x=0;xBe&&(y=Be,Be=he,he=y);var j=lm(x,he),R=lm(x,Be);if(j&&R&&(L.rangeCount!==1||L.anchorNode!==j.node||L.anchorOffset!==j.offset||L.focusNode!==R.node||L.focusOffset!==R.offset)){var M=q.createRange();M.setStart(j.node,j.offset),L.removeAllRanges(),he>Be?(L.addRange(M),L.extend(R.node,R.offset)):(M.setEnd(R.node,R.offset),L.addRange(M))}}}}for(q=[],L=x;L=L.parentNode;)L.nodeType===1&&q.push({element:L,left:L.scrollLeft,top:L.scrollTop});for(typeof x.focus=="function"&&x.focus(),x=0;xr?32:r,D.T=null,r=qc,qc=null;var f=bi,y=Yn;if(rt=0,$s=bi=null,Yn=0,(ke&6)!==0)throw Error(a(331));var x=ke;if(ke|=4,ug(f.current),rg(f,f.current,y,r),ke=x,Wa(0,!1),Mt&&typeof Mt.onPostCommitFiberRoot=="function")try{Mt.onPostCommitFiberRoot(ya,f)}catch{}return!0}finally{I.p=h,D.T=o,Rg(t,i)}}function kg(t,i,r){i=Yt(r,i),i=_c(t.stateNode,i,2),t=di(t,i,2),t!==null&&(ba(t,2),xn(t))}function Oe(t,i,r){if(t.tag===3)kg(t,t,r);else for(;i!==null;){if(i.tag===3){kg(i,t,r);break}else if(i.tag===1){var o=i.stateNode;if(typeof i.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(vi===null||!vi.has(o))){t=Yt(r,t),r=jp(2),o=di(i,r,2),o!==null&&(Op(r,o,i,t),ba(o,2),xn(o));break}}i=i.return}}function Fc(t,i,r){var o=t.pingCache;if(o===null){o=t.pingCache=new A_;var h=new Set;o.set(i,h)}else h=o.get(i),h===void 0&&(h=new Set,o.set(i,h));h.has(r)||(Vc=!0,h.add(r),t=O_.bind(null,t,i,r),i.then(t,t))}function O_(t,i,r){var o=t.pingCache;o!==null&&o.delete(i),t.pingedLanes|=t.suspendedLanes&r,t.warmLanes&=~r,Le===t&&(Se&r)===r&&(Ye===4||Ye===3&&(Se&62914560)===Se&&300>De()-Po?(ke&2)===0&&qs(t,0):Pc|=r,Hs===Se&&(Hs=0)),xn(t)}function jg(t,i){i===0&&(i=Tf()),t=Hi(t,i),t!==null&&(ba(t,i),xn(t))}function N_(t){var i=t.memoizedState,r=0;i!==null&&(r=i.retryLane),jg(t,r)}function D_(t,i){var r=0;switch(t.tag){case 31:case 13:var o=t.stateNode,h=t.memoizedState;h!==null&&(r=h.retryLane);break;case 19:o=t.stateNode;break;case 22:o=t.stateNode._retryCache;break;default:throw Error(a(314))}o!==null&&o.delete(i),jg(t,r)}function M_(t,i){return On(t,i)}var Fo=null,Is=null,Yc=!1,Yo=!1,Xc=!1,xi=0;function xn(t){t!==Is&&t.next===null&&(Is===null?Fo=Is=t:Is=Is.next=t),Yo=!0,Yc||(Yc=!0,B_())}function Wa(t,i){if(!Xc&&Yo){Xc=!0;do for(var r=!1,o=Fo;o!==null;){if(t!==0){var h=o.pendingLanes;if(h===0)var f=0;else{var y=o.suspendedLanes,x=o.pingedLanes;f=(1<<31-Ut(42|t)+1)-1,f&=h&~(y&~x),f=f&201326741?f&201326741|1:f?f|2:0}f!==0&&(r=!0,Mg(o,f))}else f=Se,f=Qr(o,o===Le?f:0,o.cancelPendingCommit!==null||o.timeoutHandle!==-1),(f&3)===0||va(o,f)||(r=!0,Mg(o,f));o=o.next}while(r);Xc=!1}}function U_(){Og()}function Og(){Yo=Yc=!1;var t=0;xi!==0&&K_()&&(t=xi);for(var i=De(),r=null,o=Fo;o!==null;){var h=o.next,f=Ng(o,i);f===0?(o.next=null,r===null?Fo=h:r.next=h,h===null&&(Is=r)):(r=o,(t!==0||(f&3)!==0)&&(Yo=!0)),o=h}rt!==0&&rt!==5||Wa(t),xi!==0&&(xi=0)}function Ng(t,i){for(var r=t.suspendedLanes,o=t.pingedLanes,h=t.expirationTimes,f=t.pendingLanes&-62914561;0x)break;var V=T.transferSize,q=T.initiatorType;V&&$g(q)&&(T=T.responseEnd,y+=V*(T"u"?null:document;function ey(t,i,r){var o=Ks;if(o&&typeof i=="string"&&i){var h=Kt(i);h='link[rel="'+t+'"][href="'+h+'"]',typeof r=="string"&&(h+='[crossorigin="'+r+'"]'),Wg.has(h)||(Wg.add(h),t={rel:t,crossOrigin:r,href:i},o.querySelector(h)===null&&(i=o.createElement("link"),gt(i,"link",t),ut(i),o.head.appendChild(i)))}}function tS(t){Xn.D(t),ey("dns-prefetch",t,null)}function nS(t,i){Xn.C(t,i),ey("preconnect",t,i)}function iS(t,i,r){Xn.L(t,i,r);var o=Ks;if(o&&t&&i){var h='link[rel="preload"][as="'+Kt(i)+'"]';i==="image"&&r&&r.imageSrcSet?(h+='[imagesrcset="'+Kt(r.imageSrcSet)+'"]',typeof r.imageSizes=="string"&&(h+='[imagesizes="'+Kt(r.imageSizes)+'"]')):h+='[href="'+Kt(t)+'"]';var f=h;switch(i){case"style":f=Fs(t);break;case"script":f=Ys(t)}en.has(f)||(t=v({rel:"preload",href:i==="image"&&r&&r.imageSrcSet?void 0:t,as:i},r),en.set(f,t),o.querySelector(h)!==null||i==="style"&&o.querySelector(ir(f))||i==="script"&&o.querySelector(sr(f))||(i=o.createElement("link"),gt(i,"link",t),ut(i),o.head.appendChild(i)))}}function sS(t,i){Xn.m(t,i);var r=Ks;if(r&&t){var o=i&&typeof i.as=="string"?i.as:"script",h='link[rel="modulepreload"][as="'+Kt(o)+'"][href="'+Kt(t)+'"]',f=h;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":f=Ys(t)}if(!en.has(f)&&(t=v({rel:"modulepreload",href:t},i),en.set(f,t),r.querySelector(h)===null)){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(r.querySelector(sr(f)))return}o=r.createElement("link"),gt(o,"link",t),ut(o),r.head.appendChild(o)}}}function aS(t,i,r){Xn.S(t,i,r);var o=Ks;if(o&&t){var h=ps(o).hoistableStyles,f=Fs(t);i=i||"default";var y=h.get(f);if(!y){var x={loading:0,preload:null};if(y=o.querySelector(ir(f)))x.loading=5;else{t=v({rel:"stylesheet",href:t,"data-precedence":i},r),(r=en.get(f))&&hh(t,r);var T=y=o.createElement("link");ut(T),gt(T,"link",t),T._p=new Promise(function(U,V){T.onload=U,T.onerror=V}),T.addEventListener("load",function(){x.loading|=1}),T.addEventListener("error",function(){x.loading|=2}),x.loading|=4,Wo(y,i,o)}y={type:"stylesheet",instance:y,count:1,state:x},h.set(f,y)}}}function rS(t,i){Xn.X(t,i);var r=Ks;if(r&&t){var o=ps(r).hoistableScripts,h=Ys(t),f=o.get(h);f||(f=r.querySelector(sr(h)),f||(t=v({src:t,async:!0},i),(i=en.get(h))&&dh(t,i),f=r.createElement("script"),ut(f),gt(f,"link",t),r.head.appendChild(f)),f={type:"script",instance:f,count:1,state:null},o.set(h,f))}}function oS(t,i){Xn.M(t,i);var r=Ks;if(r&&t){var o=ps(r).hoistableScripts,h=Ys(t),f=o.get(h);f||(f=r.querySelector(sr(h)),f||(t=v({src:t,async:!0,type:"module"},i),(i=en.get(h))&&dh(t,i),f=r.createElement("script"),ut(f),gt(f,"link",t),r.head.appendChild(f)),f={type:"script",instance:f,count:1,state:null},o.set(h,f))}}function ty(t,i,r,o){var h=(h=pe.current)?Zo(h):null;if(!h)throw Error(a(446));switch(t){case"meta":case"title":return null;case"style":return typeof r.precedence=="string"&&typeof r.href=="string"?(i=Fs(r.href),r=ps(h).hoistableStyles,o=r.get(i),o||(o={type:"style",instance:null,count:0,state:null},r.set(i,o)),o):{type:"void",instance:null,count:0,state:null};case"link":if(r.rel==="stylesheet"&&typeof r.href=="string"&&typeof r.precedence=="string"){t=Fs(r.href);var f=ps(h).hoistableStyles,y=f.get(t);if(y||(h=h.ownerDocument||h,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},f.set(t,y),(f=h.querySelector(ir(t)))&&!f._p&&(y.instance=f,y.state.loading=5),en.has(t)||(r={rel:"preload",as:"style",href:r.href,crossOrigin:r.crossOrigin,integrity:r.integrity,media:r.media,hrefLang:r.hrefLang,referrerPolicy:r.referrerPolicy},en.set(t,r),f||lS(h,t,r,y.state))),i&&o===null)throw Error(a(528,""));return y}if(i&&o!==null)throw Error(a(529,""));return null;case"script":return i=r.async,r=r.src,typeof r=="string"&&i&&typeof i!="function"&&typeof i!="symbol"?(i=Ys(r),r=ps(h).hoistableScripts,o=r.get(i),o||(o={type:"script",instance:null,count:0,state:null},r.set(i,o)),o):{type:"void",instance:null,count:0,state:null};default:throw Error(a(444,t))}}function Fs(t){return'href="'+Kt(t)+'"'}function ir(t){return'link[rel="stylesheet"]['+t+"]"}function ny(t){return v({},t,{"data-precedence":t.precedence,precedence:null})}function lS(t,i,r,o){t.querySelector('link[rel="preload"][as="style"]['+i+"]")?o.loading=1:(i=t.createElement("link"),o.preload=i,i.addEventListener("load",function(){return o.loading|=1}),i.addEventListener("error",function(){return o.loading|=2}),gt(i,"link",r),ut(i),t.head.appendChild(i))}function Ys(t){return'[src="'+Kt(t)+'"]'}function sr(t){return"script[async]"+t}function iy(t,i,r){if(i.count++,i.instance===null)switch(i.type){case"style":var o=t.querySelector('style[data-href~="'+Kt(r.href)+'"]');if(o)return i.instance=o,ut(o),o;var h=v({},r,{"data-href":r.href,"data-precedence":r.precedence,href:null,precedence:null});return o=(t.ownerDocument||t).createElement("style"),ut(o),gt(o,"style",h),Wo(o,r.precedence,t),i.instance=o;case"stylesheet":h=Fs(r.href);var f=t.querySelector(ir(h));if(f)return i.state.loading|=4,i.instance=f,ut(f),f;o=ny(r),(h=en.get(h))&&hh(o,h),f=(t.ownerDocument||t).createElement("link"),ut(f);var y=f;return y._p=new Promise(function(x,T){y.onload=x,y.onerror=T}),gt(f,"link",o),i.state.loading|=4,Wo(f,r.precedence,t),i.instance=f;case"script":return f=Ys(r.src),(h=t.querySelector(sr(f)))?(i.instance=h,ut(h),h):(o=r,(h=en.get(f))&&(o=v({},r),dh(o,h)),t=t.ownerDocument||t,h=t.createElement("script"),ut(h),gt(h,"link",o),t.head.appendChild(h),i.instance=h);case"void":return null;default:throw Error(a(443,i.type))}else i.type==="stylesheet"&&(i.state.loading&4)===0&&(o=i.instance,i.state.loading|=4,Wo(o,r.precedence,t));return i.instance}function Wo(t,i,r){for(var o=r.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),h=o.length?o[o.length-1]:null,f=h,y=0;y title"):null)}function uS(t,i,r){if(r===1||i.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof i.precedence!="string"||typeof i.href!="string"||i.href==="")break;return!0;case"link":if(typeof i.rel!="string"||typeof i.href!="string"||i.href===""||i.onLoad||i.onError)break;switch(i.rel){case"stylesheet":return t=i.disabled,typeof i.precedence=="string"&&t==null;default:return!0}case"script":if(i.async&&typeof i.async!="function"&&typeof i.async!="symbol"&&!i.onLoad&&!i.onError&&i.src&&typeof i.src=="string")return!0}return!1}function ry(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function cS(t,i,r,o){if(r.type==="stylesheet"&&(typeof o.media!="string"||matchMedia(o.media).matches!==!1)&&(r.state.loading&4)===0){if(r.instance===null){var h=Fs(o.href),f=i.querySelector(ir(h));if(f){i=f._p,i!==null&&typeof i=="object"&&typeof i.then=="function"&&(t.count++,t=tl.bind(t),i.then(t,t)),r.state.loading|=4,r.instance=f,ut(f);return}f=i.ownerDocument||i,o=ny(o),(h=en.get(h))&&hh(o,h),f=f.createElement("link"),ut(f);var y=f;y._p=new Promise(function(x,T){y.onload=x,y.onerror=T}),gt(f,"link",o),r.instance=f}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(r,i),(i=r.state.preload)&&(r.state.loading&3)===0&&(t.count++,r=tl.bind(t),i.addEventListener("load",r),i.addEventListener("error",r))}}var fh=0;function hS(t,i){return t.stylesheets&&t.count===0&&il(t,t.stylesheets),0fh?50:800)+i);return t.unsuspend=r,function(){t.unsuspend=null,clearTimeout(o),clearTimeout(h)}}:null}function tl(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)il(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var nl=null;function il(t,i){t.stylesheets=null,t.unsuspend!==null&&(t.count++,nl=new Map,i.forEach(dS,t),nl=null,tl.call(t))}function dS(t,i){if(!(i.state.loading&4)){var r=nl.get(t);if(r)var o=r.get(null);else{r=new Map,nl.set(t,r);for(var h=t.querySelectorAll("link[data-precedence],style[data-precedence]"),f=0;f"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),_h.exports=CS(),_h.exports}var jS=kS();const Pd=P.createContext({});function Hd(n){const e=P.useRef(null);return e.current===null&&(e.current=n()),e.current}const OS=typeof window<"u",$d=OS?P.useLayoutEffect:P.useEffect,Wl=P.createContext(null);function qd(n,e){n.indexOf(e)===-1&&n.push(e)}function Ul(n,e){const s=n.indexOf(e);s>-1&&n.splice(s,1)}const Cn=(n,e,s)=>s>e?e:s{};const Ni={},$v=n=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(n),qv=n=>typeof n=="object"&&n!==null,Gv=n=>/^0[^.\s]+$/u.test(n);function Iv(n){let e;return()=>(e===void 0&&(e=n()),e)}const sn=n=>n,Vr=(...n)=>n.reduce((e,s)=>a=>s(e(a))),Ar=(n,e,s)=>{const a=e-n;return a?(s-n)/a:1};class Id{constructor(){this.subscriptions=[]}add(e){return qd(this.subscriptions,e),()=>Ul(this.subscriptions,e)}notify(e,s,a){const l=this.subscriptions.length;if(l)if(l===1)this.subscriptions[0](e,s,a);else for(let u=0;un*1e3,nn=n=>n/1e3,Kv=(n,e)=>e?n*(1e3/e):0,Fv=(n,e,s)=>(((1-3*s+3*e)*n+(3*s-6*e))*n+3*e)*n,NS=1e-7,DS=12;function MS(n,e,s,a,l){let u,c,d=0;do c=e+(s-e)/2,u=Fv(c,a,l)-n,u>0?s=c:e=c;while(Math.abs(u)>NS&&++dMS(u,0,1,n,s);return u=>u===0||u===1?u:Fv(l(u),e,a)}const Yv=n=>e=>e<=.5?n(2*e)/2:(2-n(2*(1-e)))/2,Xv=n=>e=>1-n(1-e),Jv=Pr(.33,1.53,.69,.99),Kd=Xv(Jv),Qv=Yv(Kd),Zv=n=>n>=1?1:(n*=2)<1?.5*Kd(n):.5*(2-Math.pow(2,-10*(n-1))),Fd=n=>1-Math.sin(Math.acos(n)),Wv=Xv(Fd),eb=Yv(Fd),US=Pr(.42,0,1,1),BS=Pr(0,0,.58,1),tb=Pr(.42,0,.58,1),LS=n=>Array.isArray(n)&&typeof n[0]!="number",nb=n=>Array.isArray(n)&&typeof n[0]=="number",zS={linear:sn,easeIn:US,easeInOut:tb,easeOut:BS,circIn:Fd,circInOut:eb,circOut:Wv,backIn:Kd,backInOut:Qv,backOut:Jv,anticipate:Zv},VS=n=>typeof n=="string",jy=n=>{if(nb(n)){Gd(n.length===4);const[e,s,a,l]=n;return Pr(e,s,a,l)}else if(VS(n))return zS[n];return n},hl=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function PS(n){let e=new Set,s=new Set,a=!1,l=!1;const u=new WeakSet;let c={delta:0,timestamp:0,isProcessing:!1};function d(p){u.has(p)&&(m.schedule(p),n()),p(c)}const m={schedule:(p,g=!1,v=!1)=>{const _=v&&a?e:s;return g&&u.add(p),_.add(p),p},cancel:p=>{s.delete(p),u.delete(p)},process:p=>{if(c=p,a){l=!0;return}a=!0;const g=e;e=s,s=g,e.forEach(d),e.clear(),a=!1,l&&(l=!1,m.process(p))}};return m}const HS=40;function ib(n,e){let s=!1,a=!0;const l={delta:0,timestamp:0,isProcessing:!1},u=()=>s=!0,c=hl.reduce((O,z)=>(O[z]=PS(u),O),{}),{setup:d,read:m,resolveKeyframes:p,preUpdate:g,update:v,preRender:w,render:_,postRender:S}=c,E=()=>{const O=Ni.useManualTiming,z=O?l.timestamp:performance.now();s=!1,O||(l.delta=a?1e3/60:Math.max(Math.min(z-l.timestamp,HS),1)),l.timestamp=z,l.isProcessing=!0,d.process(l),m.process(l),p.process(l),g.process(l),v.process(l),w.process(l),_.process(l),S.process(l),l.isProcessing=!1,s&&e&&(a=!1,n(E))},k=()=>{s=!0,a=!0,l.isProcessing||n(E)};return{schedule:hl.reduce((O,z)=>{const F=c[z];return O[z]=(J,G=!1,Y=!1)=>(s||k(),F.schedule(J,G,Y)),O},{}),cancel:O=>{for(let z=0;z(El===void 0&&_t.set(yt.isProcessing||Ni.useManualTiming?yt.timestamp:performance.now()),El),set:n=>{El=n,queueMicrotask($S)}},sb=n=>e=>typeof e=="string"&&e.startsWith(n),ab=sb("--"),qS=sb("var(--"),Yd=n=>qS(n)?GS.test(n.split("/*")[0].trim()):!1,GS=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Oy(n){return typeof n!="string"?!1:n.split("/*")[0].includes("var(--")}const ha={test:n=>typeof n=="number",parse:parseFloat,transform:n=>n},Rr={...ha,transform:n=>Cn(0,1,n)},dl={...ha,default:1},vr=n=>Math.round(n*1e5)/1e5,Xd=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function IS(n){return n==null}const KS=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Jd=(n,e)=>s=>!!(typeof s=="string"&&KS.test(s)&&s.startsWith(n)||e&&!IS(s)&&Object.prototype.hasOwnProperty.call(s,e)),rb=(n,e,s)=>a=>{if(typeof a!="string")return a;const[l,u,c,d]=a.match(Xd);return{[n]:parseFloat(l),[e]:parseFloat(u),[s]:parseFloat(c),alpha:d!==void 0?parseFloat(d):1}},FS=n=>Cn(0,255,n),Rh={...ha,transform:n=>Math.round(FS(n))},rs={test:Jd("rgb","red"),parse:rb("red","green","blue"),transform:({red:n,green:e,blue:s,alpha:a=1})=>"rgba("+Rh.transform(n)+", "+Rh.transform(e)+", "+Rh.transform(s)+", "+vr(Rr.transform(a))+")"};function YS(n){let e="",s="",a="",l="";return n.length>5?(e=n.substring(1,3),s=n.substring(3,5),a=n.substring(5,7),l=n.substring(7,9)):(e=n.substring(1,2),s=n.substring(2,3),a=n.substring(3,4),l=n.substring(4,5),e+=e,s+=s,a+=a,l+=l),{red:parseInt(e,16),green:parseInt(s,16),blue:parseInt(a,16),alpha:l?parseInt(l,16)/255:1}}const ed={test:Jd("#"),parse:YS,transform:rs.transform},Hr=n=>({test:e=>typeof e=="string"&&e.endsWith(n)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${n}`}),Zn=Hr("deg"),Rn=Hr("%"),se=Hr("px"),XS=Hr("vh"),JS=Hr("vw"),Ny={...Rn,parse:n=>Rn.parse(n)/100,transform:n=>Rn.transform(n*100)},sa={test:Jd("hsl","hue"),parse:rb("hue","saturation","lightness"),transform:({hue:n,saturation:e,lightness:s,alpha:a=1})=>"hsla("+Math.round(n)+", "+Rn.transform(vr(e))+", "+Rn.transform(vr(s))+", "+vr(Rr.transform(a))+")"},at={test:n=>rs.test(n)||ed.test(n)||sa.test(n),parse:n=>rs.test(n)?rs.parse(n):sa.test(n)?sa.parse(n):ed.parse(n),transform:n=>typeof n=="string"?n:n.hasOwnProperty("red")?rs.transform(n):sa.transform(n),getAnimatableNone:n=>{const e=at.parse(n);return e.alpha=0,at.transform(e)}},QS=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ZS(n){var e,s;return isNaN(n)&&typeof n=="string"&&(((e=n.match(Xd))==null?void 0:e.length)||0)+(((s=n.match(QS))==null?void 0:s.length)||0)>0}const ob="number",lb="color",WS="var",e1="var(",Dy="${}",t1=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function ua(n){const e=n.toString(),s=[],a={color:[],number:[],var:[]},l=[];let u=0;const d=e.replace(t1,m=>(at.test(m)?(a.color.push(u),l.push(lb),s.push(at.parse(m))):m.startsWith(e1)?(a.var.push(u),l.push(WS),s.push(m)):(a.number.push(u),l.push(ob),s.push(parseFloat(m))),++u,Dy)).split(Dy);return{values:s,split:d,indexes:a,types:l}}function n1(n){return ua(n).values}function ub({split:n,types:e}){const s=n.length;return a=>{let l="";for(let u=0;utypeof n=="number"?0:at.test(n)?at.getAnimatableNone(n):n,a1=(n,e)=>typeof n=="number"?e!=null&&e.trim().endsWith("/")?n:0:s1(n);function r1(n){const e=ua(n);return ub(e)(e.values.map((a,l)=>a1(a,e.split[l])))}const pn={test:ZS,parse:n1,createTransformer:i1,getAnimatableNone:r1};function Ch(n,e,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?n+(e-n)*6*s:s<1/2?e:s<2/3?n+(e-n)*(2/3-s)*6:n}function o1({hue:n,saturation:e,lightness:s,alpha:a}){n/=360,e/=100,s/=100;let l=0,u=0,c=0;if(!e)l=u=c=s;else{const d=s<.5?s*(1+e):s+e-s*e,m=2*s-d;l=Ch(m,d,n+1/3),u=Ch(m,d,n),c=Ch(m,d,n-1/3)}return{red:Math.round(l*255),green:Math.round(u*255),blue:Math.round(c*255),alpha:a}}function Bl(n,e){return s=>s>0?e:n}const ze=(n,e,s)=>n+(e-n)*s,kh=(n,e,s)=>{const a=n*n,l=s*(e*e-a)+a;return l<0?0:Math.sqrt(l)},l1=[ed,rs,sa],u1=n=>l1.find(e=>e.test(n));function My(n){const e=u1(n);if(!e)return!1;let s=e.parse(n);return e===sa&&(s=o1(s)),s}const Uy=(n,e)=>{const s=My(n),a=My(e);if(!s||!a)return Bl(n,e);const l={...s};return u=>(l.red=kh(s.red,a.red,u),l.green=kh(s.green,a.green,u),l.blue=kh(s.blue,a.blue,u),l.alpha=ze(s.alpha,a.alpha,u),rs.transform(l))},td=new Set(["none","hidden"]);function c1(n,e){return td.has(n)?s=>s<=0?n:e:s=>s>=1?e:n}function h1(n,e){return s=>ze(n,e,s)}function Qd(n){return typeof n=="number"?h1:typeof n=="string"?Yd(n)?Bl:at.test(n)?Uy:m1:Array.isArray(n)?cb:typeof n=="object"?at.test(n)?Uy:d1:Bl}function cb(n,e){const s=[...n],a=s.length,l=n.map((u,c)=>Qd(u)(u,e[c]));return u=>{for(let c=0;c{for(const u in a)s[u]=a[u](l);return s}}function f1(n,e){const s=[],a={color:0,var:0,number:0};for(let l=0;l{const s=pn.createTransformer(e),a=ua(n),l=ua(e);return a.indexes.var.length===l.indexes.var.length&&a.indexes.color.length===l.indexes.color.length&&a.indexes.number.length>=l.indexes.number.length?td.has(n)&&!l.values.length||td.has(e)&&!a.values.length?c1(n,e):Vr(cb(f1(a,l),l.values),s):Bl(n,e)};function hb(n,e,s){return typeof n=="number"&&typeof e=="number"&&typeof s=="number"?ze(n,e,s):Qd(n)(n,e)}const p1=n=>{const e=({timestamp:s})=>n(s);return{start:(s=!0)=>Ve.update(e,s),stop:()=>Di(e),now:()=>yt.isProcessing?yt.timestamp:_t.now()}},db=(n,e,s=10)=>{let a="";const l=Math.max(Math.round(e/s),2);for(let u=0;u=Ll?1/0:e}function g1(n,e=100,s){const a=s({...n,keyframes:[0,e]}),l=Math.min(Zd(a),Ll);return{type:"keyframes",ease:u=>a.next(l*u).value/e,duration:nn(l)}}const Je={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function nd(n,e){return n*Math.sqrt(1-e*e)}const y1=12;function v1(n,e,s){let a=s;for(let l=1;l{const g=p*c,v=g*n,w=g-s,_=nd(p,c),S=Math.exp(-v);return jh-w/_*S},u=p=>{const v=p*c*n,w=v*s+s,_=Math.pow(c,2)*Math.pow(p,2)*n,S=Math.exp(-v),E=nd(Math.pow(p,2),c);return(-l(p)+jh>0?-1:1)*((w-_)*S)/E}):(l=p=>{const g=Math.exp(-p*n),v=(p-s)*n+1;return-jh+g*v},u=p=>{const g=Math.exp(-p*n),v=(s-p)*(n*n);return g*v});const d=5/n,m=v1(l,u,d);if(n=Gt(n),isNaN(m))return{stiffness:Je.stiffness,damping:Je.damping,duration:n};{const p=Math.pow(m,2)*a;return{stiffness:p,damping:c*2*Math.sqrt(a*p),duration:n}}}const w1=["duration","bounce"],x1=["stiffness","damping","mass"];function By(n,e){return e.some(s=>n[s]!==void 0)}function _1(n){let e={velocity:Je.velocity,stiffness:Je.stiffness,damping:Je.damping,mass:Je.mass,isResolvedFromDuration:!1,...n};if(!By(n,x1)&&By(n,w1))if(e.velocity=0,n.visualDuration){const s=n.visualDuration,a=2*Math.PI/(s*1.2),l=a*a,u=2*Cn(.05,1,1-(n.bounce||0))*Math.sqrt(l);e={...e,mass:Je.mass,stiffness:l,damping:u}}else{const s=b1({...n,velocity:0});e={...e,...s,mass:Je.mass},e.isResolvedFromDuration=!0}return e}function zl(n=Je.visualDuration,e=Je.bounce){const s=typeof n!="object"?{visualDuration:n,keyframes:[0,1],bounce:e}:n;let{restSpeed:a,restDelta:l}=s;const u=s.keyframes[0],c=s.keyframes[s.keyframes.length-1],d={done:!1,value:u},{stiffness:m,damping:p,mass:g,duration:v,velocity:w,isResolvedFromDuration:_}=_1({...s,velocity:-nn(s.velocity||0)}),S=w||0,E=p/(2*Math.sqrt(m*g)),k=c-u,C=nn(Math.sqrt(m/g)),N=Math.abs(k)<5;a||(a=N?Je.restSpeed.granular:Je.restSpeed.default),l||(l=N?Je.restDelta.granular:Je.restDelta.default);let O,z,F,J,G,Y;if(E<1)F=nd(C,E),J=(S+E*C*k)/F,O=te=>{const de=Math.exp(-E*C*te);return c-de*(J*Math.sin(F*te)+k*Math.cos(F*te))},G=E*C*J+k*F,Y=E*C*k-J*F,z=te=>Math.exp(-E*C*te)*(G*Math.sin(F*te)+Y*Math.cos(F*te));else if(E===1){O=de=>c-Math.exp(-C*de)*(k+(S+C*k)*de);const te=S+C*k;z=de=>Math.exp(-C*de)*(C*te*de-S)}else{const te=C*Math.sqrt(E*E-1);O=X=>{const ue=Math.exp(-E*C*X),D=Math.min(te*X,300);return c-ue*((S+E*C*k)*Math.sinh(D)+te*k*Math.cosh(D))/te};const de=(S+E*C*k)/te,fe=E*C*de-k*te,qe=E*C*k-de*te;z=X=>{const ue=Math.exp(-E*C*X),D=Math.min(te*X,300);return ue*(fe*Math.sinh(D)+qe*Math.cosh(D))}}const Z={calculatedDuration:_&&v||null,velocity:te=>Gt(z(te)),next:te=>{if(!_&&E<1){const fe=Math.exp(-E*C*te),qe=Math.sin(F*te),X=Math.cos(F*te),ue=c-fe*(J*qe+k*X),D=Gt(fe*(G*qe+Y*X));return d.done=Math.abs(D)<=a&&Math.abs(c-ue)<=l,d.value=d.done?c:ue,d}const de=O(te);if(_)d.done=te>=v;else{const fe=Gt(z(te));d.done=Math.abs(fe)<=a&&Math.abs(c-de)<=l}return d.value=d.done?c:de,d},toString:()=>{const te=Math.min(Zd(Z),Ll),de=db(fe=>Z.next(te*fe).value,te,30);return te+"ms "+de},toTransition:()=>{}};return Z}zl.applyToOptions=n=>{const e=g1(n,100,zl);return n.ease=e.ease,n.duration=Gt(e.duration),n.type="keyframes",n};const S1=5;function fb(n,e,s){const a=Math.max(e-S1,0);return Kv(s-n(a),e-a)}function id({keyframes:n,velocity:e=0,power:s=.8,timeConstant:a=325,bounceDamping:l=10,bounceStiffness:u=500,modifyTarget:c,min:d,max:m,restDelta:p=.5,restSpeed:g}){const v=n[0],w={done:!1,value:v},_=Y=>d!==void 0&&Ym,S=Y=>d===void 0?m:m===void 0||Math.abs(d-Y)-E*Math.exp(-Y/a),O=Y=>C+N(Y),z=Y=>{const Z=N(Y),te=O(Y);w.done=Math.abs(Z)<=p,w.value=w.done?C:te};let F,J;const G=Y=>{_(w.value)&&(F=Y,J=zl({keyframes:[w.value,S(w.value)],velocity:fb(O,Y,w.value),damping:l,stiffness:u,restDelta:p,restSpeed:g}))};return G(0),{calculatedDuration:null,next:Y=>{let Z=!1;return!J&&F===void 0&&(Z=!0,z(Y),G(Y)),F!==void 0&&Y>=F?J.next(Y-F):(!Z&&z(Y),w)}}}function T1(n,e,s){const a=[],l=s||Ni.mix||hb,u=n.length-1;for(let c=0;ce[0];if(u===2&&e[0]===e[1])return()=>e[1];const c=n[0]===n[1];n[0]>n[u-1]&&(n=[...n].reverse(),e=[...e].reverse());const d=T1(e,a,l),m=d.length,p=g=>{if(c&&g1)for(;vp(Cn(n[0],n[u-1],g)):p}function A1(n,e){const s=n[n.length-1];for(let a=1;a<=e;a++){const l=Ar(0,e,a);n.push(ze(s,1,l))}}function R1(n){const e=[0];return A1(e,n.length-1),e}function C1(n,e){return n.map(s=>s*e)}function k1(n,e){return n.map(()=>e||tb).splice(0,n.length-1)}function br({duration:n=300,keyframes:e,times:s,ease:a="easeInOut"}){const l=LS(a)?a.map(jy):jy(a),u={done:!1,value:e[0]},c=C1(s&&s.length===e.length?s:R1(e),n),d=E1(c,e,{ease:Array.isArray(l)?l:k1(e,l)});return{calculatedDuration:n,next:m=>(u.value=d(m),u.done=m>=n,u)}}const j1=n=>n!==null;function eu(n,{repeat:e,repeatType:s="loop"},a,l=1){const u=n.filter(j1),d=l<0||e&&s!=="loop"&&e%2===1?0:u.length-1;return!d||a===void 0?u[d]:a}const O1={decay:id,inertia:id,tween:br,keyframes:br,spring:zl};function mb(n){typeof n.type=="string"&&(n.type=O1[n.type])}class Wd{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,s){return this.finished.then(e,s)}}const N1=n=>n/100;class Vl extends Wd{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{var a,l;const{motionValue:s}=this.options;s&&s.updatedAt!==_t.now()&&this.tick(_t.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(l=(a=this.options).onStop)==null||l.call(a))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;mb(e);const{type:s=br,repeat:a=0,repeatDelay:l=0,repeatType:u,velocity:c=0}=e;let{keyframes:d}=e;const m=s||br;m!==br&&typeof d[0]!="number"&&(this.mixKeyframes=Vr(N1,hb(d[0],d[1])),d=[0,100]);const p=m({...e,keyframes:d});u==="mirror"&&(this.mirroredGenerator=m({...e,keyframes:[...d].reverse(),velocity:-c})),p.calculatedDuration===null&&(p.calculatedDuration=Zd(p));const{calculatedDuration:g}=p;this.calculatedDuration=g,this.resolvedDuration=g+l,this.totalDuration=this.resolvedDuration*(a+1)-l,this.generator=p}updateTime(e){const s=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=s}tick(e,s=!1){const{generator:a,totalDuration:l,mixKeyframes:u,mirroredGenerator:c,resolvedDuration:d,calculatedDuration:m}=this;if(this.startTime===null)return a.next(0);const{delay:p=0,keyframes:g,repeat:v,repeatType:w,repeatDelay:_,type:S,onUpdate:E,finalKeyframe:k}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-l/this.speed,this.startTime)),s?this.currentTime=e:this.updateTime(e);const C=this.currentTime-p*(this.playbackSpeed>=0?1:-1),N=this.playbackSpeed>=0?C<0:C>l;this.currentTime=Math.max(C,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=l);let O=this.currentTime,z=a;if(v){const Y=Math.min(this.currentTime,l)/d;let Z=Math.floor(Y),te=Y%1;!te&&Y>=1&&(te=1),te===1&&Z--,Z=Math.min(Z,v+1),!!(Z%2)&&(w==="reverse"?(te=1-te,_&&(te-=_/d)):w==="mirror"&&(z=c)),O=Cn(0,1,te)*d}let F;N?(this.delayState.value=g[0],F=this.delayState):F=z.next(O),u&&!N&&(F.value=u(F.value));let{done:J}=F;!N&&m!==null&&(J=this.playbackSpeed>=0?this.currentTime>=l:this.currentTime<=0);const G=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&J);return G&&S!==id&&(F.value=eu(g,this.options,k,this.speed)),E&&E(F.value),G&&this.finish(),F}then(e,s){return this.finished.then(e,s)}get duration(){return nn(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+nn(e)}get time(){return nn(this.currentTime)}set time(e){e=Gt(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state="paused",this.holdTime=e,this.tick(e))}getGeneratorVelocity(){const e=this.currentTime;if(e<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(e);const s=this.generator.next(e).value;return fb(a=>this.generator.next(a).value,e,s)}get speed(){return this.playbackSpeed}set speed(e){const s=this.playbackSpeed!==e;s&&this.driver&&this.updateTime(_t.now()),this.playbackSpeed=e,s&&this.driver&&(this.time=nn(this.currentTime))}play(){var l,u;if(this.isStopped)return;const{driver:e=p1,startTime:s}=this.options;this.driver||(this.driver=e(c=>this.tick(c))),(u=(l=this.options).onPlay)==null||u.call(l);const a=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=a):this.holdTime!==null?this.startTime=a-this.holdTime:this.startTime||(this.startTime=s??a),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(_t.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,s;this.notifyFinished(),this.teardown(),this.state="finished",(s=(e=this.options).onComplete)==null||s.call(e)}cancel(){var e,s;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(s=(e=this.options).onCancel)==null||s.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var s;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(s=this.driver)==null||s.stop(),e.observe(this)}}function D1(n){for(let e=1;en*180/Math.PI,sd=n=>{const e=os(Math.atan2(n[1],n[0]));return ad(e)},M1={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:n=>(Math.abs(n[0])+Math.abs(n[3]))/2,rotate:sd,rotateZ:sd,skewX:n=>os(Math.atan(n[1])),skewY:n=>os(Math.atan(n[2])),skew:n=>(Math.abs(n[1])+Math.abs(n[2]))/2},ad=n=>(n=n%360,n<0&&(n+=360),n),Ly=sd,zy=n=>Math.sqrt(n[0]*n[0]+n[1]*n[1]),Vy=n=>Math.sqrt(n[4]*n[4]+n[5]*n[5]),U1={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:zy,scaleY:Vy,scale:n=>(zy(n)+Vy(n))/2,rotateX:n=>ad(os(Math.atan2(n[6],n[5]))),rotateY:n=>ad(os(Math.atan2(-n[2],n[0]))),rotateZ:Ly,rotate:Ly,skewX:n=>os(Math.atan(n[4])),skewY:n=>os(Math.atan(n[1])),skew:n=>(Math.abs(n[1])+Math.abs(n[4]))/2};function rd(n){return n.includes("scale")?1:0}function od(n,e){if(!n||n==="none")return rd(e);const s=n.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let a,l;if(s)a=U1,l=s;else{const d=n.match(/^matrix\(([-\d.e\s,]+)\)$/u);a=M1,l=d}if(!l)return rd(e);const u=a[e],c=l[1].split(",").map(L1);return typeof u=="function"?u(c):c[u]}const B1=(n,e)=>{const{transform:s="none"}=getComputedStyle(n);return od(s,e)};function L1(n){return parseFloat(n.trim())}const da=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],fa=new Set([...da,"pathRotation"]),Py=n=>n===ha||n===se,z1=new Set(["x","y","z"]),V1=da.filter(n=>!z1.has(n));function P1(n){const e=[];return V1.forEach(s=>{const a=n.getValue(s);a!==void 0&&(e.push([s,a.get()]),a.set(s.startsWith("scale")?1:0))}),e}const Oi={width:({x:n},{paddingLeft:e="0",paddingRight:s="0",boxSizing:a})=>{const l=n.max-n.min;return a==="border-box"?l:l-parseFloat(e)-parseFloat(s)},height:({y:n},{paddingTop:e="0",paddingBottom:s="0",boxSizing:a})=>{const l=n.max-n.min;return a==="border-box"?l:l-parseFloat(e)-parseFloat(s)},top:(n,{top:e})=>parseFloat(e),left:(n,{left:e})=>parseFloat(e),bottom:({y:n},{top:e})=>parseFloat(e)+(n.max-n.min),right:({x:n},{left:e})=>parseFloat(e)+(n.max-n.min),x:(n,{transform:e})=>od(e,"x"),y:(n,{transform:e})=>od(e,"y")};Oi.translateX=Oi.x;Oi.translateY=Oi.y;const us=new Set;let ld=!1,ud=!1,cd=!1;function pb(){if(ud){const n=Array.from(us).filter(a=>a.needsMeasurement),e=new Set(n.map(a=>a.element)),s=new Map;e.forEach(a=>{const l=P1(a);l.length&&(s.set(a,l),a.render())}),n.forEach(a=>a.measureInitialState()),e.forEach(a=>{a.render();const l=s.get(a);l&&l.forEach(([u,c])=>{var d;(d=a.getValue(u))==null||d.set(c)})}),n.forEach(a=>a.measureEndState()),n.forEach(a=>{a.suspendedScrollY!==void 0&&window.scrollTo(0,a.suspendedScrollY)})}ud=!1,ld=!1,us.forEach(n=>n.complete(cd)),us.clear()}function gb(){us.forEach(n=>{n.readKeyframes(),n.needsMeasurement&&(ud=!0)})}function H1(){cd=!0,gb(),pb(),cd=!1}class ef{constructor(e,s,a,l,u,c=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=s,this.name=a,this.motionValue=l,this.element=u,this.isAsync=c}scheduleResolve(){this.state="scheduled",this.isAsync?(us.add(this),ld||(ld=!0,Ve.read(gb),Ve.resolveKeyframes(pb))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:s,element:a,motionValue:l}=this;if(e[0]===null){const u=l==null?void 0:l.get(),c=e[e.length-1];if(u!==void 0)e[0]=u;else if(a&&s){const d=a.readValue(s,c);d!=null&&(e[0]=d)}e[0]===void 0&&(e[0]=c),l&&u===void 0&&l.set(e[0])}D1(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),us.delete(this)}cancel(){this.state==="scheduled"&&(us.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const $1=n=>n.startsWith("--");function yb(n,e,s){$1(e)?n.style.setProperty(e,s):n.style[e]=s}const q1={};function vb(n,e){const s=Iv(n);return()=>q1[e]??s()}const G1=vb(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),bb=vb(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),fr=([n,e,s,a])=>`cubic-bezier(${n}, ${e}, ${s}, ${a})`,Hy={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:fr([0,.65,.55,1]),circOut:fr([.55,0,1,.45]),backIn:fr([.31,.01,.66,-.59]),backOut:fr([.33,1.53,.69,.99])};function wb(n,e){if(n)return typeof n=="function"?bb()?db(n,e):"ease-out":nb(n)?fr(n):Array.isArray(n)?n.map(s=>wb(s,e)||Hy.easeOut):Hy[n]}function I1(n,e,s,{delay:a=0,duration:l=300,repeat:u=0,repeatType:c="loop",ease:d="easeOut",times:m}={},p=void 0){const g={[e]:s};m&&(g.offset=m);const v=wb(d,l);Array.isArray(v)&&(g.easing=v);const w={delay:a,duration:l,easing:Array.isArray(v)?"linear":v,fill:"both",iterations:u+1,direction:c==="reverse"?"alternate":"normal"};return p&&(w.pseudoElement=p),n.animate(g,w)}function xb(n){return typeof n=="function"&&"applyToOptions"in n}function K1({type:n,...e}){return xb(n)&&bb()?n.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class _b extends Wd{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;const{element:s,name:a,keyframes:l,pseudoElement:u,allowFlatten:c=!1,finalKeyframe:d,onComplete:m}=e;this.isPseudoElement=!!u,this.allowFlatten=c,this.options=e,Gd(typeof e.type!="string");const p=K1(e);this.animation=I1(s,a,l,p,u),p.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!u){const g=eu(l,this.options,d,this.speed);this.updateMotionValue&&this.updateMotionValue(g),yb(s,a,g),this.animation.cancel()}m==null||m(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,s;(s=(e=this.animation).finish)==null||s.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var s,a,l;const e=(s=this.options)==null?void 0:s.element;!this.isPseudoElement&&(e!=null&&e.isConnected)&&((l=(a=this.animation).commitStyles)==null||l.call(a))}get duration(){var s,a;const e=((a=(s=this.animation.effect)==null?void 0:s.getComputedTiming)==null?void 0:a.call(s).duration)||0;return nn(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+nn(e)}get time(){return nn(Number(this.animation.currentTime)||0)}set time(e){const s=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Gt(e),s&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,rangeStart:s,rangeEnd:a,observe:l}){var u;return this.allowFlatten&&((u=this.animation.effect)==null||u.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&G1()?(this.animation.timeline=e,s&&(this.animation.rangeStart=s),a&&(this.animation.rangeEnd=a),sn):l(this)}}const Sb={anticipate:Zv,backInOut:Qv,circInOut:eb};function F1(n){return n in Sb}function Y1(n){typeof n.ease=="string"&&F1(n.ease)&&(n.ease=Sb[n.ease])}const Oh=10;class X1 extends _b{constructor(e){Y1(e),mb(e),super(e),e.startTime!==void 0&&e.autoplay!==!1&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:s,onUpdate:a,onComplete:l,element:u,...c}=this.options;if(!s)return;if(e!==void 0){s.set(e);return}const d=new Vl({...c,autoplay:!1}),m=Math.max(Oh,_t.now()-this.startTime),p=Cn(0,Oh,m-Oh),g=d.sample(m).value,{name:v}=this.options;u&&v&&yb(u,v,g),s.setWithVelocity(d.sample(Math.max(0,m-p)).value,g,p),d.stop()}}const $y=(n,e)=>e==="zIndex"?!1:!!(typeof n=="number"||Array.isArray(n)||typeof n=="string"&&(pn.test(n)||n==="0")&&!n.startsWith("url("));function J1(n){const e=n[0];if(n.length===1)return!0;for(let s=0;sObject.hasOwnProperty.call(Element.prototype,"animate"));function nT(n){var v;const{motionValue:e,name:s,repeatDelay:a,repeatType:l,damping:u,type:c,keyframes:d}=n;if(!(((v=e==null?void 0:e.owner)==null?void 0:v.current)instanceof HTMLElement))return!1;const{onUpdate:p,transformTemplate:g}=e.owner.getProps();return tT()&&s&&(Tb.has(s)||eT.has(s)&&W1(d))&&(s!=="transform"||!g)&&!p&&!a&&l!=="mirror"&&u!==0&&c!=="inertia"}const iT=40;class sT extends Wd{constructor({autoplay:e=!0,delay:s=0,type:a="keyframes",repeat:l=0,repeatDelay:u=0,repeatType:c="loop",keyframes:d,name:m,motionValue:p,element:g,...v}){var S;super(),this.stop=()=>{var E,k;this._animation&&(this._animation.stop(),(E=this.stopTimeline)==null||E.call(this)),(k=this.keyframeResolver)==null||k.cancel()},this.createdAt=_t.now();const w={autoplay:e,delay:s,type:a,repeat:l,repeatDelay:u,repeatType:c,name:m,motionValue:p,element:g,...v},_=(g==null?void 0:g.KeyframeResolver)||ef;this.keyframeResolver=new _(d,(E,k,C)=>this.onKeyframesResolved(E,k,w,!C),m,p,g),(S=this.keyframeResolver)==null||S.scheduleResolve()}onKeyframesResolved(e,s,a,l){var C,N;this.keyframeResolver=void 0;const{name:u,type:c,velocity:d,delay:m,isHandoff:p,onUpdate:g}=a;this.resolvedAt=_t.now();let v=!0;Q1(e,u,c,d)||(v=!1,(Ni.instantAnimations||!m)&&(g==null||g(eu(e,a,s))),e[0]=e[e.length-1],hd(a),a.repeat=0);const _={startTime:l?this.resolvedAt?this.resolvedAt-this.createdAt>iT?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:s,...a,keyframes:e},S=v&&!p&&nT(_),E=(N=(C=_.motionValue)==null?void 0:C.owner)==null?void 0:N.current;let k;if(S)try{k=new X1({..._,element:E})}catch{k=new Vl(_)}else k=new Vl(_);k.finished.then(()=>{this.notifyFinished()}).catch(sn),this.pendingTimeline&&(this.stopTimeline=k.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=k}get finished(){return this._animation?this.animation.finished:this._finished}then(e,s){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),H1()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var e;this._animation&&this.animation.cancel(),(e=this.keyframeResolver)==null||e.cancel()}}function Eb(n,e,s,a=0,l=1){const u=Array.from(n).sort((p,g)=>p.sortNodePosition(g)).indexOf(e),c=n.size,d=(c-1)*a;return typeof s=="function"?s(u,c):l===1?u*a:d-u*a}const qy=30,aT=n=>!isNaN(parseFloat(n));class rT{constructor(e,s={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=a=>{var u;const l=_t.now();if(this.updatedAt!==l&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(a),this.current!==this.prev&&((u=this.events.change)==null||u.notify(this.current),this.dependents))for(const c of this.dependents)c.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=s.owner}setCurrent(e){this.current=e,this.updatedAt=_t.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=aT(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,s){this.events[e]||(this.events[e]=new Id);const a=this.events[e].add(s);return e==="change"?()=>{a(),Ve.read(()=>{this.events.change.getSize()||this.stop()})}:a}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,s){this.passiveEffect=e,this.stopPassiveEffect=s}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,s,a){this.set(s),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-a}jump(e,s=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,s&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=_t.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>qy)return 0;const s=Math.min(this.updatedAt-this.prevUpdatedAt,qy);return Kv(parseFloat(this.current)-parseFloat(this.prevFrameValue),s)}start(e){return this.stop(),new Promise(s=>{this.hasAnimated=!0,this.animation=e(s),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var e,s;(e=this.dependents)==null||e.clear(),(s=this.events.destroy)==null||s.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function ca(n,e){return new rT(n,e)}function Ab(n,e){if(n!=null&&n.inherit&&e){const{inherit:s,...a}=n;return{...e,...a}}return n}function tf(n,e){const s=(n==null?void 0:n[e])??(n==null?void 0:n.default)??n;return s!==n?Ab(s,n):s}const oT={type:"spring",stiffness:500,damping:25,restSpeed:10},lT=n=>({type:"spring",stiffness:550,damping:n===0?2*Math.sqrt(550):30,restSpeed:10}),uT={type:"keyframes",duration:.8},cT={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},hT=(n,{keyframes:e})=>e.length>2?uT:fa.has(n)?n.startsWith("scale")?lT(e[1]):oT:cT,dT=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function fT(n){for(const e in n)if(!dT.has(e))return!0;return!1}const nf=(n,e,s,a={},l,u)=>c=>{const d=tf(a,n)||{},m=d.delay||a.delay||0;let{elapsed:p=0}=a;p=p-Gt(m);const g={keyframes:Array.isArray(s)?s:[null,s],ease:"easeOut",velocity:e.getVelocity(),...d,delay:-p,onUpdate:w=>{e.set(w),d.onUpdate&&d.onUpdate(w)},onComplete:()=>{c(),d.onComplete&&d.onComplete()},name:n,motionValue:e,element:u?void 0:l};fT(d)||Object.assign(g,hT(n,g)),g.duration&&(g.duration=Gt(g.duration)),g.repeatDelay&&(g.repeatDelay=Gt(g.repeatDelay)),g.from!==void 0&&(g.keyframes[0]=g.from);let v=!1;if((g.type===!1||g.duration===0&&!g.repeatDelay)&&(hd(g),g.delay===0&&(v=!0)),(Ni.instantAnimations||Ni.skipAnimations||l!=null&&l.shouldSkipAnimations||d.skipAnimations)&&(v=!0,hd(g),g.delay=0),g.allowFlatten=!d.type&&!d.ease,v&&!u&&e.get()!==void 0){const w=eu(g.keyframes,d);if(w!==void 0){Ve.update(()=>{g.onUpdate(w),g.onComplete()});return}}return d.isSync?new Vl(g):new sT(g)},mT=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function pT(n){const e=mT.exec(n);if(!e)return[,];const[,s,a,l]=e;return[`--${s??a}`,l]}function Rb(n,e,s=1){const[a,l]=pT(n);if(!a)return;const u=window.getComputedStyle(e).getPropertyValue(a);if(u){const c=u.trim();return $v(c)?parseFloat(c):c}return Yd(l)?Rb(l,e,s+1):l}function Gy(n){const e=[{},{}];return n==null||n.values.forEach((s,a)=>{e[0][a]=s.get(),e[1][a]=s.getVelocity()}),e}function sf(n,e,s,a){if(typeof e=="function"){const[l,u]=Gy(a);e=e(s!==void 0?s:n.custom,l,u)}if(typeof e=="string"&&(e=n.variants&&n.variants[e]),typeof e=="function"){const[l,u]=Gy(a);e=e(s!==void 0?s:n.custom,l,u)}return e}function cs(n,e,s){const a=n.getProps();return sf(a,e,s!==void 0?s:a.custom,n)}const Cb=new Set(["width","height","top","left","right","bottom",...da]),dd=n=>Array.isArray(n);function gT(n,e,s){n.hasValue(e)?n.getValue(e).set(s):n.addValue(e,ca(s))}function yT(n){return dd(n)?n[n.length-1]||0:n}function vT(n,e){const s=cs(n,e);let{transitionEnd:a={},transition:l={},...u}=s||{};u={...u,...a};for(const c in u){const d=yT(u[c]);gT(n,c,d)}}const vt=n=>!!(n&&n.getVelocity);function bT(n){return!!(vt(n)&&n.add)}function fd(n,e){const s=n.getValue("willChange");if(bT(s))return s.add(e);if(!s&&Ni.WillChange){const a=new Ni.WillChange("auto");n.addValue("willChange",a),a.add(e)}}function af(n){return n.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}const wT="framerAppearId",kb="data-"+af(wT);function jb(n){return n.props[kb]}function xT({protectedKeys:n,needsAnimating:e},s){const a=n.hasOwnProperty(s)&&e[s]!==!0;return e[s]=!1,a}function Ob(n,e,{delay:s=0,transitionOverride:a,type:l}={}){let{transition:u,transitionEnd:c,...d}=e;const m=n.getDefaultTransition();u=u?Ab(u,m):m;const p=u==null?void 0:u.reduceMotion,g=u==null?void 0:u.skipAnimations;a&&(u=a);const v=[],w=l&&n.animationState&&n.animationState.getState()[l],_=u==null?void 0:u.path;_&&_.animateVisualElement(n,d,u,s,v);for(const S in d){const E=n.getValue(S,n.latestValues[S]??null),k=d[S];if(k===void 0||w&&xT(w,S))continue;const C={delay:s,...tf(u||{},S)};g&&(C.skipAnimations=!0);const N=E.get();if(N!==void 0&&!E.isAnimating()&&!Array.isArray(k)&&k===N&&!C.velocity){Ve.update(()=>E.set(k));continue}let O=!1;if(window.MotionHandoffAnimation){const J=jb(n);if(J){const G=window.MotionHandoffAnimation(J,S,Ve);G!==null&&(C.startTime=G,O=!0)}}fd(n,S);const z=p??n.shouldReduceMotion;E.start(nf(S,E,k,z&&Cb.has(S)?{type:!1}:C,n,O));const F=E.animation;F&&v.push(F)}if(c){const S=()=>Ve.update(()=>{c&&vT(n,c)});v.length?Promise.all(v).then(S):S()}return v}function md(n,e,s={}){var m;const a=cs(n,e,s.type==="exit"?(m=n.presenceContext)==null?void 0:m.custom:void 0);let{transition:l=n.getDefaultTransition()||{}}=a||{};s.transitionOverride&&(l=s.transitionOverride);const u=a?()=>Promise.all(Ob(n,a,s)):()=>Promise.resolve(),c=n.variantChildren&&n.variantChildren.size?(p=0)=>{const{delayChildren:g=0,staggerChildren:v,staggerDirection:w}=l;return _T(n,e,p,g,v,w,s)}:()=>Promise.resolve(),{when:d}=l;if(d){const[p,g]=d==="beforeChildren"?[u,c]:[c,u];return p().then(()=>g())}else return Promise.all([u(),c(s.delay)])}function _T(n,e,s=0,a=0,l=0,u=1,c){const d=[];for(const m of n.variantChildren)m.notify("AnimationStart",e),d.push(md(m,e,{...c,delay:s+(typeof a=="function"?0:a)+Eb(n.variantChildren,m,a,l,u)}).then(()=>m.notify("AnimationComplete",e)));return Promise.all(d)}function ST(n,e,s={}){n.notify("AnimationStart",e);let a;if(Array.isArray(e)){const l=e.map(u=>md(n,u,s));a=Promise.all(l)}else if(typeof e=="string")a=md(n,e,s);else{const l=typeof e=="function"?cs(n,e,s.custom):e;a=Promise.all(Ob(n,l,s))}return a.then(()=>{n.notify("AnimationComplete",e)})}const TT={test:n=>n==="auto",parse:n=>n},Nb=n=>e=>e.test(n),Db=[ha,se,Rn,Zn,JS,XS,TT],Iy=n=>Db.find(Nb(n));function ET(n){return typeof n=="number"?n===0:n!==null?n==="none"||n==="0"||Gv(n):!0}const AT=new Set(["brightness","contrast","saturate","opacity"]);function RT(n){const[e,s]=n.slice(0,-1).split("(");if(e==="drop-shadow")return n;const[a]=s.match(Xd)||[];if(!a)return n;const l=s.replace(a,"");let u=AT.has(e)?1:0;return a!==s&&(u*=100),e+"("+u+l+")"}const CT=/\b([a-z-]*)\(.*?\)/gu,pd={...pn,getAnimatableNone:n=>{const e=n.match(CT);return e?e.map(RT).join(" "):n}},gd={...pn,getAnimatableNone:n=>{const e=pn.parse(n);return pn.createTransformer(n)(e.map(a=>typeof a=="number"?0:typeof a=="object"?{...a,alpha:1}:a))}},Ky={...ha,transform:Math.round},kT={rotate:Zn,pathRotation:Zn,rotateX:Zn,rotateY:Zn,rotateZ:Zn,scale:dl,scaleX:dl,scaleY:dl,scaleZ:dl,skew:Zn,skewX:Zn,skewY:Zn,distance:se,translateX:se,translateY:se,translateZ:se,x:se,y:se,z:se,perspective:se,transformPerspective:se,opacity:Rr,originX:Ny,originY:Ny,originZ:se},Pl={borderWidth:se,borderTopWidth:se,borderRightWidth:se,borderBottomWidth:se,borderLeftWidth:se,borderRadius:se,borderTopLeftRadius:se,borderTopRightRadius:se,borderBottomRightRadius:se,borderBottomLeftRadius:se,width:se,maxWidth:se,height:se,maxHeight:se,top:se,right:se,bottom:se,left:se,inset:se,insetBlock:se,insetBlockStart:se,insetBlockEnd:se,insetInline:se,insetInlineStart:se,insetInlineEnd:se,padding:se,paddingTop:se,paddingRight:se,paddingBottom:se,paddingLeft:se,paddingBlock:se,paddingBlockStart:se,paddingBlockEnd:se,paddingInline:se,paddingInlineStart:se,paddingInlineEnd:se,margin:se,marginTop:se,marginRight:se,marginBottom:se,marginLeft:se,marginBlock:se,marginBlockStart:se,marginBlockEnd:se,marginInline:se,marginInlineStart:se,marginInlineEnd:se,fontSize:se,backgroundPositionX:se,backgroundPositionY:se,...kT,zIndex:Ky,fillOpacity:Rr,strokeOpacity:Rr,numOctaves:Ky},jT={...Pl,color:at,backgroundColor:at,outlineColor:at,fill:at,stroke:at,borderColor:at,borderTopColor:at,borderRightColor:at,borderBottomColor:at,borderLeftColor:at,filter:pd,WebkitFilter:pd,mask:gd,WebkitMask:gd},Mb=n=>jT[n],OT=new Set([pd,gd]);function Ub(n,e){let s=Mb(n);return OT.has(s)||(s=pn),s.getAnimatableNone?s.getAnimatableNone(e):void 0}const NT=new Set(["auto","none","0"]);function DT(n,e,s){let a=0,l;for(;a{e.getValue(m).set(p)}),this.resolveNoneKeyframes()}}const rf=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"];function Bb(n,e,s){if(n==null)return[];if(n instanceof EventTarget)return[n];if(typeof n=="string"){let a=document;const l=(s==null?void 0:s[n])??a.querySelectorAll(n);return l?Array.from(l):[]}return Array.from(n).filter(a=>a!=null)}const yd=(n,e)=>e&&typeof n=="number"?e.transform(n):n;function Al(n){return qv(n)&&"offsetHeight"in n&&!("ownerSVGElement"in n)}const{schedule:of}=ib(queueMicrotask,!1),cn={x:!1,y:!1};function Lb(){return cn.x||cn.y}function UT(n){return n==="x"||n==="y"?cn[n]?null:(cn[n]=!0,()=>{cn[n]=!1}):cn.x||cn.y?null:(cn.x=cn.y=!0,()=>{cn.x=cn.y=!1})}function zb(n,e){const s=Bb(n),a=new AbortController,l={passive:!0,...e,signal:a.signal};return[s,l,()=>a.abort()]}function BT(n){return!(n.pointerType==="touch"||Lb())}function LT(n,e,s={}){const[a,l,u]=zb(n,s);return a.forEach(c=>{let d=!1,m=!1,p;const g=()=>{c.removeEventListener("pointerleave",S)},v=k=>{p&&(p(k),p=void 0),g()},w=k=>{d=!1,window.removeEventListener("pointerup",w),window.removeEventListener("pointercancel",w),m&&(m=!1,v(k))},_=()=>{d=!0,window.addEventListener("pointerup",w,l),window.addEventListener("pointercancel",w,l)},S=k=>{if(k.pointerType!=="touch"){if(d){m=!0;return}v(k)}},E=k=>{if(!BT(k))return;m=!1;const C=e(c,k);typeof C=="function"&&(p=C,c.addEventListener("pointerleave",S,l))};c.addEventListener("pointerenter",E,l),c.addEventListener("pointerdown",_,l)}),u}const Vb=(n,e)=>e?n===e?!0:Vb(n,e.parentElement):!1,lf=n=>n.pointerType==="mouse"?typeof n.button!="number"||n.button<=0:n.isPrimary!==!1,zT=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function VT(n){return zT.has(n.tagName)||n.isContentEditable===!0}const PT=new Set(["INPUT","SELECT","TEXTAREA"]);function HT(n){return PT.has(n.tagName)||n.isContentEditable===!0}const Rl=new WeakSet;function Fy(n){return e=>{e.key==="Enter"&&n(e)}}function Nh(n,e){n.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const $T=(n,e)=>{const s=n.currentTarget;if(!s)return;const a=Fy(()=>{if(Rl.has(s))return;Nh(s,"down");const l=Fy(()=>{Nh(s,"up")}),u=()=>Nh(s,"cancel");s.addEventListener("keyup",l,e),s.addEventListener("blur",u,e)});s.addEventListener("keydown",a,e),s.addEventListener("blur",()=>s.removeEventListener("keydown",a),e)};function Yy(n){return lf(n)&&!Lb()}const Xy=new WeakSet;function qT(n,e,s={}){const[a,l,u]=zb(n,s),c=d=>{const m=d.currentTarget;if(!Yy(d)||Xy.has(d))return;Rl.add(m),s.stopPropagation&&Xy.add(d);const p=e(m,d),g={...l,capture:!0},v=(S,E)=>{window.removeEventListener("pointerup",w,g),window.removeEventListener("pointercancel",_,g),Rl.has(m)&&Rl.delete(m),Yy(S)&&typeof p=="function"&&p(S,{success:E})},w=S=>{v(S,m===window||m===document||s.useGlobalTarget||Vb(m,S.target))},_=S=>{v(S,!1)};window.addEventListener("pointerup",w,g),window.addEventListener("pointercancel",_,g)};return a.forEach(d=>{(s.useGlobalTarget?window:d).addEventListener("pointerdown",c,l),Al(d)&&(d.addEventListener("focus",p=>$T(p,l)),!VT(d)&&!d.hasAttribute("tabindex")&&(d.tabIndex=0))}),u}function uf(n){return qv(n)&&"ownerSVGElement"in n}const Cl=new WeakMap;let Ci;const Pb=(n,e,s)=>(a,l)=>l&&l[0]?l[0][n+"Size"]:uf(a)&&"getBBox"in a?a.getBBox()[e]:a[s],GT=Pb("inline","width","offsetWidth"),IT=Pb("block","height","offsetHeight");function KT({target:n,borderBoxSize:e}){var s;(s=Cl.get(n))==null||s.forEach(a=>{a(n,{get width(){return GT(n,e)},get height(){return IT(n,e)}})})}function FT(n){n.forEach(KT)}function YT(){typeof ResizeObserver>"u"||(Ci=new ResizeObserver(FT))}function XT(n,e){Ci||YT();const s=Bb(n);return s.forEach(a=>{let l=Cl.get(a);l||(l=new Set,Cl.set(a,l)),l.add(e),Ci==null||Ci.observe(a)}),()=>{s.forEach(a=>{const l=Cl.get(a);l==null||l.delete(e),l!=null&&l.size||Ci==null||Ci.unobserve(a)})}}const kl=new Set;let aa;function JT(){aa=()=>{const n={get width(){return window.innerWidth},get height(){return window.innerHeight}};kl.forEach(e=>e(n))},window.addEventListener("resize",aa)}function QT(n){return kl.add(n),aa||JT(),()=>{kl.delete(n),!kl.size&&typeof aa=="function"&&(window.removeEventListener("resize",aa),aa=void 0)}}function Jy(n,e){return typeof n=="function"?QT(n):XT(n,e)}function ZT(n){return uf(n)&&n.tagName==="svg"}const WT=[...Db,at,pn],eE=n=>WT.find(Nb(n)),Qy=()=>({translate:0,scale:1,origin:0,originPoint:0}),ra=()=>({x:Qy(),y:Qy()}),Zy=()=>({min:0,max:0}),ot=()=>({x:Zy(),y:Zy()}),tE=new WeakMap;function tu(n){return n!==null&&typeof n=="object"&&typeof n.start=="function"}function Cr(n){return typeof n=="string"||Array.isArray(n)}const cf=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],hf=["initial",...cf];function nu(n){return tu(n.animate)||hf.some(e=>Cr(n[e]))}function Hb(n){return!!(nu(n)||n.variants)}function nE(n,e,s){for(const a in e){const l=e[a],u=s[a];if(vt(l))n.addValue(a,l);else if(vt(u))n.addValue(a,ca(l,{owner:n}));else if(u!==l)if(n.hasValue(a)){const c=n.getValue(a);c.liveStyle===!0?c.jump(l):c.hasAnimated||c.set(l)}else{const c=n.getStaticValue(a);n.addValue(a,ca(c!==void 0?c:l,{owner:n}))}}for(const a in s)e[a]===void 0&&n.removeValue(a);return e}const vd={current:null},$b={current:!1},iE=typeof window<"u";function sE(){if($b.current=!0,!!iE)if(window.matchMedia){const n=window.matchMedia("(prefers-reduced-motion)"),e=()=>vd.current=n.matches;n.addEventListener("change",e),e()}else vd.current=!1}const Wy=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let Hl={};function qb(n){Hl=n}function aE(){return Hl}class rE{scrapeMotionValuesFromProps(e,s,a){return{}}constructor({parent:e,props:s,presenceContext:a,reducedMotionConfig:l,skipAnimations:u,blockInitialAnimation:c,visualState:d},m={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=ef,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const _=_t.now();this.renderScheduledAt<_&&(this.renderScheduledAt=_,Ve.render(this.render,!1,!0))};const{latestValues:p,renderState:g}=d;this.latestValues=p,this.baseTarget={...p},this.initialValues=s.initial?{...p}:{},this.renderState=g,this.parent=e,this.props=s,this.presenceContext=a,this.depth=e?e.depth+1:0,this.reducedMotionConfig=l,this.skipAnimationsConfig=u,this.options=m,this.blockInitialAnimation=!!c,this.isControllingVariants=nu(s),this.isVariantNode=Hb(s),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:v,...w}=this.scrapeMotionValuesFromProps(s,{},this);for(const _ in w){const S=w[_];p[_]!==void 0&&vt(S)&&S.set(p[_])}}mount(e){var s,a;if(this.hasBeenMounted)for(const l in this.initialValues)(s=this.values.get(l))==null||s.jump(this.initialValues[l]),this.latestValues[l]=this.initialValues[l];this.current=e,tE.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((l,u)=>this.bindToMotionValue(u,l)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:($b.current||sE(),this.shouldReduceMotion=vd.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,(a=this.parent)==null||a.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){var e;this.projection&&this.projection.unmount(),Di(this.notifyUpdate),Di(this.render),this.valueSubscriptions.forEach(s=>s()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(e=this.parent)==null||e.removeChild(this);for(const s in this.events)this.events[s].clear();for(const s in this.features){const a=this.features[s];a&&(a.unmount(),a.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,s){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),s.accelerate&&Tb.has(e)&&this.current instanceof HTMLElement){const{factory:c,keyframes:d,times:m,ease:p,duration:g}=s.accelerate,v=new _b({element:this.current,name:e,keyframes:d,times:m,ease:p,duration:Gt(g)}),w=c(v);this.valueSubscriptions.set(e,()=>{w(),v.cancel()});return}const a=fa.has(e);a&&this.onBindTransform&&this.onBindTransform();const l=s.on("change",c=>{this.latestValues[e]=c,this.props.onUpdate&&Ve.preRender(this.notifyUpdate),a&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let u;typeof window<"u"&&window.MotionCheckAppearSync&&(u=window.MotionCheckAppearSync(this,e,s)),this.valueSubscriptions.set(e,()=>{l(),u&&u()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in Hl){const s=Hl[e];if(!s)continue;const{isEnabled:a,Feature:l}=s;if(!this.features[e]&&l&&a(this.props)&&(this.features[e]=new l(this)),this.features[e]){const u=this.features[e];u.isMounted?u.update():(u.mount(),u.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ot()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,s){this.latestValues[e]=s}update(e,s){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=s;for(let a=0;as.variantChildren.delete(e)}addValue(e,s){const a=this.values.get(e);s!==a&&(a&&this.removeValue(e),this.bindToMotionValue(e,s),this.values.set(e,s),this.latestValues[e]=s.get())}removeValue(e){this.values.delete(e);const s=this.valueSubscriptions.get(e);s&&(s(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,s){if(this.props.values&&this.props.values[e])return this.props.values[e];let a=this.values.get(e);return a===void 0&&s!==void 0&&(a=ca(s===null?void 0:s,{owner:this}),this.addValue(e,a)),a}readValue(e,s){let a=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return a!=null&&(typeof a=="string"&&($v(a)||Gv(a))?a=parseFloat(a):!eE(a)&&pn.test(s)&&(a=Ub(e,s)),this.setBaseTarget(e,vt(a)?a.get():a)),vt(a)?a.get():a}setBaseTarget(e,s){this.baseTarget[e]=s}getBaseTarget(e){var u;const{initial:s}=this.props;let a;if(typeof s=="string"||typeof s=="object"){const c=sf(this.props,s,(u=this.presenceContext)==null?void 0:u.custom);c&&(a=c[e])}if(s&&a!==void 0)return a;const l=this.getBaseTargetFromProps(this.props,e);return l!==void 0&&!vt(l)?l:this.initialValues[e]!==void 0&&a===void 0?void 0:this.baseTarget[e]}on(e,s){return this.events[e]||(this.events[e]=new Id),this.events[e].add(s)}notify(e,...s){this.events[e]&&this.events[e].notify(...s)}scheduleRenderMicrotask(){of.render(this.render)}}class Gb extends rE{constructor(){super(...arguments),this.KeyframeResolver=MT}sortInstanceNodePosition(e,s){return e.compareDocumentPosition(s)&2?1:-1}getBaseTargetFromProps(e,s){const a=e.style;return a?a[s]:void 0}removeValueFromRenderState(e,{vars:s,style:a}){delete s[e],delete a[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;vt(e)&&(this.childSubscription=e.on("change",s=>{this.current&&(this.current.textContent=`${s}`)}))}}class Mi{constructor(e){this.isMounted=!1,this.node=e}update(){}}function Ib({top:n,left:e,right:s,bottom:a}){return{x:{min:e,max:s},y:{min:n,max:a}}}function oE({x:n,y:e}){return{top:e.min,right:n.max,bottom:e.max,left:n.min}}function lE(n,e){if(!e)return n;const s=e({x:n.left,y:n.top}),a=e({x:n.right,y:n.bottom});return{top:s.y,left:s.x,bottom:a.y,right:a.x}}function Dh(n){return n===void 0||n===1}function bd({scale:n,scaleX:e,scaleY:s}){return!Dh(n)||!Dh(e)||!Dh(s)}function is(n){return bd(n)||Kb(n)||n.z||n.rotate||n.rotateX||n.rotateY||n.skewX||n.skewY}function Kb(n){return e0(n.x)||e0(n.y)}function e0(n){return n&&n!=="0%"}function $l(n,e,s){const a=n-s,l=e*a;return s+l}function t0(n,e,s,a,l){return l!==void 0&&(n=$l(n,l,a)),$l(n,s,a)+e}function wd(n,e=0,s=1,a,l){n.min=t0(n.min,e,s,a,l),n.max=t0(n.max,e,s,a,l)}function Fb(n,{x:e,y:s}){wd(n.x,e.translate,e.scale,e.originPoint),wd(n.y,s.translate,s.scale,s.originPoint)}const n0=.999999999999,i0=1.0000000000001;function uE(n,e,s,a=!1){var d;const l=s.length;if(!l)return;e.x=e.y=1;let u,c;for(let m=0;mn0&&(e.x=1),e.yn0&&(e.y=1)}function En(n,e){n.min+=e,n.max+=e}function s0(n,e,s,a,l=.5){const u=ze(n.min,n.max,l);wd(n,e,s,u,a)}function a0(n,e){return typeof n=="string"?parseFloat(n)/100*(e.max-e.min):n}function jl(n,e,s){const a=s??n;s0(n.x,a0(e.x,a.x),e.scaleX,e.scale,e.originX),s0(n.y,a0(e.y,a.y),e.scaleY,e.scale,e.originY)}function Yb(n,e){return Ib(lE(n.getBoundingClientRect(),e))}function cE(n,e,s){const a=Yb(n,s),{scroll:l}=e;return l&&(En(a.x,l.offset.x),En(a.y,l.offset.y)),a}const hE={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},dE=da.length;function fE(n,e,s){let a="",l=!0;for(let c=0;c{if(!e.target)return n;if(typeof n=="string")if(se.test(n))n=parseFloat(n);else return n;const s=r0(n,e.target.x),a=r0(n,e.target.y);return`${s}% ${a}%`}},mE={correct:(n,{treeScale:e,projectionDelta:s})=>{const a=n,l=pn.parse(n);if(l.length>5)return a;const u=pn.createTransformer(n),c=typeof l[0]!="number"?1:0,d=s.x.scale*e.x,m=s.y.scale*e.y;l[0+c]/=d,l[1+c]/=m;const p=ze(d,m,.5);return typeof l[2+c]=="number"&&(l[2+c]/=p),typeof l[3+c]=="number"&&(l[3+c]/=p),u(l)}},xd={borderRadius:{...hr,applyTo:[...rf]},borderTopLeftRadius:hr,borderTopRightRadius:hr,borderBottomLeftRadius:hr,borderBottomRightRadius:hr,boxShadow:mE};function Jb(n,{layout:e,layoutId:s}){return fa.has(n)||n.startsWith("origin")||(e||s!==void 0)&&(!!xd[n]||n==="opacity")}function ff(n,e,s){var c;const a=n.style,l=e==null?void 0:e.style,u={};if(!a)return u;for(const d in a)(vt(a[d])||l&&vt(l[d])||Jb(d,n)||((c=s==null?void 0:s.getValue(d))==null?void 0:c.liveStyle)!==void 0)&&(u[d]=a[d]);return u}function pE(n){return window.getComputedStyle(n)}class gE extends Gb{constructor(){super(...arguments),this.type="html",this.renderInstance=Xb}readValueFromInstance(e,s){var a;if(fa.has(s))return(a=this.projection)!=null&&a.isProjecting?rd(s):B1(e,s);{const l=pE(e),u=(ab(s)?l.getPropertyValue(s):l[s])||0;return typeof u=="string"?u.trim():u}}measureInstanceViewportBox(e,{transformPagePoint:s}){return Yb(e,s)}build(e,s,a){df(e,s,a.transformTemplate)}scrapeMotionValuesFromProps(e,s,a){return ff(e,s,a)}}const yE={offset:"stroke-dashoffset",array:"stroke-dasharray"},vE={offset:"strokeDashoffset",array:"strokeDasharray"};function bE(n,e,s=1,a=0,l=!0){n.pathLength=1;const u=l?yE:vE;n[u.offset]=`${-a}`,n[u.array]=`${e} ${s}`}const wE=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function Qb(n,{attrX:e,attrY:s,attrScale:a,pathLength:l,pathSpacing:u=1,pathOffset:c=0,...d},m,p,g){if(df(n,d,p),m){n.style.viewBox&&(n.attrs.viewBox=n.style.viewBox);return}n.attrs=n.style,n.style={};const{attrs:v,style:w}=n;v.transform&&(w.transform=v.transform,delete v.transform),(w.transform||v.transformOrigin)&&(w.transformOrigin=v.transformOrigin??"50% 50%",delete v.transformOrigin),w.transform&&(w.transformBox=(g==null?void 0:g.transformBox)??"fill-box",delete v.transformBox);for(const _ of wE)v[_]!==void 0&&(w[_]=v[_],delete v[_]);e!==void 0&&(v.x=e),s!==void 0&&(v.y=s),a!==void 0&&(v.scale=a),l!==void 0&&bE(v,l,u,c,!1)}const Zb=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]),Wb=n=>typeof n=="string"&&n.toLowerCase()==="svg";function xE(n,e,s,a){Xb(n,e,void 0,a);for(const l in e.attrs)n.setAttribute(Zb.has(l)?l:af(l),e.attrs[l])}function ew(n,e,s){const a=ff(n,e,s);for(const l in n)if(vt(n[l])||vt(e[l])){const u=da.indexOf(l)!==-1?"attr"+l.charAt(0).toUpperCase()+l.substring(1):l;a[u]=n[l]}return a}class _E extends Gb{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ot}getBaseTargetFromProps(e,s){return e[s]}readValueFromInstance(e,s){if(fa.has(s)){const a=Mb(s);return a&&a.default||0}return s=Zb.has(s)?s:af(s),e.getAttribute(s)}scrapeMotionValuesFromProps(e,s,a){return ew(e,s,a)}build(e,s,a){Qb(e,s,this.isSVGTag,a.transformTemplate,a.style)}renderInstance(e,s,a,l){xE(e,s,a,l)}mount(e){this.isSVGTag=Wb(e.tagName),super.mount(e)}}const SE=hf.length;function tw(n){if(!n)return;if(!n.isControllingVariants){const s=n.parent?tw(n.parent)||{}:{};return n.props.initial!==void 0&&(s.initial=n.props.initial),s}const e={};for(let s=0;sPromise.all(e.map(({animation:s,options:a})=>ST(n,s,a)))}function RE(n){let e=AE(n),s=o0(),a=!0,l=!1;const u=p=>(g,v)=>{var _;const w=cs(n,v,p==="exit"?(_=n.presenceContext)==null?void 0:_.custom:void 0);if(w){const{transition:S,transitionEnd:E,...k}=w;g={...g,...k,...E}}return g};function c(p){e=p(n)}function d(p){const{props:g}=n,v=tw(n.parent)||{},w=[],_=new Set;let S={},E=1/0;for(let C=0;CE&&F,te=!1;const de=Array.isArray(z)?z:[z];let fe=de.reduce(u(N),{});J===!1&&(fe={});const{prevResolvedValues:qe={}}=O,X={...qe,...fe},ue=ee=>{Z=!0,_.has(ee)&&(te=!0,_.delete(ee)),O.needsAnimating[ee]=!0;const re=n.getValue(ee);re&&(re.liveStyle=!1)};for(const ee in X){const re=fe[ee],me=qe[ee];if(S.hasOwnProperty(ee))continue;let A=!1;dd(re)&&dd(me)?A=!nw(re,me)||Y:A=re!==me,A?re!=null?ue(ee):_.add(ee):re!==void 0&&_.has(ee)?ue(ee):O.protectedKeys[ee]=!0}O.prevProp=z,O.prevResolvedValues=fe,O.isActive&&(S={...S,...fe}),(a||l)&&n.blockInitialAnimation&&(Z=!1);const D=G&&Y;Z&&(!D||te)&&w.push(...de.map(ee=>{const re={type:N};if(typeof ee=="string"&&(a||l)&&!D&&n.manuallyAnimateOnMount&&n.parent){const{parent:me}=n,A=cs(me,ee);if(me.enteringChildren&&A){const{delayChildren:$}=A.transition||{};re.delay=Eb(me.enteringChildren,n,$)}}return{animation:ee,options:re}}))}if(_.size){const C={};if(typeof g.initial!="boolean"){const N=cs(n,Array.isArray(g.initial)?g.initial[0]:g.initial);N&&N.transition&&(C.transition=N.transition)}_.forEach(N=>{const O=n.getBaseTarget(N),z=n.getValue(N);z&&(z.liveStyle=!0),C[N]=O??null}),w.push({animation:C})}let k=!!w.length;return a&&(g.initial===!1||g.initial===g.animate)&&!n.manuallyAnimateOnMount&&(k=!1),a=!1,l=!1,k?e(w):Promise.resolve()}function m(p,g){var w;if(s[p].isActive===g)return Promise.resolve();(w=n.variantChildren)==null||w.forEach(_=>{var S;return(S=_.animationState)==null?void 0:S.setActive(p,g)}),s[p].isActive=g;const v=d(p);for(const _ in s)s[_].protectedKeys={};return v}return{animateChanges:d,setActive:m,setAnimateFunction:c,getState:()=>s,reset:()=>{s=o0(),l=!0}}}function CE(n,e){return typeof e=="string"?e!==n:Array.isArray(e)?!nw(e,n):!1}function es(n=!1){return{isActive:n,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function o0(){return{animate:es(!0),whileInView:es(),whileHover:es(),whileTap:es(),whileDrag:es(),whileFocus:es(),exit:es()}}function _d(n,e){n.min=e.min,n.max=e.max}function ln(n,e){_d(n.x,e.x),_d(n.y,e.y)}function l0(n,e){n.translate=e.translate,n.scale=e.scale,n.originPoint=e.originPoint,n.origin=e.origin}const iw=1e-4,kE=1-iw,jE=1+iw,sw=.01,OE=0-sw,NE=0+sw;function St(n){return n.max-n.min}function DE(n,e,s){return Math.abs(n-e)<=s}function u0(n,e,s,a=.5){n.origin=a,n.originPoint=ze(e.min,e.max,n.origin),n.scale=St(s)/St(e),n.translate=ze(s.min,s.max,n.origin)-n.originPoint,(n.scale>=kE&&n.scale<=jE||isNaN(n.scale))&&(n.scale=1),(n.translate>=OE&&n.translate<=NE||isNaN(n.translate))&&(n.translate=0)}function wr(n,e,s,a){u0(n.x,e.x,s.x,a?a.originX:void 0),u0(n.y,e.y,s.y,a?a.originY:void 0)}function c0(n,e,s,a=0){const l=a?ze(s.min,s.max,a):s.min;n.min=l+e.min,n.max=n.min+St(e)}function ME(n,e,s,a){c0(n.x,e.x,s.x,a==null?void 0:a.x),c0(n.y,e.y,s.y,a==null?void 0:a.y)}function h0(n,e,s,a=0){const l=a?ze(s.min,s.max,a):s.min;n.min=e.min-l,n.max=n.min+St(e)}function ql(n,e,s,a){h0(n.x,e.x,s.x,a==null?void 0:a.x),h0(n.y,e.y,s.y,a==null?void 0:a.y)}function d0(n,e,s,a,l){return n-=e,n=$l(n,1/s,a),l!==void 0&&(n=$l(n,1/l,a)),n}function UE(n,e=0,s=1,a=.5,l,u=n,c=n){if(Rn.test(e)&&(e=parseFloat(e),e=ze(c.min,c.max,e/100)-c.min),typeof e!="number")return;let d=ze(u.min,u.max,a);n===u&&(d-=e),n.min=d0(n.min,e,s,d,l),n.max=d0(n.max,e,s,d,l)}function f0(n,e,[s,a,l],u,c){UE(n,e[s],e[a],e[l],e.scale,u,c)}const BE=["x","scaleX","originX"],LE=["y","scaleY","originY"];function m0(n,e,s,a){f0(n.x,e,BE,s?s.x:void 0,a?a.x:void 0),f0(n.y,e,LE,s?s.y:void 0,a?a.y:void 0)}function p0(n){return n.translate===0&&n.scale===1}function aw(n){return p0(n.x)&&p0(n.y)}function g0(n,e){return n.min===e.min&&n.max===e.max}function zE(n,e){return g0(n.x,e.x)&&g0(n.y,e.y)}function y0(n,e){return Math.round(n.min)===Math.round(e.min)&&Math.round(n.max)===Math.round(e.max)}function rw(n,e){return y0(n.x,e.x)&&y0(n.y,e.y)}function v0(n){return St(n.x)/St(n.y)}function b0(n,e){return n.translate===e.translate&&n.scale===e.scale&&n.originPoint===e.originPoint}function Sn(n){return[n("x"),n("y")]}function VE(n,e,s){let a="";const l=n.x.translate/e.x,u=n.y.translate/e.y,c=(s==null?void 0:s.z)||0;if((l||u||c)&&(a=`translate3d(${l}px, ${u}px, ${c}px) `),(e.x!==1||e.y!==1)&&(a+=`scale(${1/e.x}, ${1/e.y}) `),s){const{transformPerspective:p,rotate:g,pathRotation:v,rotateX:w,rotateY:_,skewX:S,skewY:E}=s;p&&(a=`perspective(${p}px) ${a}`),g&&(a+=`rotate(${g}deg) `),v&&(a+=`rotate(${v}deg) `),w&&(a+=`rotateX(${w}deg) `),_&&(a+=`rotateY(${_}deg) `),S&&(a+=`skewX(${S}deg) `),E&&(a+=`skewY(${E}deg) `)}const d=n.x.scale*e.x,m=n.y.scale*e.y;return(d!==1||m!==1)&&(a+=`scale(${d}, ${m})`),a||"none"}const PE=rf.length,w0=n=>typeof n=="string"?parseFloat(n):n,x0=n=>typeof n=="number"||se.test(n);function HE(n,e,s,a,l,u){l?(n.opacity=ze(0,s.opacity??1,$E(a)),n.opacityExit=ze(e.opacity??1,0,qE(a))):u&&(n.opacity=ze(e.opacity??1,s.opacity??1,a));for(let c=0;cae?1:s(Ar(n,e,a))}function GE(n,e,s){const a=vt(n)?n:ca(n);return a.start(nf("",a,e,s)),a.animation}function kr(n,e,s,a={passive:!0}){return n.addEventListener(e,s,a),()=>n.removeEventListener(e,s,a)}const IE=(n,e)=>n.depth-e.depth;class KE{constructor(){this.children=[],this.isDirty=!1}add(e){qd(this.children,e),this.isDirty=!0}remove(e){Ul(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(IE),this.isDirty=!1,this.children.forEach(e)}}function FE(n,e){const s=_t.now(),a=({timestamp:l})=>{const u=l-s;u>=e&&(Di(a),n(u-e))};return Ve.setup(a,!0),()=>Di(a)}function Ol(n){return vt(n)?n.get():n}class YE{constructor(){this.members=[]}add(e){qd(this.members,e);for(let s=this.members.length-1;s>=0;s--){const a=this.members[s];if(a===e||a===this.lead||a===this.prevLead)continue;const l=a.instance;(!l||l.isConnected===!1)&&!a.snapshot&&(Ul(this.members,a),a.unmount())}e.scheduleRender()}remove(e){if(Ul(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const s=this.members[this.members.length-1];s&&this.promote(s)}}relegate(e){var s;for(let a=this.members.indexOf(e)-1;a>=0;a--){const l=this.members[a];if(l.isPresent!==!1&&((s=l.instance)==null?void 0:s.isConnected)!==!1)return this.promote(l),!0}return!1}promote(e,s){var l;const a=this.lead;if(e!==a&&(this.prevLead=a,this.lead=e,e.show(),a)){a.updateSnapshot(),e.scheduleRender();const{layoutDependency:u}=a.options,{layoutDependency:c}=e.options;(u===void 0||u!==c)&&(e.resumeFrom=a,s&&(a.preserveOpacity=!0),a.snapshot&&(e.snapshot=a.snapshot,e.snapshot.latestValues=a.animationValues||a.latestValues),(l=e.root)!=null&&l.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&a.hide()}}exitAnimationComplete(){this.members.forEach(e=>{var s,a,l,u,c;(a=(s=e.options).onExitComplete)==null||a.call(s),(c=(l=e.resumingFrom)==null?void 0:(u=l.options).onExitComplete)==null||c.call(u)})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){var e;(e=this.lead)!=null&&e.snapshot&&(this.lead.snapshot=void 0)}}const Nl={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Mh=["","X","Y","Z"],XE=1e3;let JE=0;function Uh(n,e,s,a){const{latestValues:l}=e;l[n]&&(s[n]=l[n],e.setStaticValue(n,0),a&&(a[n]=0))}function lw(n){if(n.hasCheckedOptimisedAppear=!0,n.root===n)return;const{visualElement:e}=n.options;if(!e)return;const s=jb(e);if(window.MotionHasOptimisedAnimation(s,"transform")){const{layout:l,layoutId:u}=n.options;window.MotionCancelOptimisedAnimation(s,"transform",Ve,!(l||u))}const{parent:a}=n;a&&!a.hasCheckedOptimisedAppear&&lw(a)}function uw({attachResizeListener:n,defaultParent:e,measureScroll:s,checkIsScrollRoot:a,resetTransform:l}){return class{constructor(c={},d=e==null?void 0:e()){this.id=JE++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(WE),this.nodes.forEach(aA),this.nodes.forEach(rA),this.nodes.forEach(eA)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=c,this.root=d?d.root||d:this,this.path=d?[...d.path,d]:[],this.parent=d,this.depth=d?d.depth+1:0;for(let m=0;mthis.root.updateBlockedByResize=!1;Ve.read(()=>{v=window.innerWidth}),n(c,()=>{const _=window.innerWidth;_!==v&&(v=_,this.root.updateBlockedByResize=!0,g&&g(),g=FE(w,250),Nl.hasAnimatedSinceResize&&(Nl.hasAnimatedSinceResize=!1,this.nodes.forEach(E0)))})}d&&this.root.registerSharedNode(d,this),this.options.animate!==!1&&p&&(d||m)&&this.addEventListener("didUpdate",({delta:g,hasLayoutChanged:v,hasRelativeLayoutChanged:w,layout:_})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const S=this.options.transition||p.getDefaultTransition()||hA,{onLayoutAnimationStart:E,onLayoutAnimationComplete:k}=p.getProps(),C=!this.targetLayout||!rw(this.targetLayout,_),N=!v&&w;if(this.options.layoutRoot||this.resumeFrom||N||v&&(C||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const O={...tf(S,"layout"),onPlay:E,onComplete:k};(p.shouldReduceMotion||this.options.layoutRoot)&&(O.delay=0,O.type=!1),this.startAnimation(O),this.setAnimationOrigin(g,N,O.path)}else v||E0(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=_})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const c=this.getStack();c&&c.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Di(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(oA),this.animationId++)}getTransformTemplate(){const{visualElement:c}=this.options;return c&&c.getProps().transformTemplate}willUpdate(c=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&lw(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let g=0;g{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!St(this.snapshot.measuredBox.x)&&!St(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let m=0;m{const G=J/1e3,Y=F==null?void 0:F(G);Y?(w.x.translate=Y.x,w.x.scale=ze(c.x.scale,1,G),w.x.origin=c.x.origin,w.x.originPoint=c.x.originPoint,w.y.translate=Y.y,w.y.scale=ze(c.y.scale,1,G),w.y.origin=c.y.origin,w.y.originPoint=c.y.originPoint):(A0(w.x,c.x,G),A0(w.y,c.y,G)),this.setTargetDelta(w),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ql(_,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),uA(this.relativeTarget,this.relativeTargetOrigin,_,G),z&&zE(this.relativeTarget,z)&&(this.isProjectionDirty=!1),z||(z=ot()),ln(z,this.relativeTarget)),k&&(this.animationValues=v,HE(v,g,this.latestValues,G,O,N)),Y&&Y.rotate!==void 0&&(this.animationValues||(this.animationValues=v),this.animationValues.pathRotation=Y.rotate),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=G},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(c){var d,m,p;this.notifyListeners("animationStart"),(d=this.currentAnimation)==null||d.stop(),(p=(m=this.resumingFrom)==null?void 0:m.currentAnimation)==null||p.stop(),this.pendingAnimation&&(Di(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Ve.update(()=>{Nl.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=ca(0)),this.motionValue.jump(0,!1),this.currentAnimation=GE(this.motionValue,[0,1e3],{...c,velocity:0,isSync:!0,onUpdate:g=>{this.mixTargetDelta(g),c.onUpdate&&c.onUpdate(g)},onComplete:()=>{c.onComplete&&c.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const c=this.getStack();c&&c.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(XE),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const c=this.getLead();let{targetWithTransforms:d,target:m,layout:p,latestValues:g}=c;if(!(!d||!m||!p)){if(this!==c&&this.layout&&p&&cw(this.options.animationType,this.layout.layoutBox,p.layoutBox)){m=this.target||ot();const v=St(this.layout.layoutBox.x);m.x.min=c.target.x.min,m.x.max=m.x.min+v;const w=St(this.layout.layoutBox.y);m.y.min=c.target.y.min,m.y.max=m.y.min+w}ln(d,m),jl(d,g),wr(this.projectionDeltaWithTransform,this.layoutCorrected,d,g)}}registerSharedNode(c,d){this.sharedNodes.has(c)||this.sharedNodes.set(c,new YE),this.sharedNodes.get(c).add(d);const p=d.options.initialPromotionConfig;d.promote({transition:p?p.transition:void 0,preserveFollowOpacity:p&&p.shouldPreserveFollowOpacity?p.shouldPreserveFollowOpacity(d):void 0})}isLead(){const c=this.getStack();return c?c.lead===this:!0}getLead(){var d;const{layoutId:c}=this.options;return c?((d=this.getStack())==null?void 0:d.lead)||this:this}getPrevLead(){var d;const{layoutId:c}=this.options;return c?(d=this.getStack())==null?void 0:d.prevLead:void 0}getStack(){const{layoutId:c}=this.options;if(c)return this.root.sharedNodes.get(c)}promote({needsReset:c,transition:d,preserveFollowOpacity:m}={}){const p=this.getStack();p&&p.promote(this,m),c&&(this.projectionDelta=void 0,this.needsReset=!0),d&&this.setOptions({transition:d})}relegate(){const c=this.getStack();return c?c.relegate(this):!1}resetSkewAndRotation(){const{visualElement:c}=this.options;if(!c)return;let d=!1;const{latestValues:m}=c;if((m.z||m.rotate||m.rotateX||m.rotateY||m.rotateZ||m.skewX||m.skewY)&&(d=!0),!d)return;const p={};m.z&&Uh("z",c,p,this.animationValues);for(let g=0;g{var d;return(d=c.currentAnimation)==null?void 0:d.stop()}),this.root.nodes.forEach(S0),this.root.sharedNodes.clear()}}}function QE(n){n.updateLayout()}function ZE(n){var s;const e=((s=n.resumeFrom)==null?void 0:s.snapshot)||n.snapshot;if(n.isLead()&&n.layout&&e&&n.hasListeners("didUpdate")){const{layoutBox:a,measuredBox:l}=n.layout,{animationType:u}=n.options,c=e.source!==n.layout.source;if(u==="size")Sn(v=>{const w=c?e.measuredBox[v]:e.layoutBox[v],_=St(w);w.min=a[v].min,w.max=w.min+_});else if(u==="x"||u==="y"){const v=u==="x"?"y":"x";_d(c?e.measuredBox[v]:e.layoutBox[v],a[v])}else cw(u,e.layoutBox,a)&&Sn(v=>{const w=c?e.measuredBox[v]:e.layoutBox[v],_=St(a[v]);w.max=w.min+_,n.relativeTarget&&!n.currentAnimation&&(n.isProjectionDirty=!0,n.relativeTarget[v].max=n.relativeTarget[v].min+_)});const d=ra();wr(d,a,e.layoutBox);const m=ra();c?wr(m,n.applyTransform(l,!0),e.measuredBox):wr(m,a,e.layoutBox);const p=!aw(d);let g=!1;if(!n.resumeFrom){const v=n.getClosestProjectingParent();if(v&&!v.resumeFrom){const{snapshot:w,layout:_}=v;if(w&&_){const S=n.options.layoutAnchor||void 0,E=ot();ql(E,e.layoutBox,w.layoutBox,S);const k=ot();ql(k,a,_.layoutBox,S),rw(E,k)||(g=!0),v.options.layoutRoot&&(n.relativeTarget=k,n.relativeTargetOrigin=E,n.relativeParent=v)}}}n.notifyListeners("didUpdate",{layout:a,snapshot:e,delta:m,layoutDelta:d,hasLayoutChanged:p,hasRelativeLayoutChanged:g})}else if(n.isLead()){const{onExitComplete:a}=n.options;a&&a()}n.options.transition=void 0}function WE(n){n.parent&&(n.isProjecting()||(n.isProjectionDirty=n.parent.isProjectionDirty),n.isSharedProjectionDirty||(n.isSharedProjectionDirty=!!(n.isProjectionDirty||n.parent.isProjectionDirty||n.parent.isSharedProjectionDirty)),n.isTransformDirty||(n.isTransformDirty=n.parent.isTransformDirty))}function eA(n){n.isProjectionDirty=n.isSharedProjectionDirty=n.isTransformDirty=!1}function tA(n){n.clearSnapshot()}function S0(n){n.clearMeasurements()}function nA(n){n.isLayoutDirty=!0,n.updateLayout()}function T0(n){n.isLayoutDirty=!1}function iA(n){n.isAnimationBlocked&&n.layout&&!n.isLayoutDirty&&(n.snapshot=n.layout,n.isLayoutDirty=!0)}function sA(n){const{visualElement:e}=n.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),n.resetTransform()}function E0(n){n.finishAnimation(),n.targetDelta=n.relativeTarget=n.target=void 0,n.isProjectionDirty=!0}function aA(n){n.resolveTargetDelta()}function rA(n){n.calcProjection()}function oA(n){n.resetSkewAndRotation()}function lA(n){n.removeLeadSnapshot()}function A0(n,e,s){n.translate=ze(e.translate,0,s),n.scale=ze(e.scale,1,s),n.origin=e.origin,n.originPoint=e.originPoint}function R0(n,e,s,a){n.min=ze(e.min,s.min,a),n.max=ze(e.max,s.max,a)}function uA(n,e,s,a){R0(n.x,e.x,s.x,a),R0(n.y,e.y,s.y,a)}function cA(n){return n.animationValues&&n.animationValues.opacityExit!==void 0}const hA={duration:.45,ease:[.4,0,.1,1]},C0=n=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(n),k0=C0("applewebkit/")&&!C0("chrome/")?Math.round:sn;function j0(n){n.min=k0(n.min),n.max=k0(n.max)}function dA(n){j0(n.x),j0(n.y)}function cw(n,e,s){return n==="position"||n==="preserve-aspect"&&!DE(v0(e),v0(s),.2)}function fA(n){var e;return n!==n.root&&((e=n.scroll)==null?void 0:e.wasRoot)}const mA=uw({attachResizeListener:(n,e)=>kr(n,"resize",e),measureScroll:()=>{var n,e;return{x:document.documentElement.scrollLeft||((n=document.body)==null?void 0:n.scrollLeft)||0,y:document.documentElement.scrollTop||((e=document.body)==null?void 0:e.scrollTop)||0}},checkIsScrollRoot:()=>!0}),Bh={current:void 0},hw=uw({measureScroll:n=>({x:n.scrollLeft,y:n.scrollTop}),defaultParent:()=>{if(!Bh.current){const n=new mA({});n.mount(window),n.setOptions({layoutScroll:!0}),Bh.current=n}return Bh.current},resetTransform:(n,e)=>{n.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:n=>window.getComputedStyle(n).position==="fixed"}),mf=P.createContext({transformPagePoint:n=>n,isStatic:!1,reducedMotion:"never"});function O0(n,e){if(typeof n=="function")return n(e);n!=null&&(n.current=e)}function pA(...n){return e=>{let s=!1;const a=n.map(l=>{const u=O0(l,e);return!s&&typeof u=="function"&&(s=!0),u});if(s)return()=>{for(let l=0;l{const{width:_,height:S,top:E,left:k,right:C,bottom:N,direction:O}=m.current;if(e||u===!1||!d.current||!_||!S)return;const z=O==="rtl",F=s==="left"?z?`right: ${C}`:`left: ${k}`:z?`left: ${k}`:`right: ${C}`,J=a==="bottom"?`bottom: ${N}`:`top: ${E}`;d.current.dataset.motionPopId=c;const G=document.createElement("style");p&&(G.nonce=p);const Y=l??document.head;return Y.appendChild(G),G.sheet&&G.sheet.insertRule(` [data-motion-pop-id="${c}"] { position: absolute !important; width: ${_}px !important; height: ${S}px !important; ${F}px !important; ${J}px !important; } `),()=>{var Z;(Z=d.current)==null||Z.removeAttribute("data-motion-pop-id"),Y.contains(G)&&Y.removeChild(G)}},[e]),b.jsx(yA,{isPresent:e,childRef:d,sizeRef:m,pop:u,children:u===!1?n:P.cloneElement(n,{ref:v})})}const bA=({children:n,initial:e,isPresent:s,onExitComplete:a,custom:l,presenceAffectsLayout:u,mode:c,anchorX:d,anchorY:m,root:p})=>{const g=Hd(wA),v=P.useId(),w=P.useRef(s),_=P.useRef(a);$d(()=>{w.current=s,_.current=a});let S=!0,E=P.useMemo(()=>(S=!1,{id:v,initial:e,isPresent:s,custom:l,onExitComplete:k=>{g.set(k,!0);for(const C of g.values())if(!C)return;a&&a()},register:k=>(g.set(k,!1),()=>{var C;g.delete(k),!w.current&&!g.size&&((C=_.current)==null||C.call(_))})}),[s,g,a]);return u&&S&&(E={...E}),P.useMemo(()=>{g.forEach((k,C)=>g.set(C,!1))},[s]),P.useEffect(()=>{!s&&!g.size&&a&&a()},[s]),n=b.jsx(vA,{pop:c==="popLayout",isPresent:s,anchorX:d,anchorY:m,root:p,children:n}),b.jsx(Wl.Provider,{value:E,children:n})};function wA(){return new Map}function dw(n=!0){const e=P.useContext(Wl);if(e===null)return[!0,null];const{isPresent:s,onExitComplete:a,register:l}=e,u=P.useId();P.useEffect(()=>{if(n)return l(u)},[n]);const c=P.useCallback(()=>n&&a&&a(u),[u,a,n]);return!s&&a?[!1,c]:[!0]}const fl=n=>n.key||"";function N0(n){const e=[];return P.Children.forEach(n,s=>{P.isValidElement(s)&&e.push(s)}),e}const as=({children:n,custom:e,initial:s=!0,onExitComplete:a,presenceAffectsLayout:l=!0,mode:u="sync",propagate:c=!1,anchorX:d="left",anchorY:m="top",root:p})=>{const[g,v]=dw(c),w=P.useMemo(()=>N0(n),[n]),_=c&&!g?[]:w.map(fl),S=P.useRef(!0),E=P.useRef(w),k=Hd(()=>new Map),C=P.useRef(new Set),[N,O]=P.useState(w),[z,F]=P.useState(w);$d(()=>{S.current=!1,E.current=w;for(let Y=0;Y{const Z=fl(Y),te=c&&!g?!1:w===z||_.includes(Z),de=()=>{if(C.current.has(Z))return;if(k.has(Z))C.current.add(Z),k.set(Z,!0);else return;let fe=!0;k.forEach(qe=>{qe||(fe=!1)}),fe&&(G==null||G(),F(E.current),c&&(v==null||v()),a&&a())};return b.jsx(bA,{isPresent:te,initial:!S.current||s?void 0:!1,custom:e,presenceAffectsLayout:l,mode:u,root:p,onExitComplete:te?void 0:de,anchorX:d,anchorY:m,children:Y},Z)})})},fw=P.createContext({strict:!1}),D0={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let M0=!1;function xA(){if(M0)return;const n={};for(const e in D0)n[e]={isEnabled:s=>D0[e].some(a=>!!s[a])};qb(n),M0=!0}function mw(){return xA(),aE()}function _A(n){const e=mw();for(const s in n)e[s]={...e[s],...n[s]};qb(e)}const SA=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","propagate","ignoreStrict","viewport"]);function Gl(n){return n.startsWith("while")||n.startsWith("drag")&&n!=="draggable"||n.startsWith("layout")||n.startsWith("onTap")||n.startsWith("onPan")||n.startsWith("onLayout")||SA.has(n)}let pw=n=>!Gl(n);function TA(n){typeof n=="function"&&(pw=e=>e.startsWith("on")?!Gl(e):n(e))}try{TA(require("@emotion/is-prop-valid").default)}catch{}function EA(n,e,s){const a={};for(const l in n)l==="values"&&typeof n.values=="object"||vt(n[l])||(pw(l)||s===!0&&Gl(l)||!e&&!Gl(l)||n.draggable&&l.startsWith("onDrag"))&&(a[l]=n[l]);return a}const iu=P.createContext({});function AA(n,e){if(nu(n)){const{initial:s,animate:a}=n;return{initial:s===!1||Cr(s)?s:void 0,animate:Cr(a)?a:void 0}}return n.inherit!==!1?e:{}}function RA(n){const{initial:e,animate:s}=AA(n,P.useContext(iu));return P.useMemo(()=>({initial:e,animate:s}),[U0(e),U0(s)])}function U0(n){return Array.isArray(n)?n.join(" "):n}const pf=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function gw(n,e,s){for(const a in e)!vt(e[a])&&!Jb(a,s)&&(n[a]=e[a])}function CA({transformTemplate:n},e){return P.useMemo(()=>{const s=pf();return df(s,e,n),Object.assign({},s.vars,s.style)},[e])}function kA(n,e){const s=n.style||{},a={};return gw(a,s,n),Object.assign(a,CA(n,e)),a}function jA(n,e){const s={},a=kA(n,e);return n.drag&&n.dragListener!==!1&&(s.draggable=!1,a.userSelect=a.WebkitUserSelect=a.WebkitTouchCallout="none",a.touchAction=n.drag===!0?"none":`pan-${n.drag==="x"?"y":"x"}`),n.tabIndex===void 0&&(n.onTap||n.onTapStart||n.whileTap)&&(s.tabIndex=0),s.style=a,s}const yw=()=>({...pf(),attrs:{}});function OA(n,e,s,a){const l=P.useMemo(()=>{const u=yw();return Qb(u,e,Wb(a),n.transformTemplate,n.style),{...u.attrs,style:{...u.style}}},[e]);if(n.style){const u={};gw(u,n.style,n),l.style={...u,...l.style}}return l}const NA=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function gf(n){return typeof n!="string"||n.includes("-")?!1:!!(NA.indexOf(n)>-1||/[A-Z]/u.test(n))}function DA(n,e,s,{latestValues:a},l,u=!1,c){const m=(c??gf(n)?OA:jA)(e,a,l,n),p=EA(e,typeof n=="string",u),g=n!==P.Fragment?{...p,...m,ref:s}:{},{children:v}=e,w=P.useMemo(()=>vt(v)?v.get():v,[v]);return P.createElement(n,{...g,children:w})}function MA({scrapeMotionValuesFromProps:n,createRenderState:e},s,a,l){return{latestValues:UA(s,a,l,n),renderState:e()}}function UA(n,e,s,a){const l={},u=a(n,{});for(const w in u)l[w]=Ol(u[w]);let{initial:c,animate:d}=n;const m=nu(n),p=Hb(n);e&&p&&!m&&n.inherit!==!1&&(c===void 0&&(c=e.initial),d===void 0&&(d=e.animate));let g=s?s.initial===!1:!1;g=g||c===!1;const v=g?d:c;if(v&&typeof v!="boolean"&&!tu(v)){const w=Array.isArray(v)?v:[v];for(let _=0;_(e,s)=>{const a=P.useContext(iu),l=P.useContext(Wl),u=()=>MA(n,e,a,l);return s?u():Hd(u)},BA=vw({scrapeMotionValuesFromProps:ff,createRenderState:pf}),LA=vw({scrapeMotionValuesFromProps:ew,createRenderState:yw}),zA=Symbol.for("motionComponentSymbol");function VA(n,e,s){const a=P.useRef(s);P.useInsertionEffect(()=>{a.current=s});const l=P.useRef(null);return P.useCallback(u=>{var d;u&&((d=n.onMount)==null||d.call(n,u)),e&&(u?e.mount(u):e.unmount());const c=a.current;if(typeof c=="function")if(u){const m=c(u);typeof m=="function"&&(l.current=m)}else l.current?(l.current(),l.current=null):c(u);else c&&(c.current=u)},[e])}const bw=P.createContext({});function ea(n){return n&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,"current")}function PA(n,e,s,a,l,u){var O,z;const{visualElement:c}=P.useContext(iu),d=P.useContext(fw),m=P.useContext(Wl),p=P.useContext(mf),g=p.reducedMotion,v=p.skipAnimations,w=P.useRef(null),_=P.useRef(!1);a=a||d.renderer,!w.current&&a&&(w.current=a(n,{visualState:e,parent:c,props:s,presenceContext:m,blockInitialAnimation:m?m.initial===!1:!1,reducedMotionConfig:g,skipAnimations:v,isSVG:u}),_.current&&w.current&&(w.current.manuallyAnimateOnMount=!0));const S=w.current,E=P.useContext(bw);S&&!S.projection&&l&&(S.type==="html"||S.type==="svg")&&HA(w.current,s,l,E);const k=P.useRef(!1);P.useInsertionEffect(()=>{S&&k.current&&S.update(s,m)});const C=s[kb],N=P.useRef(!!C&&typeof window<"u"&&!((O=window.MotionHandoffIsComplete)!=null&&O.call(window,C))&&((z=window.MotionHasOptimisedAnimation)==null?void 0:z.call(window,C)));return $d(()=>{_.current=!0,S&&(k.current=!0,window.MotionIsMounted=!0,S.updateFeatures(),S.scheduleRenderMicrotask(),N.current&&S.animationState&&S.animationState.animateChanges())}),P.useEffect(()=>{S&&(!N.current&&S.animationState&&S.animationState.animateChanges(),N.current&&(queueMicrotask(()=>{var F;(F=window.MotionHandoffMarkAsComplete)==null||F.call(window,C)}),N.current=!1),S.enteringChildren=void 0)}),S}function HA(n,e,s,a){const{layoutId:l,layout:u,drag:c,dragConstraints:d,layoutScroll:m,layoutRoot:p,layoutAnchor:g,layoutCrossfade:v}=e;n.projection=new s(n.latestValues,e["data-framer-portal-id"]?void 0:ww(n.parent)),n.projection.setOptions({layoutId:l,layout:u,alwaysMeasureLayout:!!c||d&&ea(d),visualElement:n,animationType:typeof u=="string"?u:"both",initialPromotionConfig:a,crossfade:v,layoutScroll:m,layoutRoot:p,layoutAnchor:g})}function ww(n){if(n)return n.options.allowProjection!==!1?n.projection:ww(n.parent)}function Lh(n,{forwardMotionProps:e=!1,type:s}={},a,l){a&&_A(a);const u=s?s==="svg":gf(n),c=u?LA:BA;function d(p,g){let v;const w={...P.useContext(mf),...p,layoutId:$A(p)},{isStatic:_}=w,S=RA(p),E=c(p,_);if(!_&&typeof window<"u"){qA();const k=GA(w);v=k.MeasureLayout,S.visualElement=PA(n,E,w,l,k.ProjectionNode,u)}return b.jsxs(iu.Provider,{value:S,children:[v&&S.visualElement?b.jsx(v,{visualElement:S.visualElement,...w}):null,DA(n,p,VA(E,S.visualElement,g),E,_,e,u)]})}d.displayName=`motion.${typeof n=="string"?n:`create(${n.displayName??n.name??""})`}`;const m=P.forwardRef(d);return m[zA]=n,m}function $A({layoutId:n}){const e=P.useContext(Pd).id;return e&&n!==void 0?e+"-"+n:n}function qA(n,e){P.useContext(fw).strict}function GA(n){const e=mw(),{drag:s,layout:a}=e;if(!s&&!a)return{};const l={...s,...a};return{MeasureLayout:s!=null&&s.isEnabled(n)||a!=null&&a.isEnabled(n)?l.MeasureLayout:void 0,ProjectionNode:l.ProjectionNode}}function IA(n,e){if(typeof Proxy>"u")return Lh;const s=new Map,a=(u,c)=>Lh(u,c,n,e),l=(u,c)=>a(u,c);return new Proxy(l,{get:(u,c)=>c==="create"?a:(s.has(c)||s.set(c,Lh(c,void 0,n,e)),s.get(c))})}const KA=(n,e)=>e.isSVG??gf(n)?new _E(e):new gE(e,{allowProjection:n!==P.Fragment});class FA extends Mi{constructor(e){super(e),e.animationState||(e.animationState=RE(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();tu(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:s}=this.node.prevProps||{};e!==s&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let YA=0;class XA extends Mi{constructor(){super(...arguments),this.id=YA++,this.isExitComplete=!1}update(){var u;if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:s}=this.node.presenceContext,{isPresent:a}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===a)return;if(e&&a===!1){if(this.isExitComplete){const{initial:c,custom:d}=this.node.getProps();if(typeof c=="string"||typeof c=="object"&&c!==null&&!Array.isArray(c)){const m=cs(this.node,c,d);if(m){const{transition:p,transitionEnd:g,...v}=m;for(const w in v)(u=this.node.getValue(w))==null||u.jump(v[w])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const l=this.node.animationState.setActive("exit",!e);s&&!e&&l.then(()=>{this.isExitComplete=!0,s(this.id)})}mount(){const{register:e,onExitComplete:s}=this.node.presenceContext||{};s&&s(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const JA={animation:{Feature:FA},exit:{Feature:XA}};function $r(n){return{point:{x:n.pageX,y:n.pageY}}}const QA=n=>e=>lf(e)&&n(e,$r(e));function xr(n,e,s,a){return kr(n,e,QA(s),a)}const xw=({current:n})=>n?n.ownerDocument.defaultView:null,B0=(n,e)=>Math.abs(n-e);function ZA(n,e){const s=B0(n.x,e.x),a=B0(n.y,e.y);return Math.sqrt(s**2+a**2)}const L0=new Set(["auto","scroll"]);class _w{constructor(e,s,{transformPagePoint:a,contextWindow:l=window,dragSnapToOrigin:u=!1,distanceThreshold:c=3,element:d}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=S=>{this.handleScroll(S.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=ml(this.lastRawMoveEventInfo,this.transformPagePoint));const S=zh(this.lastMoveEventInfo,this.history),E=this.startEvent!==null,k=ZA(S.offset,{x:0,y:0})>=this.distanceThreshold;if(!E&&!k)return;const{point:C}=S,{timestamp:N}=yt;this.history.push({...C,timestamp:N});const{onStart:O,onMove:z}=this.handlers;E||(O&&O(this.lastMoveEvent,S),this.startEvent=this.lastMoveEvent),z&&z(this.lastMoveEvent,S)},this.handlePointerMove=(S,E)=>{this.lastMoveEvent=S,this.lastRawMoveEventInfo=E,this.lastMoveEventInfo=ml(E,this.transformPagePoint),Ve.update(this.updatePoint,!0)},this.handlePointerUp=(S,E)=>{this.end();const{onEnd:k,onSessionEnd:C,resumeAnimation:N}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&N&&N(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const O=zh(S.type==="pointercancel"?this.lastMoveEventInfo:ml(E,this.transformPagePoint),this.history);this.startEvent&&k&&k(S,O),C&&C(S,O)},!lf(e))return;this.dragSnapToOrigin=u,this.handlers=s,this.transformPagePoint=a,this.distanceThreshold=c,this.contextWindow=l||window;const m=$r(e),p=ml(m,this.transformPagePoint),{point:g}=p,{timestamp:v}=yt;this.history=[{...g,timestamp:v}];const{onSessionStart:w}=s;w&&w(e,zh(p,this.history));const _={passive:!0,capture:!0};this.removeListeners=Vr(xr(this.contextWindow,"pointermove",this.handlePointerMove,_),xr(this.contextWindow,"pointerup",this.handlePointerUp,_),xr(this.contextWindow,"pointercancel",this.handlePointerUp,_)),d&&this.startScrollTracking(d)}startScrollTracking(e){let s=e.parentElement;for(;s;){const a=getComputedStyle(s);(L0.has(a.overflowX)||L0.has(a.overflowY))&&this.scrollPositions.set(s,{x:s.scrollLeft,y:s.scrollTop}),s=s.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(e){const s=this.scrollPositions.get(e);if(!s)return;const a=e===window,l=a?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},u={x:l.x-s.x,y:l.y-s.y};u.x===0&&u.y===0||(a?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=u.x,this.lastMoveEventInfo.point.y+=u.y):this.history.length>0&&(this.history[0].x-=u.x,this.history[0].y-=u.y),this.scrollPositions.set(e,l),Ve.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Di(this.updatePoint)}}function ml(n,e){return e?{point:e(n.point)}:n}function z0(n,e){return{x:n.x-e.x,y:n.y-e.y}}function zh({point:n},e){return{point:n,delta:z0(n,Sw(e)),offset:z0(n,WA(e)),velocity:e2(e,.1)}}function WA(n){return n[0]}function Sw(n){return n[n.length-1]}function e2(n,e){if(n.length<2)return{x:0,y:0};let s=n.length-1,a=null;const l=Sw(n);for(;s>=0&&(a=n[s],!(l.timestamp-a.timestamp>Gt(e)));)s--;if(!a)return{x:0,y:0};a===n[0]&&n.length>2&&l.timestamp-a.timestamp>Gt(e)*2&&(a=n[1]);const u=nn(l.timestamp-a.timestamp);if(u===0)return{x:0,y:0};const c={x:(l.x-a.x)/u,y:(l.y-a.y)/u};return c.x===1/0&&(c.x=0),c.y===1/0&&(c.y=0),c}function t2(n,{min:e,max:s},a){return e!==void 0&&ns&&(n=a?ze(s,n,a.max):Math.min(n,s)),n}function V0(n,e,s){return{min:e!==void 0?n.min+e:void 0,max:s!==void 0?n.max+s-(n.max-n.min):void 0}}function n2(n,{top:e,left:s,bottom:a,right:l}){return{x:V0(n.x,s,l),y:V0(n.y,e,a)}}function P0(n,e){let s=e.min-n.min,a=e.max-n.max;return e.max-e.mina?s=Ar(e.min,e.max-a,n.min):a>l&&(s=Ar(n.min,n.max-l,e.min)),Cn(0,1,s)}function a2(n,e){const s={};return e.min!==void 0&&(s.min=e.min-n.min),e.max!==void 0&&(s.max=e.max-n.min),s}const Sd=.35;function r2(n=Sd){return n===!1?n=0:n===!0&&(n=Sd),{x:H0(n,"left","right"),y:H0(n,"top","bottom")}}function H0(n,e,s){return{min:$0(n,e),max:$0(n,s)}}function $0(n,e){return typeof n=="number"?n:n[e]||0}const o2=new WeakMap;class l2{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ot(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:s=!1,distanceThreshold:a}={}){const{presenceContext:l}=this.visualElement;if(l&&l.isPresent===!1)return;const u=v=>{s&&this.snapToCursor($r(v).point),this.stopAnimation()},c=(v,w)=>{const{drag:_,dragPropagation:S,onDragStart:E}=this.getProps();if(_&&!S&&(this.openDragLock&&this.openDragLock(),this.openDragLock=UT(_),!this.openDragLock))return;this.latestPointerEvent=v,this.latestPanInfo=w,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Sn(C=>{let N=this.getAxisMotionValue(C).get()||0;if(Rn.test(N)){const{projection:O}=this.visualElement;if(O&&O.layout){const z=O.layout.layoutBox[C];z&&(N=St(z)*(parseFloat(N)/100))}}this.originPoint[C]=N}),E&&Ve.update(()=>E(v,w),!1,!0),fd(this.visualElement,"transform");const{animationState:k}=this.visualElement;k&&k.setActive("whileDrag",!0)},d=(v,w)=>{this.latestPointerEvent=v,this.latestPanInfo=w;const{dragPropagation:_,dragDirectionLock:S,onDirectionLock:E,onDrag:k}=this.getProps();if(!_&&!this.openDragLock)return;const{offset:C}=w;if(S&&this.currentDirection===null){this.currentDirection=c2(C),this.currentDirection!==null&&E&&E(this.currentDirection);return}this.updateAxis("x",w.point,C),this.updateAxis("y",w.point,C),this.visualElement.render(),k&&Ve.update(()=>k(v,w),!1,!0)},m=(v,w)=>{this.latestPointerEvent=v,this.latestPanInfo=w,this.stop(v,w),this.latestPointerEvent=null,this.latestPanInfo=null},p=()=>{const{dragSnapToOrigin:v}=this.getProps();(v||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:g}=this.getProps();this.panSession=new _w(e,{onSessionStart:u,onStart:c,onMove:d,onSessionEnd:m,resumeAnimation:p},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:g,distanceThreshold:a,contextWindow:xw(this.visualElement),element:this.visualElement.current})}stop(e,s){const a=e||this.latestPointerEvent,l=s||this.latestPanInfo,u=this.isDragging;if(this.cancel(),!u||!l||!a)return;const{velocity:c}=l;this.startAnimation(c);const{onDragEnd:d}=this.getProps();d&&Ve.postRender(()=>d(a,l))}cancel(){this.isDragging=!1;const{projection:e,animationState:s}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:a}=this.getProps();!a&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),s&&s.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,s,a){const{drag:l}=this.getProps();if(!a||!pl(e,l,this.currentDirection))return;const u=this.getAxisMotionValue(e);let c=this.originPoint[e]+a[e];this.constraints&&this.constraints[e]&&(c=t2(c,this.constraints[e],this.elastic[e])),u.set(c)}resolveConstraints(){var u;const{dragConstraints:e,dragElastic:s}=this.getProps(),a=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(u=this.visualElement.projection)==null?void 0:u.layout,l=this.constraints;e&&ea(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&a?this.constraints=n2(a.layoutBox,e):this.constraints=!1,this.elastic=r2(s),l!==this.constraints&&!ea(e)&&a&&this.constraints&&!this.hasMutatedConstraints&&Sn(c=>{this.constraints!==!1&&this.getAxisMotionValue(c)&&(this.constraints[c]=a2(a.layoutBox[c],this.constraints[c]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:s}=this.getProps();if(!e||!ea(e))return!1;const a=e.current,{projection:l}=this.visualElement;if(!l||!l.layout)return!1;l.root&&(l.root.scroll=void 0,l.root.updateScroll());const u=cE(a,l.root,this.visualElement.getTransformPagePoint());let c=i2(l.layout.layoutBox,u);if(s){const d=s(oE(c));this.hasMutatedConstraints=!!d,d&&(c=Ib(d))}return c}startAnimation(e){const{drag:s,dragMomentum:a,dragElastic:l,dragTransition:u,dragSnapToOrigin:c,onDragTransitionEnd:d}=this.getProps(),m=this.constraints||{},p=Sn(g=>{if(!pl(g,s,this.currentDirection))return;let v=m&&m[g]||{};(c===!0||c===g)&&(v={min:0,max:0});const w=l?200:1e6,_=l?40:1e7,S={type:"inertia",velocity:a?e[g]:0,bounceStiffness:w,bounceDamping:_,timeConstant:750,restDelta:1,restSpeed:10,...u,...v};return this.startAxisValueAnimation(g,S)});return Promise.all(p).then(d)}startAxisValueAnimation(e,s){const a=this.getAxisMotionValue(e);return fd(this.visualElement,e),a.start(nf(e,a,0,s,this.visualElement,!1))}stopAnimation(){Sn(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){const s=`_drag${e.toUpperCase()}`,l=this.visualElement.getProps()[s];return l||this.visualElement.getValue(e,this.visualElement.latestValues[e]??0)}snapToCursor(e){Sn(s=>{const{drag:a}=this.getProps();if(!pl(s,a,this.currentDirection))return;const{projection:l}=this.visualElement,u=this.getAxisMotionValue(s);if(l&&l.layout){const{min:c,max:d}=l.layout.layoutBox[s],m=u.get()||0;u.set(e[s]-ze(c,d,.5)+m)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:s}=this.getProps(),{projection:a}=this.visualElement;if(!ea(s)||!a||!this.constraints)return;this.stopAnimation();const l={x:0,y:0};Sn(c=>{const d=this.getAxisMotionValue(c);if(d&&this.constraints!==!1){const m=d.get();l[c]=s2({min:m,max:m},this.constraints[c])}});const{transformTemplate:u}=this.visualElement.getProps();this.visualElement.current.style.transform=u?u({},""):"none",a.root&&a.root.updateScroll(),a.updateLayout(),this.constraints=!1,this.resolveConstraints(),Sn(c=>{if(!pl(c,e,null))return;const d=this.getAxisMotionValue(c),{min:m,max:p}=this.constraints[c];d.set(ze(m,p,l[c]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;o2.set(this.visualElement,this);const e=this.visualElement.current,s=xr(e,"pointerdown",p=>{const{drag:g,dragListener:v=!0}=this.getProps(),w=p.target,_=w!==e&&HT(w);g&&v&&!_&&this.start(p)});let a;const l=()=>{const{dragConstraints:p}=this.getProps();ea(p)&&p.current&&(this.constraints=this.resolveRefConstraints(),a||(a=u2(e,p.current,()=>this.scalePositionWithinConstraints())))},{projection:u}=this.visualElement,c=u.addEventListener("measure",l);u&&!u.layout&&(u.root&&u.root.updateScroll(),u.updateLayout()),Ve.read(l);const d=kr(window,"resize",()=>this.scalePositionWithinConstraints()),m=u.addEventListener("didUpdate",(({delta:p,hasLayoutChanged:g})=>{this.isDragging&&g&&(Sn(v=>{const w=this.getAxisMotionValue(v);w&&(this.originPoint[v]+=p[v].translate,w.set(w.get()+p[v].translate))}),this.visualElement.render())}));return()=>{d(),s(),c(),m&&m(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:s=!1,dragDirectionLock:a=!1,dragPropagation:l=!1,dragConstraints:u=!1,dragElastic:c=Sd,dragMomentum:d=!0}=e;return{...e,drag:s,dragDirectionLock:a,dragPropagation:l,dragConstraints:u,dragElastic:c,dragMomentum:d}}}function q0(n){let e=!0;return()=>{if(e){e=!1;return}n()}}function u2(n,e,s){const a=Jy(n,q0(s)),l=Jy(e,q0(s));return()=>{a(),l()}}function pl(n,e,s){return(e===!0||e===n)&&(s===null||s===n)}function c2(n,e=10){let s=null;return Math.abs(n.y)>e?s="y":Math.abs(n.x)>e&&(s="x"),s}class h2 extends Mi{constructor(e){super(e),this.removeGroupControls=sn,this.removeListeners=sn,this.controls=new l2(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||sn}update(){const{dragControls:e}=this.node.getProps(),{dragControls:s}=this.node.prevProps||{};e!==s&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const Vh=n=>(e,s)=>{n&&Ve.update(()=>n(e,s),!1,!0)};class d2 extends Mi{constructor(){super(...arguments),this.removePointerDownListener=sn}onPointerDown(e){this.session=new _w(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:xw(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:s,onPan:a,onPanEnd:l}=this.node.getProps();return{onSessionStart:Vh(e),onStart:Vh(s),onMove:Vh(a),onEnd:(u,c)=>{delete this.session,l&&Ve.postRender(()=>l(u,c))}}}mount(){this.removePointerDownListener=xr(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let Ph=!1;class f2 extends P.Component{componentDidMount(){const{visualElement:e,layoutGroup:s,switchLayoutGroup:a,layoutId:l}=this.props,{projection:u}=e;u&&(s.group&&s.group.add(u),a&&a.register&&l&&a.register(u),Ph&&u.root.didUpdate(),u.addEventListener("animationComplete",()=>{this.safeToRemove()}),u.setOptions({...u.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Nl.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:s,visualElement:a,drag:l,isPresent:u}=this.props,{projection:c}=a;return c&&(c.isPresent=u,e.layoutDependency!==s&&c.setOptions({...c.options,layoutDependency:s}),Ph=!0,l||e.layoutDependency!==s||s===void 0||e.isPresent!==u?c.willUpdate():this.safeToRemove(),e.isPresent!==u&&(u?c.promote():c.relegate()||Ve.postRender(()=>{const d=c.getStack();(!d||!d.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:e,layoutAnchor:s}=this.props,{projection:a}=e;a&&(a.options.layoutAnchor=s,a.root.didUpdate(),of.postRender(()=>{!a.currentAnimation&&a.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:s,switchLayoutGroup:a}=this.props,{projection:l}=e;Ph=!0,l&&(l.scheduleCheckAfterUnmount(),s&&s.group&&s.group.remove(l),a&&a.deregister&&a.deregister(l))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function Tw(n){const[e,s]=dw(),a=P.useContext(Pd);return b.jsx(f2,{...n,layoutGroup:a,switchLayoutGroup:P.useContext(bw),isPresent:e,safeToRemove:s})}const m2={pan:{Feature:d2},drag:{Feature:h2,ProjectionNode:hw,MeasureLayout:Tw}};function G0(n,e,s){const{props:a}=n;n.animationState&&a.whileHover&&n.animationState.setActive("whileHover",s==="Start");const l="onHover"+s,u=a[l];u&&Ve.postRender(()=>u(e,$r(e)))}class p2 extends Mi{mount(){const{current:e}=this.node;e&&(this.unmount=LT(e,(s,a)=>(G0(this.node,a,"Start"),l=>G0(this.node,l,"End"))))}unmount(){}}class g2 extends Mi{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Vr(kr(this.node.current,"focus",()=>this.onFocus()),kr(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function I0(n,e,s){const{props:a}=n;if(n.current instanceof HTMLButtonElement&&n.current.disabled)return;n.animationState&&a.whileTap&&n.animationState.setActive("whileTap",s==="Start");const l="onTap"+(s==="End"?"":s),u=a[l];u&&Ve.postRender(()=>u(e,$r(e)))}class y2 extends Mi{mount(){const{current:e}=this.node;if(!e)return;const{globalTapTarget:s,propagate:a}=this.node.props;this.unmount=qT(e,(l,u)=>(I0(this.node,u,"Start"),(c,{success:d})=>I0(this.node,c,d?"End":"Cancel")),{useGlobalTarget:s,stopPropagation:(a==null?void 0:a.tap)===!1})}unmount(){}}const Td=new WeakMap,Hh=new WeakMap,v2=n=>{const e=Td.get(n.target);e&&e(n)},b2=n=>{n.forEach(v2)};function w2({root:n,...e}){const s=n||document;Hh.has(s)||Hh.set(s,{});const a=Hh.get(s),l=JSON.stringify(e);return a[l]||(a[l]=new IntersectionObserver(b2,{root:n,...e})),a[l]}function x2(n,e,s){const a=w2(e);return Td.set(n,s),a.observe(n),()=>{Td.delete(n),a.unobserve(n)}}const _2={some:0,all:1};class S2 extends Mi{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){var m;(m=this.stopObserver)==null||m.call(this);const{viewport:e={}}=this.node.getProps(),{root:s,margin:a,amount:l="some",once:u}=e,c={root:s?s.current:void 0,rootMargin:a,threshold:typeof l=="number"?l:_2[l]},d=p=>{const{isIntersecting:g}=p;if(this.isInView===g||(this.isInView=g,u&&!g&&this.hasEnteredView))return;g&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",g);const{onViewportEnter:v,onViewportLeave:w}=this.node.getProps(),_=g?v:w;_&&_(p)};this.stopObserver=x2(this.node.current,c,d)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:s}=this.node;["amount","margin","root"].some(T2(e,s))&&this.startObserver()}unmount(){var e;(e=this.stopObserver)==null||e.call(this),this.hasEnteredView=!1,this.isInView=!1}}function T2({viewport:n={}},{viewport:e={}}={}){return s=>n[s]!==e[s]}const E2={inView:{Feature:S2},tap:{Feature:y2},focus:{Feature:g2},hover:{Feature:p2}},A2={layout:{ProjectionNode:hw,MeasureLayout:Tw}},R2={...JA,...E2,...m2,...A2},C2=IA(R2,KA),mn=C2;/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k2=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),j2=n=>n.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,s,a)=>a?a.toUpperCase():s.toLowerCase()),K0=n=>{const e=j2(n);return e.charAt(0).toUpperCase()+e.slice(1)},Ew=(...n)=>n.filter((e,s,a)=>!!e&&e.trim()!==""&&a.indexOf(e)===s).join(" ").trim(),O2=n=>{for(const e in n)if(e.startsWith("aria-")||e==="role"||e==="title")return!0};/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */var N2={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const D2=P.forwardRef(({color:n="currentColor",size:e=24,strokeWidth:s=2,absoluteStrokeWidth:a,className:l="",children:u,iconNode:c,...d},m)=>P.createElement("svg",{ref:m,...N2,width:e,height:e,stroke:n,strokeWidth:a?Number(s)*24/Number(e):s,className:Ew("lucide",l),...!u&&!O2(d)&&{"aria-hidden":"true"},...d},[...c.map(([p,g])=>P.createElement(p,g)),...Array.isArray(u)?u:[u]]));/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ne=(n,e)=>{const s=P.forwardRef(({className:a,...l},u)=>P.createElement(D2,{ref:u,iconNode:e,className:Ew(`lucide-${k2(K0(n))}`,`lucide-${n}`,a),...l}));return s.displayName=K0(n),s};/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M2=[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]],U2=Ne("arrow-left-right",M2);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const B2=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],L2=Ne("arrow-right",B2);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const z2=[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M6 12h.01M18 12h.01",key:"113zkx"}]],F0=Ne("banknote",z2);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const V2=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]],P2=Ne("calendar-days",V2);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H2=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],$2=Ne("calendar",H2);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q2=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],G2=Ne("chevron-down",q2);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I2=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],K2=Ne("circle-alert",I2);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const F2=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],yf=Ne("circle-check",F2);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Y2=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]],X2=Ne("circle-user",Y2);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const J2=[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Aw=Ne("earth",J2);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Q2=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Z2=Ne("external-link",Q2);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W2=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],eR=Ne("eye",W2);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tR=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]],Dl=Ne("file-spreadsheet",tR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nR=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],$h=Ne("file-text",nR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iR=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],sR=Ne("funnel",iR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aR=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],rR=Ne("history",aR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oR=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Rw=Ne("info",oR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lR=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Ed=Ne("loader-circle",lR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uR=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],cR=Ne("lock-keyhole",uR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hR=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],dR=Ne("log-out",hR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fR=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Cw=Ne("menu",fR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mR=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],pR=Ne("play",mR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gR=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],yR=Ne("plus",gR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vR=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],bR=Ne("refresh-cw",vR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wR=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],kw=Ne("search",wR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xR=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Y0=Ne("trash-2",xR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _R=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],vf=Ne("triangle-alert",_R);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SR=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],X0=Ne("upload",SR);/** * @license lucide-react v0.546.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TR=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],bf=Ne("x",TR),jr=[{code:"GT",name:"Guatemala",flag:"/cruce-cuentas/gt-flag.png",currency:"GTQ",locale:"es-GT",enabled:!0},{code:"TT",name:"Trinidad y Tobago",flag:"/cruce-cuentas/tt-flag.png",currency:"TTD",locale:"en-TT",enabled:!1}];function J0(n){return jr.find(e=>e.code===n)??jr[0]}const ER="https://dbit.digitalcompass.agency/storage/v1/object/public/public-assets/GLM_completo.png";function AR({currentView:n,onViewChange:e,onNewCruce:s,isSidebarOpen:a=!1,onCloseSidebar:l,user:u,isAuthEnabled:c=!1,onLogout:d,country:m,onCountryChange:p,onChooseAnotherCountry:g}){const[v,w]=P.useState(!1),_=P.useRef(null);return P.useEffect(()=>{function S(E){_.current&&!_.current.contains(E.target)&&w(!1)}return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]),b.jsxs("aside",{className:`bg-neutral-100 h-screen w-64 fixed left-0 top-0 flex flex-col z-50 pb-6 min-h-screen font-sans transition-transform duration-300 md:translate-x-0 ${a?"translate-x-0":"-translate-x-full"}`,children:[b.jsx("div",{className:"absolute right-0 top-0 h-[80px] w-px bg-[#D0D0D0] pointer-events-none z-10 hidden md:block"}),b.jsx("div",{className:"absolute right-0 top-[84px] bottom-0 w-px bg-[#D0D0D0] pointer-events-none z-10 hidden md:block"}),b.jsxs("div",{className:"h-[84px] px-4 flex justify-between md:justify-center items-center bg-white border-b-4 border-[#6CC24A] relative",children:[b.jsx("img",{alt:"GomezLee Marketing logo",className:"h-10 object-contain selection:bg-transparent",src:ER}),b.jsx("button",{onClick:l,className:"md:hidden p-2 text-neutral-500 hover:text-neutral-800 transition-colors","aria-label":"Cerrar menú",children:b.jsx(bf,{className:"w-5 h-5"})})]}),b.jsxs("div",{className:"px-4 pt-5",children:[b.jsxs("label",{className:"block",children:[b.jsxs("span",{className:"text-[9px] uppercase tracking-wider font-black text-neutral-400 flex items-center gap-1.5 mb-1.5",children:[b.jsx(Aw,{className:"w-3.5 h-3.5"}),"País"]}),b.jsxs("div",{className:"relative",ref:_,children:[b.jsxs("button",{type:"button",onClick:()=>w(!v),className:"w-full border border-neutral-300 bg-white px-3 py-2 text-xs font-bold text-[#4F758B] focus:outline-none focus:border-[#4F758B] flex items-center justify-between transition-colors hover:bg-neutral-50",children:[b.jsxs("div",{className:"flex items-center gap-2",children:[b.jsx("img",{src:m.flag,alt:"",className:"w-5 h-3.5 object-cover shadow-sm border border-neutral-200"}),b.jsx("span",{children:m.name})]}),b.jsx(G2,{className:`w-4 h-4 text-[#4F758B] transition-transform ${v?"rotate-180":""}`})]}),v&&b.jsx("ul",{className:"absolute left-0 right-0 top-full mt-1 bg-white border border-neutral-300 shadow-lg z-50 py-1",children:jr.map(S=>b.jsx("li",{children:b.jsxs("button",{type:"button",disabled:!S.enabled,onClick:()=>{p(S.code),w(!1)},className:`w-full text-left px-3 py-2.5 text-xs font-bold flex items-center gap-2.5 transition-colors ${S.enabled?"hover:bg-neutral-100 text-[#4F758B]":"opacity-60 cursor-not-allowed text-neutral-500 bg-neutral-50"}`,children:[b.jsx("img",{src:S.flag,alt:"",className:"w-6 h-4 object-cover shadow-sm border border-neutral-200 bg-white flex-shrink-0"}),b.jsxs("span",{className:"min-w-0 text-left leading-tight",children:[b.jsx("span",{className:"block",children:S.name}),!S.enabled&&b.jsx("span",{className:"block mt-1 text-[10px] text-neutral-400 font-medium italic",children:"Próximamente"})]})]})},S.code))})]})]}),b.jsx("button",{type:"button",onClick:g,className:"mt-2 text-[9px] font-bold uppercase tracking-wider text-neutral-400 hover:text-[#4F758B]",children:"Ver países disponibles"})]}),b.jsx("nav",{className:"flex-1 flex flex-col mt-5",children:b.jsxs("ul",{className:"space-y-1",children:[b.jsx("li",{children:b.jsxs("button",{onClick:()=>e("cruce"),className:`w-full flex items-center gap-3 px-6 py-3.5 transition-all duration-150 text-left font-bold text-sm tracking-wide ${n==="cruce"?"bg-[#4F758B] text-white":"text-neutral-600 hover:bg-neutral-200 hover:text-neutral-800"}`,children:[b.jsx(U2,{className:`w-4 h-4 ${n==="cruce"?"text-[#6CC24A]":""}`}),b.jsx("span",{children:"Cruce de Cuentas"})]})}),b.jsx("li",{children:b.jsxs("button",{onClick:()=>e("historial"),className:`w-full flex items-center gap-3 px-6 py-3.5 transition-all duration-150 text-left font-bold text-sm tracking-wide ${n==="historial"?"bg-[#4F758B] text-white":"text-neutral-600 hover:bg-neutral-200 hover:text-neutral-800"}`,children:[b.jsx(rR,{className:`w-4 h-4 ${n==="historial"?"text-[#6CC24A]":""}`}),b.jsx("span",{children:"Reportes Históricos"})]})})]})}),b.jsxs("div",{className:"px-4 space-y-3 pt-4 border-t border-[#D0D0D0] bg-neutral-100",children:[u&&b.jsxs("div",{className:"border border-neutral-200 bg-white px-3 py-3 flex items-center gap-2",children:[b.jsx(X2,{className:"w-4 h-4 text-[#4F758B] flex-shrink-0"}),b.jsxs("div",{className:"min-w-0",children:[b.jsx("p",{className:"text-[11px] font-black text-neutral-700 truncate",title:u.name,children:u.name}),b.jsx("p",{className:"text-[9px] text-neutral-400 truncate",title:u.email,children:u.email})]})]}),b.jsxs("button",{onClick:s,className:"w-full bg-[#6CC24A] hover:bg-[#5bb03c] text-white py-3 px-4 font-bold text-xs uppercase tracking-wider flex items-center justify-center gap-2 transition-all duration-150 shadow-sm active:scale-98",children:[b.jsx(yR,{className:"w-4 h-4"}),b.jsx("span",{children:"Nuevo Cruce"})]}),c&&d&&b.jsxs("button",{onClick:d,className:"w-full border border-neutral-300 bg-white hover:bg-neutral-50 text-neutral-600 py-2.5 px-4 font-bold text-[11px] uppercase tracking-wider flex items-center justify-center gap-2 transition-all duration-150",children:[b.jsx(dR,{className:"w-4 h-4"}),b.jsx("span",{children:"Cerrar sesión"})]})]})]})}const jw=[{value:1,label:"Enero"},{value:2,label:"Febrero"},{value:3,label:"Marzo"},{value:4,label:"Abril"},{value:5,label:"Mayo"},{value:6,label:"Junio"},{value:7,label:"Julio"},{value:8,label:"Agosto"},{value:9,label:"Septiembre"},{value:10,label:"Octubre"},{value:11,label:"Noviembre"},{value:12,label:"Diciembre"}],Q0=[{value:"quincena_15",label:"Quincena 15",description:"Del día 1 al 15 del mes."},{value:"quincena_30",label:"Quincena 30 / fin de mes",description:"Del día 16 al último día del mes."}],RR="https://agenteit.digitalcompass.agency/webhook/cruce-cuentas-analizar-nomina";function CR(n){return n==="TT"?"":"https://agenteit.digitalcompass.agency/webhook/nominagt-bamboo-test"}function kR(){const n=new Date().getFullYear(),e=n-5,s=n+10;return Array.from({length:s-e+1},(a,l)=>e+l)}function jR(){const n=new Date,e=n.getDate();let s=n.getFullYear(),a=n.getMonth()+1,l="quincena_15";return e<=15&&(a-=1,l="quincena_30",a===0&&(a=12,s-=1)),{year:s,month:a,periodType:l}}function Ow(n){return n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(2)} MB`}function Z0(n){const e=n.name.toLowerCase();return e.endsWith(".xlsx")||e.endsWith(".xls")}function W0(n){return n.name.toLowerCase().endsWith(".csv")}function ev(n){return Array.from(n).map(e=>({name:e.name,size:Ow(e.size),type:"bank",rawFile:e}))}function gl(n,e,s){return`${n}-${String(e).padStart(2,"0")}-${String(s).padStart(2,"0")}`}function tv(n,e,s){var u;const a=new Date(n,e,0).getDate(),l=((u=jw.find(c=>c.value===e))==null?void 0:u.label)??"Mes";return s==="quincena_15"?{start:gl(n,e,1),end:gl(n,e,15),label:`${l} ${n} · Quincena 15`}:{start:gl(n,e,16),end:gl(n,e,a),label:`${l} ${n} · Quincena 30 / fin de mes`}}function qh(n,e){return n==null||Number.isNaN(n)?"—":new Intl.NumberFormat(e.locale,{style:"currency",currency:e.currency,minimumFractionDigits:2}).format(n)}function _n(n,e=0){const s=Number(n);return Number.isFinite(s)?s:e}function Tt(n){return n.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function OR(n,e){const s=Tt(String(n??e??""));return s.includes("coincid")?"Coincidencia":s.includes("resuelto")?"Resuelto":s.includes("no encontrado")?"No encontrado":s.includes("pendiente")?"Pendiente revisión":s.includes("riesgo")||s.includes("discrep")||s.includes("mal digitada")?"Riesgo":e==="coincidencia"?"Coincidencia":e==="posible_cuenta_mal_digitada"||e==="discrepancia"?"Riesgo":"Pendiente revisión"}function Gh(n,e){for(const s of e){if(typeof n[s]=="number")return n[s];if(typeof n[s]=="string"&&n[s]!==""){const a=n[s].replace(/[Q,$\s]/g,"").replace(/,/g,""),l=Number(a);if(Number.isFinite(l))return l}}return null}function nv(n){return Array.isArray(n)?n.map((e,s)=>{const a=e,l=String(a.category??a.categoria??a.tipo??a.source??a.fuente??""),u=Gh(a,["amountPayroll","monto_nomina","payroll_amount","amount_payroll","montoNomina"]),c=Gh(a,["amountBank","monto_banco","bank_amount","amount_bank","montoBanco"]),d=Gh(a,["difference","diferencia","diff"]);return{id:String(a.id??a.employeeNumber??a.employee_number??a.account??a.cuenta??`row-${s+1}`),employee:String(a.employee??a.empleado??a.name??a.nombre??a.employee_name??"Sin nombre"),employeeNumber:String(a.employeeNumber??a.employee_number??a.codigo??""),account:a.account||a.cuenta||a.bank_account?String(a.account??a.cuenta??a.bank_account):void 0,amountPayroll:u,amountBank:c,difference:d??(u!==null&&c!==null?u-c:null),status:OR(a.status??a.estado,l),category:l,observation:String(a.observation??a.observacion??a.note??a.nota??a.comentario??""),source:a.source??a.fuente??l}}):[]}function NR(n){const s=(Array.isArray(n)?n[0]:n)??{},a=s.originalResponse??s.original_response??s.response??s,l=a.summary??a.resumen??s.summary??s.resumen??{},u=nv(a.rows??s.rows??a.resultados??s.resultados??[]),c=nv(a.bankWithoutBamboo??s.bankWithoutBamboo??a.banco_sin_bamboo_rows??s.banco_sin_bamboo_rows??[]).map(C=>({...C,category:C.category||"banco_sin_bamboo",source:"banco_sin_bamboo",status:C.status==="Coincidencia"?"Pendiente revisión":C.status})),d=new Map;[...u,...c].forEach((C,N)=>{const O=C.id||`${C.source??C.category??"row"}-${N}`;d.set(O,C)});const m=Array.from(d.values()),p=_n(l.matches??l.coincidencias,u.filter(C=>C.status==="Coincidencia").length),g=_n(l.discrepancies??l.discrepancias,u.filter(C=>{const N=Tt(String(C.category??C.source??""));return N.includes("discrepancia")||N.includes("posible_cuenta_mal_digitada")}).length),v=_n(l.bankWithoutPayroll??l.bancoSinNomina??l.banco_sin_nomina,u.filter(C=>mr(C,"banco_sin_nomina")).length),w=_n(l.bankWithoutBamboo??l.bancoSinBamboo??l.banco_sin_bamboo,c.length),_=_n(l.payrollWithoutAccount??l.nominaSinCuenta??l.nomina_sin_cuenta),S=_n(l.nameDifferences??l.diferenciasNombreBanco??l.diferencias_nombre_banco,u.filter(C=>Tt(String(C.category??"")).includes("diferencia_nombre_banco")).length),E=_n(l.possibleWrongAccounts??l.posiblesCuentasMalDigitadas??l.posibles_cuentas_mal_digitadas,u.filter(C=>Tt(String(C.category??"")).includes("posible_cuenta_mal_digitada")).length),k=g+v+w+_+S;return{ok:!!(a.ok??s.ok??!0),executionId:a.executionId||a.execution_id||s.executionId||s.execution_id?String(a.executionId??a.execution_id??s.executionId??s.execution_id):void 0,reportUrl:a.reportUrl||a.report_url||s.reportUrl||s.report_url||s.google_sheet_url?String(a.reportUrl??a.report_url??s.reportUrl??s.report_url??s.google_sheet_url):void 0,summary:{matches:p,discrepancies:g,bankWithoutPayroll:v,bankWithoutBamboo:w,payrollWithoutAccount:_,nameDifferences:S,possibleWrongAccounts:E,totalPending:k,totalRows:m.length,totalPayroll:_n(l.totalNomina??l.total_nomina,void 0),totalBank:_n(l.totalBanco??l.total_banco,void 0),totalDifference:_n(l.diferenciaTotal??l.diferencia_total,void 0)},rows:m,message:a.message||s.message?String(a.message??s.message):void 0}}function DR(n){return n==="Coincidencia"?"bg-emerald-50 text-emerald-800 border-emerald-200":n==="Resuelto"?"bg-blue-50 text-blue-800 border-blue-200":n==="No encontrado"?"bg-amber-50 text-amber-800 border-amber-200":n==="Pendiente revisión"?"bg-neutral-100 text-neutral-700 border-neutral-300":"bg-red-50 text-[#ba1a1a] border-red-200"}function iv(n){const e=Tt(String(n.category??n.source??"")),s=Tt(n.observation??"");return n.status==="Coincidencia"||e.includes("coincidencia")?90:e.includes("posible_cuenta_mal_digitada")||s.includes("mal digitada")?1:e.includes("discrepancia")||n.status==="Riesgo"?2:e.includes("banco_sin_bamboo")?3:e.includes("banco_sin_nomina")?4:e.includes("diferencia_nombre_banco")?5:e.includes("nomina_sin_cuenta")?6:n.status==="Pendiente revisión"?7:n.status==="No encontrado"?10:20}function MR(n){return[...n].sort((e,s)=>{const a=iv(e)-iv(s);return a!==0?a:e.employee.localeCompare(s.employee,"es")})}function UR(n){const e=Tt(String(n.category??n.source??""));return e.includes("discrepancia")||e.includes("posible_cuenta_mal_digitada")}function mr(n,e){return n.source===e||Tt(String(n.category??"")).includes(e)}function BR(n){const e=Tt(String(n??""));return e?e.includes("posible_cuenta_mal_digitada")?"Posible cuenta mal digitada":e.includes("banco_sin_bamboo")?"Banco sin Bamboo":e.includes("banco_sin_nomina")?"Banco sin nómina":e.includes("diferencia_nombre_banco")?"Diferencia nombre banco":e.includes("nomina_sin_cuenta")?"Nómina sin cuenta":e.includes("discrepancia")?"Discrepancia":e.includes("coincidencia")?"Coincidencia":String(n).replace(/_/g," "):"—"}function LR(n){const e=n instanceof Error?n.message:"";return e.includes("planillas del banco repetidas")?e:"No se pudo procesar el cruce. Verifica los archivos e intenta nuevamente."}function zR(n){try{return new TextDecoder("windows-1252").decode(n)}catch{return new TextDecoder("utf-8").decode(n)}}function sv(n,e){let s=0,a=!1;for(let l=0;lsv(n,a)>sv(n,s)?a:s)}function av(n,e=Nw(n)){const s=[];let a="",l=!1;for(let u=0;uu.replace(/^\uFEFF/,"").trim())}function VR(n){const e=String(n??"").replace(/\D/g,"");return/^\d{1,20}$/.test(e)?e:null}function PR(n){const e=n.split(/\r?\n/).slice(0,120);for(const s of e.slice(0,25)){const l=Tt(s).match(/(?:consulta\s+(?:del\s+)?)?detalle\s+(?:del\s+)?envio\s+(\d{1,20})/);if(l!=null&&l[1])return l[1]}for(let s=0;sTt(m).trim()).findIndex(m=>m==="numero de envio"||m.includes("numero de envio"));if(!(d<0))for(let m=s+1;ms.length>1).map(([s,a])=>({shipmentNumber:s,fileNames:a}))}const qR={1:["enero","january","jan"],2:["febrero","february","feb"],3:["marzo","march","mar"],4:["abril","april","apr"],5:["mayo","may"],6:["junio","june","jun"],7:["julio","july","jul"],8:["agosto","august","aug"],9:["septiembre","setiembre","september","sep"],10:["octubre","october","oct"],11:["noviembre","november","nov"],12:["diciembre","december","dec"]};function GR(n){const e=Tt(n).replace(/[_\-.()]+/g," ").replace(/\s+/g," ").trim(),s=e.match(/\b(20\d{2})\b/),a=s?Number(s[1]):void 0;let l;for(const[c,d]of Object.entries(qR))if(d.some(m=>new RegExp(`\\b${m}\\b`,"i").test(e))){l=Number(c);break}let u;return/\b(?:1q|q1|quincena\s*15|primera\s+quincena)\b/.test(e)?u="quincena_15":/\b(?:2q|q2|quincena\s*30|segunda\s+quincena|fin\s+de\s+mes)\b/.test(e)?u="quincena_30":/\b15\b/.test(e)?u="quincena_15":/\b(?:30|31)\b/.test(e)&&(u="quincena_30"),{year:a,month:l,periodType:u}}function rv(n){const e=jR();try{const s=window.localStorage.getItem(`glm_cruce_period_${n}`);if(!s)return e;const a=JSON.parse(s);if(Number.isInteger(a.year)&&Number.isInteger(a.month)&&a.month>=1&&a.month<=12&&(a.periodType==="quincena_15"||a.periodType==="quincena_30"))return a}catch{}return e}async function IR(n,e){const s=GR(n);try{const a=await fetch(RR,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify({fileName:n,country:e.code,countryName:e.name})});if(!a.ok)return s;const l=await a.json().catch(()=>null),u=(l==null?void 0:l.detected)??(l==null?void 0:l.result)??(l==null?void 0:l.analysis)??l??{},c=String(u.periodType??u.period_type??""),d=Number(u.year)||s.year,m=Number(u.month)||s.month,p=c==="quincena_15"||c==="quincena_30"?c:s.periodType;return{year:d,month:m,periodType:p,confidence:Number.isFinite(Number(u.confidence))?Number(u.confidence):void 0,requiresManualReview:!!(u.requiresManualReview??u.requires_manual_review??!1),source:String(u.source??"gemini")}}catch{return{...s,source:"local_fallback",requiresManualReview:!(Number.isInteger(s.year)&&Number.isInteger(s.month)&&(s.periodType==="quincena_15"||s.periodType==="quincena_30"))}}}function KR({onShowToast:n,uploadedPayroll:e,setUploadedPayroll:s,uploadedBankFiles:a,setUploadedBankFiles:l,isCruceExecuted:u,setIsCruceExecuted:c,response:d,setResponse:m,onOpenSidebar:p,operatorName:g,operatorEmail:v,resetToken:w=0,country:_}){const S=P.useMemo(()=>rv(_.code),[_.code]),[E,k]=P.useState(!1),[C,N]=P.useState(""),[O,z]=P.useState("todos"),[F,J]=P.useState(S.year),[G,Y]=P.useState(S.month),[Z,te]=P.useState(S.periodType),[de,fe]=P.useState(1),[qe,X]=P.useState(""),ue=`glm_cruce_period_${_.code}`,D=P.useRef(null),I=P.useRef(null),ee=P.useMemo(()=>kR(),[]),re=P.useMemo(()=>tv(F,G,Z),[F,G,Z]),A=P.useMemo(()=>MR((d==null?void 0:d.rows)??[]),[d==null?void 0:d.rows]).filter(K=>{const be=Tt(qe.trim());return Tt(`${K.employee} ${K.employeeNumber} ${K.account??""} ${K.observation} ${K.category??""} ${K.source??""}`).includes(be)?O==="discrepancias"?UR(K):O==="coincidencias"?K.status==="Coincidencia":O==="banco_sin_nomina"?mr(K,"banco_sin_nomina"):O==="banco_sin_bamboo"?mr(K,"banco_sin_bamboo"):O==="diferencia_nombre_banco"?mr(K,"diferencia_nombre_banco"):O==="nomina_sin_cuenta"?mr(K,"nomina_sin_cuenta"):!0:!1}),$=10,Q=Math.max(1,Math.ceil(A.length/$)),ne=A.slice((de-1)*$,de*$);P.useEffect(()=>{de>Q&&fe(Q)},[de,Q]);const ge=P.useMemo(()=>{var K;return((K=Q0.find(be=>be.value===Z))==null?void 0:K.description)??""},[Z]);P.useEffect(()=>{const K=rv(_.code);J(K.year),Y(K.month),te(K.periodType),fe(1),X(""),z("todos")},[_.code]),P.useEffect(()=>{window.localStorage.setItem(ue,JSON.stringify({year:F,month:G,periodType:Z}))},[ue,F,G,Z]),P.useEffect(()=>{X(""),z("todos"),fe(1),N(""),k(!1),D.current&&(D.current.value=""),I.current&&(I.current.value="")},[w]);const pe=()=>{c(!1),m(null),fe(1),X(""),z("todos")},Ae=async K=>{s({name:K.name,size:Ow(K.size),type:"payroll",rawFile:K}),pe();const be=await IR(K.name,_);if(Number.isInteger(be.year)&&Number.isInteger(be.month)&&(be.periodType==="quincena_15"||be.periodType==="quincena_30")){J(be.year),Y(be.month),te(be.periodType);const Dt=tv(be.year,be.month,be.periodType);be.requiresManualReview?n(`Nómina cargada. Período sugerido: ${Dt.label}. Confirma los datos antes de ejecutar.`,"info"):n(`Nómina cargada. Período detectado: ${Dt.label}.`,"success");return}n("Archivo de nómina cargado con éxito.","success")},lt=K=>{K.preventDefault()},Ie=async K=>{K.preventDefault();const be=K.dataTransfer.files[0];be&&(Z0(be)?await Ae(be):n("Formato inválido. Por favor carga un archivo Excel (.xlsx, .xls).","error"))},Ui=K=>{K.preventDefault();const Ke=Array.from(K.dataTransfer.files).filter(W0);if(Ke.length===0){n("Formato inválido. Por favor carga uno o varios archivos CSV (.csv).","error");return}l([...a,...ev(Ke)]),pe(),n(`${Ke.length} planilla(s) del banco cargada(s) con éxito.`,"success")},hs=async K=>{var Ke;const be=(Ke=K.target.files)==null?void 0:Ke[0];be&&(Z0(be)?await Ae(be):n("Formato inválido. Por favor carga un archivo Excel (.xlsx, .xls).","error"))},pa=K=>{const be=K.target.files;if(!be||be.length===0)return;const Ke=Array.from(be).filter(W0);if(Ke.length===0){n("Formato inválido. Por favor carga uno o varios archivos CSV (.csv).","error");return}l([...a,...ev(Ke)]),pe(),n(`${Ke.length} planilla(s) del banco cargada(s) con éxito.`,"success")},Gr=K=>{l(a.filter((be,Ke)=>Ke!==K)),I.current&&(I.current.value=""),pe(),n("Planilla de banco removida.","info")},jn=async()=>{if(!E){if(!F||!G||!Z){n("Debes seleccionar año, mes y tipo de cruce antes de ejecutar.","error");return}if(!(e!=null&&e.rawFile)){n("Debes cargar la nómina antes de ejecutar el cruce.","error");return}if(a.length===0||a.some(K=>!K.rawFile)){n("Debes cargar al menos una planilla del banco antes de ejecutar el cruce.","error");return}k(!0),N("Validando archivos..."),fe(1);try{const K=await $R(a);if(K.length>0){const De=K.map(yn=>`Número de envío ${yn.shipmentNumber}: ${yn.fileNames.join(", ")}`).join(` `);throw new Error(`Hay planillas del banco repetidas. Revisa los archivos cargados antes de continuar. ${De}`)}const be=CR(_.code);if(!be)throw new Error("No se pudo procesar el cruce. El servicio de conciliación no está disponible.");const Ke={country:_.code,country_name:_.name,year:F,month:G,period_type:Z,period_label:re.label,period_start:re.start,period_end:re.end,payroll_file_name:e.name,bank_file_names:a.map(De=>De.name),requested_by_name:g,requested_by_email:v,auth_mode:"supabase_google",source_app:"portal-cruce-cuentas-glm"};N("Procesando cruce de cuentas...");const Dt=new FormData;Dt.append("metadata",JSON.stringify(Ke)),Object.entries(Ke).forEach(([De,yn])=>{Dt.append(De,Array.isArray(yn)?JSON.stringify(yn):String(yn))}),Dt.append("payroll_file",e.rawFile,e.name),a.forEach((De,yn)=>{De.rawFile&&(Dt.append("bank_files",De.rawFile,De.name),Dt.append(`bank_file_${yn+1}`,De.rawFile,De.name))});const On=await fetch(be,{method:"POST",body:Dt});N("Generando reporte...");const gn=(On.headers.get("content-type")??"").includes("application/json")?await On.json():{ok:On.ok,message:await On.text()};if(!On.ok||(gn==null?void 0:gn.ok)===!1)throw new Error(typeof(gn==null?void 0:gn.message)=="string"?gn.message:"No se pudo procesar el cruce. Verifica los archivos e intenta nuevamente.");const Kr=NR(gn);m(Kr),c(!0),n(Kr.message||"Cruce procesado correctamente.","success"),setTimeout(()=>{const De=document.getElementById("resultados-seccion");De&&De.scrollIntoView({behavior:"smooth",block:"start"})},150)}catch(K){const be=LR(K);c(!1),m(null),n(be,"error")}finally{k(!1),N("")}}},ga=()=>{if(d!=null&&d.reportUrl){window.open(d.reportUrl,"_blank","noopener,noreferrer");return}n("El reporte aún no tiene un enlace disponible.","info")};return b.jsxs("div",{className:"flex-1 flex flex-col min-h-screen bg-neutral-50 text-neutral-800 font-sans",children:[b.jsxs("header",{className:"bg-white border-b-4 border-[#6CC24A] flex justify-between items-center w-full px-4 sm:px-8 h-[84px] sticky top-0 z-40 shadow-sm gap-x-4",children:[b.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 min-w-0",children:[b.jsx("button",{onClick:p,className:"md:hidden p-2 -ml-2 text-neutral-600 hover:text-neutral-800 hover:bg-neutral-100 transition-colors flex-shrink-0","aria-label":"Abrir menú",children:b.jsx(Cw,{className:"w-6 h-6"})}),b.jsx("h1",{className:"text-xs sm:text-sm md:text-lg lg:text-2xl font-black text-[#4F758B] tracking-tight uppercase flex items-center gap-1.5 sm:gap-2 min-w-0",children:b.jsxs("span",{className:"truncate",children:["Cruce de Cuentas GLM - ",_.name]})})]}),b.jsx("div",{className:"flex-shrink-0 flex items-center","aria-label":`Bandera de ${_.name}`,children:b.jsx("div",{className:"border border-neutral-200 bg-white px-2.5 py-2 shadow-sm",children:b.jsx("img",{src:_.flag,alt:`Bandera de ${_.name}`,className:"h-5 sm:h-6 w-auto object-contain"})})})]}),b.jsxs("main",{className:"flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 py-8 flex flex-col gap-8",children:[b.jsxs("section",{className:"bg-white border border-[#D0D0D0] p-5 shadow-sm",children:[b.jsx("div",{className:"flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-5",children:b.jsxs("div",{className:"flex items-center gap-3",children:[b.jsx("div",{className:"bg-[#4F758B]/10 p-2 rounded-full",children:b.jsx(Rw,{className:"w-5 h-5 text-[#4F758B]"})}),b.jsx("div",{className:"pt-0.5",children:b.jsx("h2",{className:"text-sm font-black text-[#4F758B] uppercase tracking-wider leading-none",children:"Datos del cruce"})})]})}),b.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[b.jsxs("label",{className:"flex flex-col gap-1.5",children:[b.jsx("span",{className:"text-[10px] font-black uppercase tracking-wider text-neutral-500",children:"Año"}),b.jsx("select",{value:F,onChange:K=>{J(Number(K.target.value)),pe()},className:"border border-[#D0D0D0] bg-white px-3 py-2.5 text-sm font-bold text-neutral-700 focus:outline-none focus:border-[#4F758B]",children:ee.map(K=>b.jsx("option",{value:K,children:K},K))})]}),b.jsxs("label",{className:"flex flex-col gap-1.5",children:[b.jsx("span",{className:"text-[10px] font-black uppercase tracking-wider text-neutral-500",children:"Mes"}),b.jsx("select",{value:G,onChange:K=>{Y(Number(K.target.value)),pe()},className:"border border-[#D0D0D0] bg-white px-3 py-2.5 text-sm font-bold text-neutral-700 focus:outline-none focus:border-[#4F758B]",children:jw.map(K=>b.jsx("option",{value:K.value,children:K.label},K.value))})]}),b.jsxs("label",{className:"flex flex-col gap-1.5",children:[b.jsx("span",{className:"text-[10px] font-black uppercase tracking-wider text-neutral-500",children:"Tipo de cruce"}),b.jsx("select",{value:Z,onChange:K=>{te(K.target.value),pe()},className:"border border-[#D0D0D0] bg-white px-3 py-2.5 text-sm font-bold text-neutral-700 focus:outline-none focus:border-[#4F758B]",children:Q0.map(K=>b.jsx("option",{value:K.value,children:K.label},K.value))})]})]}),b.jsxs("div",{className:"mt-4 grid grid-cols-1 md:grid-cols-[1fr_auto] gap-3 items-center bg-[#4F758B]/5 border border-[#4F758B]/10 px-4 py-3",children:[b.jsxs("div",{className:"flex items-start gap-2 text-xs text-neutral-600",children:[b.jsx(P2,{className:"w-4 h-4 text-[#4F758B] mt-0.5 flex-shrink-0"}),b.jsxs("div",{children:[b.jsx("span",{className:"font-black text-[#4F758B]",children:"Período calculado:"})," ",re.start," al ",re.end,b.jsx("p",{className:"text-[10px] text-neutral-500 mt-0.5",children:ge})]})]}),b.jsx("div",{className:"text-[10px] font-bold text-neutral-500 uppercase tracking-wider",children:re.label})]})]}),b.jsxs("section",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[b.jsxs("div",{className:"bg-white border border-[#D0D0D0] p-6 flex flex-col justify-between relative shadow-sm hover:shadow-md transition-shadow",children:[b.jsx("div",{className:"absolute top-0 left-0 w-full h-1 bg-[#4F758B]"}),b.jsxs("div",{children:[b.jsxs("div",{className:"flex items-center gap-2.5 mb-4",children:[b.jsx(Dl,{className:"w-5 h-5 text-[#4F758B]"}),b.jsx("h2",{className:"text-sm font-black text-neutral-800 uppercase tracking-wider",children:"1. Carga de Nómina"})]}),b.jsx("input",{type:"file",ref:D,onChange:hs,accept:".xlsx,.xls",className:"hidden"}),e?b.jsxs("div",{className:"border border-[#6CC24A]/30 bg-[#6CC24A]/5 p-5 flex items-center justify-between gap-3",children:[b.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[b.jsx(Dl,{className:"w-8 h-8 text-[#6CC24A] flex-shrink-0"}),b.jsxs("div",{className:"overflow-hidden",children:[b.jsx("p",{className:"text-xs font-bold text-neutral-700 truncate max-w-[300px]",title:e.name,children:e.name}),b.jsxs("p",{className:"text-[10px] text-neutral-400 font-mono mt-0.5",children:[e.size," • Excel"]})]})]}),b.jsx("button",{onClick:()=>{s(null),D.current&&(D.current.value=""),pe(),n("Nómina removida.","info")},className:"p-1.5 text-neutral-400 hover:text-red-500 hover:bg-neutral-100 transition-all rounded","aria-label":"Remover nómina",children:b.jsx(Y0,{className:"w-4.5 h-4.5"})})]}):b.jsxs("div",{onDragOver:lt,onDrop:Ie,onClick:()=>{var K;return(K=D.current)==null?void 0:K.click()},className:"border-2 border-dashed border-[#D0D0D0] bg-neutral-50 hover:bg-[#4F758B]/5 hover:border-[#4F758B]/40 transition-colors flex flex-col items-center justify-center py-10 px-4 text-center cursor-pointer min-h-[190px]",children:[b.jsx(X0,{className:"w-8 h-8 text-neutral-300 mb-2"}),b.jsx("p",{className:"text-xs font-bold text-neutral-700",children:"Arrastre y suelte archivo Excel"}),b.jsx("p",{className:"text-[10px] text-neutral-400 mt-1 font-medium",children:"Formato .xlsx, .xls"}),b.jsx("button",{type:"button",className:"mt-4 border border-[#D0D0D0] bg-white px-4 py-1.5 text-[10px] font-bold text-neutral-600 hover:border-[#4F758B] hover:text-[#4F758B] transition-colors shadow-sm uppercase tracking-wide",children:"Seleccionar Archivo"})]})]})]}),b.jsxs("div",{className:"bg-white border border-[#D0D0D0] p-6 flex flex-col justify-between relative shadow-sm hover:shadow-md transition-shadow",children:[b.jsx("div",{className:"absolute top-0 left-0 w-full h-1 bg-[#4F758B]"}),b.jsxs("div",{children:[b.jsxs("div",{className:"flex items-center gap-2.5 mb-2",children:[b.jsx($h,{className:"w-5 h-5 text-[#4F758B]"}),b.jsx("h2",{className:"text-sm font-black text-neutral-800 uppercase tracking-wider",children:"2. Carga de Planillas del Banco"})]}),b.jsx("p",{className:"text-[11px] text-neutral-500 mb-4 leading-relaxed",children:"Puede subir múltiples archivos separados o un archivo consolidado del período."}),b.jsx("input",{type:"file",ref:I,onChange:pa,accept:".csv",multiple:!0,className:"hidden"}),b.jsxs("div",{onDragOver:lt,onDrop:Ui,onClick:()=>{var K;return(K=I.current)==null?void 0:K.click()},className:"border-2 border-dashed border-[#D0D0D0] bg-neutral-50 hover:bg-[#4F758B]/5 hover:border-[#4F758B]/40 transition-colors flex flex-col items-center justify-center py-8 px-4 text-center cursor-pointer min-h-[130px]",children:[b.jsx(X0,{className:"w-7 h-7 text-neutral-300 mb-2"}),b.jsx("p",{className:"text-xs font-bold text-neutral-700",children:"Arrastre y suelte archivo CSV"}),b.jsx("p",{className:"text-[10px] text-neutral-400 mt-1 font-medium",children:"Formato .csv"}),b.jsx("button",{type:"button",className:"mt-4 border border-[#D0D0D0] bg-white px-4 py-1.5 text-[10px] font-bold text-neutral-600 hover:border-[#4F758B] hover:text-[#4F758B] transition-colors shadow-sm uppercase tracking-wide",children:"Seleccionar Archivos"})]}),a.length>0&&b.jsx("div",{className:"mt-4 space-y-2 max-h-[140px] overflow-y-auto pr-1",children:a.map((K,be)=>b.jsxs("div",{className:"border border-neutral-200 bg-neutral-50 px-3 py-2 flex items-center justify-between gap-3",children:[b.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[b.jsx($h,{className:"w-4 h-4 text-[#4F758B] flex-shrink-0"}),b.jsxs("div",{className:"min-w-0",children:[b.jsx("p",{className:"text-[11px] font-bold text-neutral-700 truncate max-w-[260px]",title:K.name,children:K.name}),b.jsxs("p",{className:"text-[9px] text-neutral-400 font-mono",children:[K.size," • CSV"]})]})]}),b.jsx("button",{onClick:Ke=>{Ke.stopPropagation(),Gr(be)},className:"p-1 text-neutral-400 hover:text-red-500 hover:bg-white rounded transition-colors","aria-label":"Remover planilla de banco",children:b.jsx(Y0,{className:"w-3.5 h-3.5"})})]},`${K.name}-${be}`))})]})]})]}),b.jsx("section",{className:"flex flex-col items-center gap-3",children:b.jsx("button",{onClick:jn,disabled:E,className:"w-full sm:w-auto min-w-[280px] bg-[#4F758B] hover:bg-[#41677b] disabled:bg-neutral-300 disabled:cursor-not-allowed text-white px-8 py-4 font-black text-sm uppercase tracking-wider shadow-md flex items-center justify-center gap-3 transition-all duration-150 active:scale-[0.99] border-l-4 border-[#6CC24A]",children:E?b.jsxs(b.Fragment,{children:[b.jsx(Ed,{className:"w-5 h-5 animate-spin"}),b.jsx("span",{children:C||"Procesando cruce de cuentas..."})]}):b.jsxs(b.Fragment,{children:[b.jsx(pR,{className:"w-5 h-5"}),b.jsx("span",{children:"Ejecutar Cruce de Cuentas"})]})})}),b.jsx(as,{children:u&&d&&b.jsxs(mn.section,{id:"resultados-seccion",initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:10},className:"flex flex-col gap-5 scroll-mt-28",children:[b.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4",children:[b.jsxs("div",{className:"bg-white border border-emerald-200 p-4 shadow-sm",children:[b.jsxs("div",{className:"flex items-center gap-2 text-emerald-700",children:[b.jsx(yf,{className:"w-5 h-5"}),b.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black",children:"Coincidencias"})]}),b.jsx("p",{className:"text-3xl font-black text-emerald-800 mt-2",children:d.summary.matches})]}),b.jsxs("div",{className:"bg-white border border-red-200 p-4 shadow-sm",children:[b.jsxs("div",{className:"flex items-center gap-2 text-[#ba1a1a]",children:[b.jsx(vf,{className:"w-5 h-5"}),b.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black",children:"Discrepancias"})]}),b.jsx("p",{className:"text-3xl font-black text-[#ba1a1a] mt-2",children:d.summary.discrepancies})]}),b.jsxs("div",{className:"bg-white border border-amber-200 p-4 shadow-sm",children:[b.jsxs("div",{className:"flex items-center gap-2 text-amber-800",children:[b.jsx(F0,{className:"w-5 h-5"}),b.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black",children:"Banco sin nómina"})]}),b.jsx("p",{className:"text-3xl font-black text-amber-800 mt-2",children:d.summary.bankWithoutPayroll})]}),b.jsxs("div",{className:"bg-white border border-orange-200 p-4 shadow-sm",children:[b.jsxs("div",{className:"flex items-center gap-2 text-orange-800",children:[b.jsx(F0,{className:"w-5 h-5"}),b.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black",children:"Banco sin Bamboo"})]}),b.jsx("p",{className:"text-3xl font-black text-orange-800 mt-2",children:d.summary.bankWithoutBamboo})]}),b.jsxs("div",{className:"bg-white border border-violet-200 p-4 shadow-sm",children:[b.jsxs("div",{className:"flex items-center gap-2 text-violet-800",children:[b.jsx($h,{className:"w-5 h-5"}),b.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black",children:"Diferencias nombre banco"})]}),b.jsx("p",{className:"text-3xl font-black text-violet-800 mt-2",children:d.summary.nameDifferences})]}),b.jsxs("div",{className:"bg-white border border-blue-200 p-4 shadow-sm",children:[b.jsxs("div",{className:"flex items-center gap-2 text-blue-800",children:[b.jsx(Dl,{className:"w-5 h-5"}),b.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black",children:"Nómina sin cuenta"})]}),b.jsx("p",{className:"text-3xl font-black text-blue-800 mt-2",children:d.summary.payrollWithoutAccount})]})]}),b.jsxs("div",{className:"bg-white border border-[#D0D0D0] shadow-sm overflow-hidden",children:[b.jsxs("div",{className:"p-5 border-b border-neutral-200 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4",children:[b.jsxs("div",{children:[b.jsx("h2",{className:"text-lg font-black text-[#4F758B] uppercase tracking-tight",children:"Resultados del Cruce"}),b.jsx("p",{className:"text-[11px] text-neutral-500 mt-1",children:re.label})]}),b.jsx("div",{className:"flex flex-col sm:flex-row gap-2",children:b.jsxs("button",{onClick:ga,disabled:!d.reportUrl,className:"inline-flex items-center justify-center gap-2 border border-[#4F758B] text-[#4F758B] hover:bg-[#4F758B] hover:text-white px-4 py-2 text-xs font-bold transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[b.jsx(Z2,{className:"w-4 h-4"}),"Abrir Google Sheet"]})})]}),b.jsxs("div",{className:"p-4 border-b border-neutral-200 bg-neutral-50 flex flex-col lg:flex-row gap-3 lg:items-center lg:justify-between",children:[b.jsxs("div",{className:"relative w-full lg:max-w-sm",children:[b.jsx(kw,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-neutral-400"}),b.jsx("input",{type:"text",value:qe,onChange:K=>{X(K.target.value),fe(1)},placeholder:"Buscar empleado, Employee Number o cuenta...",className:"w-full pl-9 pr-3 py-2 border border-[#D0D0D0] text-xs font-medium focus:outline-none focus:border-[#4F758B]"})]}),b.jsx("div",{className:"flex flex-wrap gap-2",children:[["todos","Todos"],["discrepancias","Discrepancias"],["coincidencias","Coincidencias"],["banco_sin_nomina","Banco sin nómina"],["banco_sin_bamboo","Banco sin Bamboo"],["diferencia_nombre_banco","Diferencias nombre banco"],["nomina_sin_cuenta","Nómina sin cuenta"]].map(([K,be])=>b.jsx("button",{onClick:()=>{z(K),fe(1)},className:`px-3 py-1.5 text-[10px] uppercase tracking-wider font-black border transition-colors ${O===K?"bg-[#4F758B] text-white border-[#4F758B]":"bg-white text-neutral-500 border-neutral-300 hover:border-[#4F758B] hover:text-[#4F758B]"}`,children:be},K))})]}),b.jsx("div",{className:"overflow-x-auto",children:b.jsxs("table",{className:"w-full text-left border-collapse min-w-[960px] xl:min-w-full",children:[b.jsx("thead",{children:b.jsxs("tr",{className:"bg-[#4F758B] text-white text-xs font-bold uppercase tracking-wider",children:[b.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Empleado"}),b.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Employee Number"}),b.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Cuenta"}),b.jsx("th",{className:"py-3 px-3 xl:px-4 text-right",children:"Monto Nómina"}),b.jsx("th",{className:"py-3 px-3 xl:px-4 text-right",children:"Monto Banco"}),b.jsx("th",{className:"py-3 px-3 xl:px-4 text-right",children:"Diferencia"}),b.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Estado"}),b.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Categoría"}),b.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Observación"})]})}),b.jsx("tbody",{className:"divide-y divide-neutral-200 text-xs",children:ne.length>0?ne.map(K=>b.jsxs("tr",{className:"hover:bg-neutral-50 transition-colors",children:[b.jsx("td",{className:"py-3 px-3 xl:px-4 font-bold text-neutral-800",children:K.employee}),b.jsx("td",{className:"py-3 px-3 xl:px-4 font-mono text-neutral-600",children:K.employeeNumber||"—"}),b.jsx("td",{className:"py-3 px-3 xl:px-4 font-mono text-neutral-500",children:K.account??"—"}),b.jsx("td",{className:"py-3 px-3 xl:px-4 text-right font-mono text-neutral-700",children:qh(K.amountPayroll,_)}),b.jsx("td",{className:"py-3 px-3 xl:px-4 text-right font-mono text-neutral-700",children:qh(K.amountBank,_)}),b.jsx("td",{className:"py-3 px-3 xl:px-4 text-right font-mono text-neutral-700",children:qh(K.difference,_)}),b.jsx("td",{className:"py-3 px-3 xl:px-4 text-center",children:b.jsx("span",{className:`inline-block px-2.5 py-1 text-[9px] font-black uppercase tracking-wider border ${DR(K.status)}`,children:K.status})}),b.jsx("td",{className:"py-3 px-3 xl:px-4 text-neutral-600 max-w-[180px] capitalize",children:BR(K.category??K.source)}),b.jsx("td",{className:"py-3 px-3 xl:px-4 text-neutral-600 max-w-[300px]",children:K.observation})]},K.id)):b.jsx("tr",{children:b.jsx("td",{colSpan:9,className:"py-12 text-center text-neutral-400 font-medium",children:"No hay resultados para el filtro seleccionado."})})})]})}),b.jsxs("div",{className:"p-4 border-t border-neutral-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 text-xs text-neutral-500",children:[b.jsxs("span",{children:["Mostrando ",ne.length," de ",A.length," resultado(s)."]}),b.jsxs("div",{className:"flex items-center gap-2",children:[b.jsx("button",{onClick:()=>fe(K=>Math.max(1,K-1)),disabled:de===1,className:"px-3 py-1.5 border border-neutral-300 bg-white disabled:opacity-40 disabled:cursor-not-allowed hover:border-[#4F758B] font-bold",children:"Anterior"}),b.jsxs("span",{className:"font-bold text-neutral-700",children:["Página ",de," de ",Q]}),b.jsx("button",{onClick:()=>fe(K=>Math.min(Q,K+1)),disabled:de===Q,className:"px-3 py-1.5 border border-neutral-300 bg-white disabled:opacity-40 disabled:cursor-not-allowed hover:border-[#4F758B] font-bold",children:"Siguiente"})]})]})]})]})})]})]})}const Ih=10;function FR(n){return n==="TT"?"":"https://agenteit.digitalcompass.agency/webhook/cruce-cuentas-gt-historicos"}function YR(n){return n==="TT"?"":"https://agenteit.digitalcompass.agency/webhook/cruce-cuentas-gt-marcar-resuelto"}function Jn(n){const e=Number(n);return Number.isFinite(e)?e:0}function XR(n,e){if(!n)return"";const s=new Date(String(n));return Number.isNaN(s.getTime())?String(n).slice(0,10):s.toLocaleDateString(e,{year:"numeric",month:"2-digit",day:"2-digit"})}function Ad(n,e){if(!n)return"";const s=new Date(String(n));return Number.isNaN(s.getTime())?String(n):s.toLocaleString(e,{dateStyle:"short",timeStyle:"short"})}function JR(n){return String(n??"").toLowerCase().includes("resuelto")?"Resuelto":"Pendiente revisión"}function QR(n,e){const s=n,a=!Array.isArray(s)&&s?s:{};return(Array.isArray(s)?s:Array.isArray(a.reports)?a.reports:[]).map((u,c)=>{const d=u,m=Jn(d.discrepancias??d.discrepancies),p=Jn(d.bancoSinNomina??d.banco_sin_nomina??d.bankWithoutPayroll),g=Jn(d.bancoSinBamboo??d.banco_sin_bamboo??d.bankWithoutBamboo),v=Jn(d.nominaSinCuenta??d.nomina_sin_cuenta??d.payrollWithoutAccount),w=Jn(d.diferenciasNombreBanco??d.diferencias_nombre_banco??d.nameDifferences),_=m+p+g+v+w,S=String(d.country??d.pais??d.country_code??e.code).toUpperCase(),E=Array.isArray(d.archivosBanco)?d.archivosBanco.map(String):Array.isArray(d.bank_file_names)?d.bank_file_names.map(String):[],k=d.fechaEjecucion??d.ejecutado_en??d.created_at;return{id:String(d.id??`reporte-${c+1}`),country:S==="TT"?"TT":"GT",date:XR(d.fecha??d.period_end??k,e.locale),executionDate:Ad(k,e.locale),period:String(d.periodo??d.period_label??d.period??"Período no especificado"),payrollFile:String(d.archivoNomina??d.payroll_file_name??d.payrollFile??""),bankFiles:E,matches:Jn(d.coincidencias??d.matches),discrepancies:m,bankWithoutPayroll:p,bankWithoutBamboo:g,payrollWithoutAccount:v,nameDifferences:w,totalPending:_,totalPayroll:Jn(d.totalNomina??d.total_nomina),totalBank:Jn(d.totalBanco??d.total_banco),totalDifference:Jn(d.diferenciaTotal??d.diferencia_total),status:JR(d.estado??d.status??d.estadoLabel),reportUrl:d.reportUrl||d.report_url?String(d.reportUrl??d.report_url):void 0,spreadsheetId:d.spreadsheetId||d.spreadsheet_id?String(d.spreadsheetId??d.spreadsheet_id):void 0,executedBy:d.ejecutadoPorNombre||d.ejecutado_por_nombre?String(d.ejecutadoPorNombre??d.ejecutado_por_nombre):void 0,executedByEmail:d.ejecutadoPorEmail||d.ejecutado_por_email?String(d.ejecutadoPorEmail??d.ejecutado_por_email):void 0,resolvedBy:d.resueltoPorNombre||d.resuelto_por_nombre?String(d.resueltoPorNombre??d.resuelto_por_nombre):void 0,resolvedByEmail:d.resueltoPorEmail||d.resuelto_por_email?String(d.resueltoPorEmail??d.resuelto_por_email):void 0,resolvedAt:Ad(d.resueltoEn??d.resuelto_en,e.locale),resolutionComment:d.comentarioResolucion||d.comentario_resolucion?String(d.comentarioResolucion??d.comentario_resolucion):void 0,_sortTime:new Date(String(k??d.period_end??"")).getTime()||0}}).filter(u=>u.country===e.code).sort((u,c)=>c._sortTime-u._sortTime).map(({_sortTime:u,...c})=>c)}function ZR(n){return n==="Resuelto"?"bg-blue-50 text-blue-800 border-blue-200":"bg-amber-50 text-amber-800 border-amber-200"}function WR(n){return n==="Resuelto"?"RESUELTO":"PENDIENTE REVISIÓN"}function eC({onShowToast:n,onOpenSidebar:e,operatorName:s,operatorEmail:a,country:l}){const[u,c]=P.useState(""),[d,m]=P.useState("todos"),[p,g]=P.useState([]),[v,w]=P.useState(1),[_,S]=P.useState(!1),[E,k]=P.useState(!1),[C,N]=P.useState(""),[O,z]=P.useState(null),[F,J]=P.useState(""),G=P.useMemo(()=>{const X=u.trim().toLowerCase();return p.filter(ue=>{const D=d==="todos"||d==="pendiente"&&ue.status==="Pendiente revisión"||d==="resuelto"&&ue.status==="Resuelto",I=!X||ue.period.toLowerCase().includes(X)||ue.payrollFile.toLowerCase().includes(X)||ue.id.toLowerCase().includes(X)||(ue.resolvedBy??"").toLowerCase().includes(X)||(ue.executedBy??"").toLowerCase().includes(X);return D&&I})},[p,u,d]),Y=Math.max(1,Math.ceil(G.length/Ih)),Z=G.slice((v-1)*Ih,v*Ih);P.useEffect(()=>{w(1)},[u,d,l.code]),P.useEffect(()=>{v>Y&&w(Y)},[v,Y]);const te=async()=>{const X=FR(l.code);if(!X){g([]),N(`Los reportes de ${l.name} estarán disponibles próximamente.`);return}S(!0),N("");try{const ue=new URL(X);ue.searchParams.set("country",l.code);const D=await fetch(ue.toString(),{method:"GET"}),I=await D.json().catch(()=>null);if(!D.ok||(I==null?void 0:I.ok)===!1)throw new Error("No se pudieron cargar los reportes históricos.");g(QR(I,l)),w(1)}catch{N("No se pudieron cargar los reportes históricos. Intenta nuevamente."),n("No se pudieron cargar los reportes históricos.","error")}finally{S(!1)}};P.useEffect(()=>{te()},[l.code]);const de=X=>{if(X.reportUrl){window.open(X.reportUrl,"_blank","noopener,noreferrer");return}n("Este reporte aún no tiene un Google Sheet disponible.","info")},fe=X=>{if(X.status==="Resuelto"){n("Este reporte ya fue marcado como resuelto.","info");return}z(X),J("")},qe=async()=>{if(!O)return;const X=F.trim();if(X.length<10){n("Debes escribir un comentario de resolución más descriptivo.","error");return}const ue=YR(l.code);if(!ue){n(`La resolución de reportes para ${l.name} estará disponible próximamente.`,"info");return}k(!0);try{const D=await fetch(ue,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:O.id,comentarioResolucion:X,resueltoPorNombre:s,resueltoPorEmail:a,country:l.code,countryName:l.name})}),I=await D.json().catch(()=>null);if(!D.ok||(I==null?void 0:I.ok)===!1){const me=Array.isArray(I==null?void 0:I.errors)?I.errors.join(` `):(I==null?void 0:I.message)||"No se pudo marcar el reporte como resuelto.";throw new Error(me)}const ee=I.report??{},re=Ad(ee.resueltoEn??new Date().toISOString(),l.locale);g(me=>me.map(A=>A.id===O.id?{...A,status:"Resuelto",resolvedBy:String(ee.resueltoPorNombre??s),resolvedByEmail:String(ee.resueltoPorEmail??a),resolvedAt:re,resolutionComment:String(ee.comentarioResolucion??X)}:A)),z(null),J(""),n("Reporte marcado como resuelto correctamente.","success")}catch(D){const I=D instanceof Error?D.message:"No se pudo marcar el reporte como resuelto.";n(I,"error")}finally{k(!1)}};return b.jsxs("div",{className:"flex-1 flex flex-col min-h-screen bg-neutral-50 text-neutral-800 font-sans",children:[b.jsxs("header",{className:"bg-white border-b-4 border-[#6CC24A] flex justify-between items-center w-full px-4 sm:px-8 h-[84px] sticky top-0 z-40 shadow-sm gap-x-4",children:[b.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 min-w-0",children:[b.jsx("button",{onClick:e,className:"md:hidden p-2 -ml-2 text-neutral-600 hover:text-neutral-800 hover:bg-neutral-100 transition-colors flex-shrink-0","aria-label":"Abrir menú",children:b.jsx(Cw,{className:"w-6 h-6"})}),b.jsx("h1",{className:"text-xs sm:text-sm md:text-lg lg:text-2xl font-black text-[#4F758B] tracking-tight uppercase flex items-center gap-1.5 sm:gap-2 min-w-0",children:b.jsxs("span",{className:"truncate",children:["Reportes Históricos - ",l.name]})})]}),b.jsxs("div",{className:"flex items-center gap-3 flex-shrink-0",children:[b.jsx("div",{className:"hidden sm:flex items-center border border-neutral-200 bg-white px-2.5 py-2 shadow-sm","aria-label":`Bandera de ${l.name}`,children:b.jsx("img",{src:l.flag,alt:`Bandera de ${l.name}`,className:"h-5 sm:h-6 w-auto object-contain"})}),b.jsxs("button",{onClick:te,disabled:_,className:"hidden sm:inline-flex items-center gap-2 border border-[#4F758B]/20 text-[#4F758B] px-3 py-2 text-xs font-bold hover:border-[#4F758B]/50 disabled:opacity-50",children:[b.jsx(bR,{className:`w-4 h-4 ${_?"animate-spin":""}`}),"Actualizar"]})]})]}),b.jsxs("main",{className:"flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 py-8 flex flex-col gap-6",children:[b.jsxs("div",{className:"bg-white border border-[#D0D0D0] p-4 flex flex-col lg:flex-row items-center justify-between gap-4 shadow-sm",children:[b.jsxs("div",{className:"relative w-full lg:max-w-md",children:[b.jsx(kw,{className:"absolute left-3.5 top-1/2 transform -translate-y-1/2 text-neutral-400 w-4 h-4"}),b.jsx("input",{type:"text",placeholder:"Buscar por período, reporte, archivo o resolutor...",value:u,onChange:X=>c(X.target.value),className:"w-full pl-10 pr-4 py-2 border border-[#D0D0D0] text-xs font-medium placeholder-neutral-400 focus:outline-none focus:border-[#4F758B] transition-colors"})]}),b.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3 w-full lg:w-auto",children:[b.jsx("div",{className:"flex flex-wrap gap-2",children:[["todos","Todos"],["pendiente","Pendiente revisión"],["resuelto","Resuelto"]].map(([X,ue])=>b.jsx("button",{onClick:()=>m(X),className:`px-3 py-1.5 text-[10px] uppercase tracking-wider font-black border transition-colors ${d===X?"bg-[#4F758B] text-white border-[#4F758B]":"bg-white text-neutral-500 border-neutral-300 hover:border-[#4F758B] hover:text-[#4F758B]"}`,children:ue},X))}),b.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold text-neutral-500",children:[b.jsx(sR,{className:"w-4 h-4 text-neutral-400"}),b.jsxs("span",{children:["Mostrando: ",G.length," de ",p.length," reportes"]})]})]})]}),C&&b.jsxs("div",{className:"border border-red-200 bg-red-50 text-[#ba1a1a] px-4 py-3 text-xs font-bold flex items-center gap-2",children:[b.jsx(vf,{className:"w-4 h-4"}),C]}),b.jsxs("div",{className:"bg-white border border-[#D0D0D0] shadow-sm overflow-hidden",children:[b.jsx("div",{className:"overflow-x-auto",children:b.jsxs("table",{className:"w-full text-left border-collapse min-w-[960px] xl:min-w-full",children:[b.jsx("thead",{children:b.jsxs("tr",{className:"bg-[#4F758B] text-white text-xs font-bold uppercase tracking-wider",children:[b.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Fecha"}),b.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Período"}),b.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Archivo de Nómina"}),b.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Coincidencias"}),b.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Banco sin Bamboo"}),b.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Pendientes"}),b.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Estado"}),b.jsx("th",{className:"py-3 px-3 xl:px-4",children:"Resuelto por"}),b.jsx("th",{className:"py-3 px-3 xl:px-4 text-center",children:"Acciones"})]})}),b.jsx("tbody",{className:"divide-y divide-neutral-200 text-xs",children:_?b.jsx("tr",{children:b.jsx("td",{colSpan:9,className:"py-12 text-center text-neutral-400 font-medium",children:b.jsxs("div",{className:"inline-flex items-center gap-2",children:[b.jsx(Ed,{className:"w-4 h-4 animate-spin"}),"Cargando reportes históricos..."]})})}):Z.length>0?Z.map(X=>b.jsxs(mn.tr,{initial:{opacity:0},animate:{opacity:1},className:"hover:bg-neutral-50/70 transition-colors",children:[b.jsx("td",{className:"py-3 px-3 xl:px-4 font-medium text-neutral-700",children:b.jsxs("div",{className:"flex items-center gap-2",children:[b.jsx($2,{className:"w-4 h-4 text-neutral-400"}),b.jsxs("div",{children:[b.jsx("span",{children:X.date}),X.executionDate&&b.jsx("p",{className:"text-[9px] text-neutral-400 mt-0.5",children:X.executionDate})]})]})}),b.jsx("td",{className:"py-3 px-3 xl:px-4 font-bold text-[#4F758B]",children:X.period}),b.jsx("td",{className:"py-3 px-3 xl:px-4 font-mono text-neutral-500 truncate max-w-[260px]",title:X.payrollFile,children:b.jsxs("div",{className:"flex items-center gap-1.5",children:[b.jsx(Dl,{className:"w-4 h-4 text-neutral-400 flex-shrink-0"}),b.jsx("span",{className:"truncate",children:X.payrollFile||"No especificado"})]})}),b.jsx("td",{className:"py-3 px-3 xl:px-4 text-center font-black text-emerald-800",children:X.matches}),b.jsx("td",{className:"py-3 px-3 xl:px-4 text-center",children:b.jsx("span",{className:`inline-block min-w-8 px-2.5 py-1 text-[10px] font-black border ${X.bankWithoutBamboo>0?"bg-orange-50 text-orange-800 border-orange-200":"bg-neutral-50 text-neutral-400 border-neutral-200"}`,children:X.bankWithoutBamboo})}),b.jsx("td",{className:"py-3 px-3 xl:px-4 text-center",children:b.jsx("span",{className:`inline-block px-2.5 py-1 text-[10px] font-bold border ${X.totalPending>0?"bg-red-50 text-[#ba1a1a] border-red-200":"bg-emerald-50 text-emerald-800 border-emerald-200"}`,children:X.totalPending===0?"Sin pendientes":`${X.totalPending} pendiente${X.totalPending>1?"s":""}`})}),b.jsx("td",{className:"py-3 px-3 xl:px-4 text-center",children:b.jsx("span",{className:`inline-block px-2.5 py-1 text-[9px] uppercase font-black tracking-wider border ${ZR(X.status)}`,children:WR(X.status)})}),b.jsx("td",{className:"py-3 px-3 xl:px-4 text-neutral-600 max-w-[220px]",children:X.resolvedBy?b.jsxs("div",{title:X.resolutionComment||"",children:[b.jsx("p",{className:"font-bold text-neutral-700 truncate",children:X.resolvedBy}),b.jsx("p",{className:"text-[10px] text-neutral-400",children:X.resolvedAt})]}):b.jsx("span",{className:"text-neutral-400",children:"Pendiente"})}),b.jsx("td",{className:"py-3 px-3 xl:px-4 text-center",children:b.jsxs("div",{className:"flex justify-center gap-2",children:[b.jsxs("button",{onClick:()=>de(X),className:"inline-flex items-center gap-1.5 text-[#4F758B] hover:text-[#3d6378] font-bold text-xs border border-[#4F758B]/20 hover:border-[#4F758B]/50 px-3 py-1.5 bg-white hover:bg-neutral-50 transition-colors",children:[b.jsx(eR,{className:"w-3.5 h-3.5"}),b.jsx("span",{children:"Ver"})]}),b.jsxs("button",{onClick:()=>fe(X),disabled:X.status==="Resuelto",className:"inline-flex items-center gap-1.5 text-emerald-700 hover:text-emerald-800 font-bold text-xs border border-emerald-200 hover:border-emerald-400 px-3 py-1.5 bg-emerald-50 hover:bg-emerald-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[b.jsx(yf,{className:"w-3.5 h-3.5"}),b.jsx("span",{children:X.status==="Resuelto"?"Resuelto":"Marcar resuelto"})]})]})})]},X.id)):b.jsx("tr",{children:b.jsx("td",{colSpan:9,className:"py-12 text-center text-neutral-400 font-medium",children:"No se encontraron reportes históricos."})})})]})}),b.jsxs("div",{className:"p-4 border-t border-neutral-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 text-xs text-neutral-500",children:[b.jsxs("span",{children:["Mostrando ",Z.length," de ",G.length," reporte(s)."]}),b.jsxs("div",{className:"flex items-center gap-2",children:[b.jsx("button",{onClick:()=>w(X=>Math.max(1,X-1)),disabled:v===1,className:"px-3 py-1.5 border border-neutral-300 bg-white disabled:opacity-40 disabled:cursor-not-allowed hover:border-[#4F758B] font-bold",children:"Anterior"}),b.jsxs("span",{className:"font-bold text-neutral-700",children:["Página ",v," de ",Y]}),b.jsx("button",{onClick:()=>w(X=>Math.min(Y,X+1)),disabled:v===Y,className:"px-3 py-1.5 border border-neutral-300 bg-white disabled:opacity-40 disabled:cursor-not-allowed hover:border-[#4F758B] font-bold",children:"Siguiente"})]})]})]})]}),b.jsx(as,{children:O&&b.jsx(mn.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-[80] flex items-center justify-center bg-black/45 px-4",children:b.jsxs(mn.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:12},className:"w-full max-w-lg bg-white border border-[#D0D0D0] shadow-xl",children:[b.jsxs("div",{className:"border-b border-neutral-200 px-5 py-4 flex items-center justify-between",children:[b.jsxs("div",{children:[b.jsx("h2",{className:"text-base font-black text-[#4F758B] uppercase tracking-tight",children:"Marcar reporte como resuelto"}),b.jsx("p",{className:"text-xs text-neutral-500 mt-1",children:O.period})]}),b.jsx("button",{onClick:()=>z(null),disabled:E,className:"p-2 text-neutral-400 hover:text-neutral-700 disabled:opacity-50","aria-label":"Cerrar",children:b.jsx(bf,{className:"w-4 h-4"})})]}),b.jsxs("div",{className:"p-5 space-y-4",children:[b.jsx("div",{className:"bg-amber-50 border border-amber-200 text-amber-800 p-3 text-xs leading-relaxed",children:"Antes de resolver, confirma que las diferencias fueron revisadas y explica cómo se cerró el caso."}),b.jsxs("label",{className:"block",children:[b.jsx("span",{className:"text-[10px] uppercase tracking-wider font-black text-neutral-500",children:"Comentario de resolución"}),b.jsx("textarea",{value:F,onChange:X=>J(X.target.value),placeholder:"Ejemplo: Se corrigió la cuenta bancaria en nómina y se validó contra el banco.",className:"mt-2 w-full min-h-[130px] border border-[#D0D0D0] px-3 py-2 text-sm focus:outline-none focus:border-[#4F758B]"})]})]}),b.jsxs("div",{className:"border-t border-neutral-200 px-5 py-4 flex justify-end gap-3",children:[b.jsx("button",{onClick:()=>z(null),disabled:E,className:"border border-neutral-300 bg-white px-4 py-2 text-xs font-bold text-neutral-600 hover:bg-neutral-50 disabled:opacity-50",children:"Cancelar"}),b.jsxs("button",{onClick:qe,disabled:E,className:"bg-[#4F758B] hover:bg-[#41677b] text-white px-4 py-2 text-xs font-black uppercase tracking-wider disabled:opacity-50 inline-flex items-center gap-2",children:[E&&b.jsx(Ed,{className:"w-4 h-4 animate-spin"}),"Confirmar resolución"]})]})]})})})]})}function Kh({message:n,type:e,onClose:s}){P.useEffect(()=>{const u=setTimeout(()=>{s()},2e3);return()=>clearTimeout(u)},[s]);const a={success:"bg-[#6CC24A] text-white border-l-4 border-emerald-700",error:"bg-[#ba1a1a] text-white border-l-4 border-red-800",info:"bg-[#4F758B] text-white border-l-4 border-slate-700"},l={success:yf,error:K2,info:Rw}[e];return b.jsx("div",{className:"fixed bottom-6 right-6 z-50 max-w-sm w-full",children:b.jsxs(mn.div,{initial:{opacity:0,y:30,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:20,scale:.95},className:`flex items-center gap-3 p-4 shadow-lg rounded-md border border-neutral-200/10 ${a[e]}`,children:[b.jsx("span",{className:"flex-shrink-0",children:b.jsx(l,{className:"w-5 h-5"})}),b.jsx("div",{className:"flex-1 font-medium text-sm leading-tight pr-2",children:n}),b.jsx("button",{onClick:s,className:"flex-shrink-0 hover:bg-white/20 p-1 rounded transition-colors text-white",children:b.jsx(bf,{className:"w-4 h-4"})})]})})}function su(n,e){var s={};for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&e.indexOf(a)<0&&(s[a]=n[a]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var l=0,a=Object.getOwnPropertySymbols(n);ln?(...e)=>n(...e):(...e)=>fetch(...e);class wf extends Error{constructor(e,s="FunctionsError",a){super(e),this.name=s,this.context=a}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class iC extends wf{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class ov extends wf{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class lv extends wf{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Rd;(function(n){n.Any="any",n.ApNortheast1="ap-northeast-1",n.ApNortheast2="ap-northeast-2",n.ApSouth1="ap-south-1",n.ApSoutheast1="ap-southeast-1",n.ApSoutheast2="ap-southeast-2",n.CaCentral1="ca-central-1",n.EuCentral1="eu-central-1",n.EuWest1="eu-west-1",n.EuWest2="eu-west-2",n.EuWest3="eu-west-3",n.SaEast1="sa-east-1",n.UsEast1="us-east-1",n.UsWest1="us-west-1",n.UsWest2="us-west-2"})(Rd||(Rd={}));class sC{constructor(e,{headers:s={},customFetch:a,region:l=Rd.Any}={}){this.url=e,this.headers=s,this.region=l,this.fetch=nC(a)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return tC(this,arguments,void 0,function*(s,a={}){var l;let u,c;try{const{headers:d,method:m,body:p,signal:g,timeout:v}=a;let w={},{region:_}=a;_||(_=this.region);const S=new URL(`${this.url}/${s}`);_&&_!=="any"&&(w["x-region"]=_,S.searchParams.set("forceFunctionRegion",_));let E;const k=!!d&&Object.keys(d).some(J=>J.toLowerCase()==="content-type");p&&!k?typeof Blob<"u"&&p instanceof Blob||p instanceof ArrayBuffer?(w["Content-Type"]="application/octet-stream",E=p):typeof p=="string"?(w["Content-Type"]="text/plain",E=p):typeof FormData<"u"&&p instanceof FormData?E=p:(w["Content-Type"]="application/json",E=JSON.stringify(p)):p&&typeof p!="string"&&!(typeof Blob<"u"&&p instanceof Blob)&&!(p instanceof ArrayBuffer)&&!(typeof FormData<"u"&&p instanceof FormData)?E=JSON.stringify(p):E=p;let C=g;v&&(c=new AbortController,u=setTimeout(()=>c.abort(),v),g?(C=c.signal,g.addEventListener("abort",()=>c.abort())):C=c.signal);const N=yield this.fetch(S.toString(),{method:m||"POST",headers:Object.assign(Object.assign(Object.assign({},w),this.headers),d),body:E,signal:C}).catch(J=>{throw new iC(J)}),O=N.headers.get("x-relay-error");if(O&&O==="true")throw new ov(N);if(!N.ok)throw new lv(N);let z=((l=N.headers.get("Content-Type"))!==null&&l!==void 0?l:"text/plain").split(";")[0].trim(),F;return z==="application/json"?F=yield N.json():z==="application/octet-stream"||z==="application/pdf"?F=yield N.blob():z==="text/event-stream"?F=N:z==="multipart/form-data"?F=yield N.formData():F=yield N.text(),{data:F,error:null,response:N}}catch(d){return{data:null,error:d,response:d instanceof lv||d instanceof ov?d.context:void 0}}finally{u&&clearTimeout(u)}})}}const Dw=3,uv=n=>Math.min(1e3*2**n,3e4),aC=[520,503],Mw=["GET","HEAD","OPTIONS"];var cv=class extends Error{constructor(n){super(n.message),this.name="PostgrestError",this.details=n.details,this.hint=n.hint,this.code=n.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function hv(n,e){return new Promise(s=>{if(e!=null&&e.aborted){s();return}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",l),s()},n);function l(){clearTimeout(a),s()}e==null||e.addEventListener("abort",l)})}function rC(n,e,s,a){return!(!a||s>=Dw||!Mw.includes(n)||!aC.includes(e))}var oC=class{constructor(n){var e,s,a,l,u;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=n.method,this.url=n.url,this.headers=new Headers(n.headers),this.schema=n.schema,this.body=n.body,this.shouldThrowOnError=(e=n.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=n.signal,this.isMaybeSingle=(s=n.isMaybeSingle)!==null&&s!==void 0?s:!1,this.shouldStripNulls=(a=n.shouldStripNulls)!==null&&a!==void 0?a:!1,this.urlLengthLimit=(l=n.urlLengthLimit)!==null&&l!==void 0?l:8e3,this.retryEnabled=(u=n.retry)!==null&&u!==void 0?u:!0,n.fetch?this.fetch=n.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(n,e){return this.headers=new Headers(this.headers),this.headers.set(n,e),this}retry(n){return this.retryEnabled=n,this}then(n,e){var s=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){const c=this.headers.get("Accept");c==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!c||c==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const a=this.fetch;let u=(async()=>{let c=0;for(;;){const p={};s.headers.forEach((v,w)=>{p[w]=v}),c>0&&(p["X-Retry-Count"]=String(c));let g;try{g=await a(s.url.toString(),{method:s.method,headers:p,body:JSON.stringify(s.body,(v,w)=>typeof w=="bigint"?w.toString():w),signal:s.signal})}catch(v){if((v==null?void 0:v.name)==="AbortError"||(v==null?void 0:v.code)==="ABORT_ERR"||!Mw.includes(s.method))throw v;if(s.retryEnabled&&c{var d;let m="",p="",g="";const v=c==null?void 0:c.cause;if(v){var w,_,S,E;const N=(w=v==null?void 0:v.message)!==null&&w!==void 0?w:"",O=(_=v==null?void 0:v.code)!==null&&_!==void 0?_:"";m=`${(S=c==null?void 0:c.name)!==null&&S!==void 0?S:"FetchError"}: ${c==null?void 0:c.message}`,m+=` Caused by: ${(E=v==null?void 0:v.name)!==null&&E!==void 0?E:"Error"}: ${N}`,O&&(m+=` (${O})`),v!=null&&v.stack&&(m+=` ${v.stack}`)}else{var k;m=(k=c==null?void 0:c.stack)!==null&&k!==void 0?k:""}const C=this.url.toString().length;return(c==null?void 0:c.name)==="AbortError"||(c==null?void 0:c.code)==="ABORT_ERR"?(g="",p="Request was aborted (timeout or manual cancellation)",C>this.urlLengthLimit&&(p+=`. Note: Your request URL is ${C} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((v==null?void 0:v.name)==="HeadersOverflowError"||(v==null?void 0:v.code)==="UND_ERR_HEADERS_OVERFLOW")&&(g="",p="HTTP headers exceeded server limits (typically 16KB)",C>this.urlLengthLimit&&(p+=`. Your request URL is ${C} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${(d=c==null?void 0:c.name)!==null&&d!==void 0?d:"FetchError"}: ${c==null?void 0:c.message}`,details:m,hint:p,code:g},data:null,count:null,status:0,statusText:""}})),u.then(n,e)}async processResponse(n){var e=this;let s=null,a=null,l=null,u=n.status,c=n.statusText;if(n.ok){var d,m;if(e.method!=="HEAD"){var p;const w=await n.text();if(w!=="")if(e.headers.get("Accept")==="text/csv")a=w;else if(e.headers.get("Accept")&&(!((p=e.headers.get("Accept"))===null||p===void 0)&&p.includes("application/vnd.pgrst.plan+text")))a=w;else try{a=JSON.parse(w)}catch{if(s={message:w},a=null,e.shouldThrowOnError)throw new cv({message:w,details:"",hint:"",code:""})}}const g=(d=e.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),v=(m=n.headers.get("content-range"))===null||m===void 0?void 0:m.split("/");g&&v&&v.length>1&&(l=parseInt(v[1])),e.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(s={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,u=406,c="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{const g=await n.text();try{s=JSON.parse(g),Array.isArray(s)&&n.status===404&&(a=[],s=null,u=200,c="OK")}catch{n.status===404&&g===""?(u=204,c="No Content"):s={message:g}}if(s&&e.shouldThrowOnError)throw new cv(s)}return{success:s===null,error:s,data:a,count:l,status:u,statusText:c}}returns(){return this}overrideTypes(){return this}},lC=class extends oC{throwOnError(){return super.throwOnError()}select(n){let e=!1;const s=(n??"*").split("").map(a=>/\s/.test(a)&&!e?"":(a==='"'&&(e=!e),a)).join("");return this.url.searchParams.set("select",s),this.headers.append("Prefer","return=representation"),this}order(n,{ascending:e=!0,nullsFirst:s,foreignTable:a,referencedTable:l=a}={}){const u=l?`${l}.order`:"order",c=this.url.searchParams.get(u);return this.url.searchParams.set(u,`${c?`${c},`:""}${n}.${e?"asc":"desc"}${s===void 0?"":s?".nullsfirst":".nullslast"}`),this}limit(n,{foreignTable:e,referencedTable:s=e}={}){const a=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(a,`${n}`),this}range(n,e,{foreignTable:s,referencedTable:a=s}={}){const l=typeof a>"u"?"offset":`${a}.offset`,u=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(l,`${n}`),this.url.searchParams.set(u,`${e-n+1}`),this}abortSignal(n){return this.signal=n,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:n=!1,verbose:e=!1,settings:s=!1,buffers:a=!1,wal:l=!1,format:u="text"}={}){var c;const d=[n?"analyze":null,e?"verbose":null,s?"settings":null,a?"buffers":null,l?"wal":null].filter(Boolean).join("|"),m=(c=this.headers.get("Accept"))!==null&&c!==void 0?c:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${u}; for="${m}"; options=${d};`),u==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(n){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${n}`),this}};const dv=new RegExp("[,()]");var ta=class extends lC{throwOnError(){return super.throwOnError()}eq(n,e){return this.url.searchParams.append(n,`eq.${e}`),this}neq(n,e){return this.url.searchParams.append(n,`neq.${e}`),this}gt(n,e){return this.url.searchParams.append(n,`gt.${e}`),this}gte(n,e){return this.url.searchParams.append(n,`gte.${e}`),this}lt(n,e){return this.url.searchParams.append(n,`lt.${e}`),this}lte(n,e){return this.url.searchParams.append(n,`lte.${e}`),this}like(n,e){return this.url.searchParams.append(n,`like.${e}`),this}likeAllOf(n,e){return this.url.searchParams.append(n,`like(all).{${e.join(",")}}`),this}likeAnyOf(n,e){return this.url.searchParams.append(n,`like(any).{${e.join(",")}}`),this}ilike(n,e){return this.url.searchParams.append(n,`ilike.${e}`),this}ilikeAllOf(n,e){return this.url.searchParams.append(n,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(n,e){return this.url.searchParams.append(n,`ilike(any).{${e.join(",")}}`),this}regexMatch(n,e){return this.url.searchParams.append(n,`match.${e}`),this}regexIMatch(n,e){return this.url.searchParams.append(n,`imatch.${e}`),this}is(n,e){return this.url.searchParams.append(n,`is.${e}`),this}isDistinct(n,e){return this.url.searchParams.append(n,`isdistinct.${e}`),this}in(n,e){const s=Array.from(new Set(e)).map(a=>typeof a=="string"&&dv.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(n,`in.(${s})`),this}notIn(n,e){const s=Array.from(new Set(e)).map(a=>typeof a=="string"&&dv.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(n,`not.in.(${s})`),this}contains(n,e){return typeof e=="string"?this.url.searchParams.append(n,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(n,`cs.{${e.join(",")}}`):this.url.searchParams.append(n,`cs.${JSON.stringify(e)}`),this}containedBy(n,e){return typeof e=="string"?this.url.searchParams.append(n,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(n,`cd.{${e.join(",")}}`):this.url.searchParams.append(n,`cd.${JSON.stringify(e)}`),this}rangeGt(n,e){return this.url.searchParams.append(n,`sr.${e}`),this}rangeGte(n,e){return this.url.searchParams.append(n,`nxl.${e}`),this}rangeLt(n,e){return this.url.searchParams.append(n,`sl.${e}`),this}rangeLte(n,e){return this.url.searchParams.append(n,`nxr.${e}`),this}rangeAdjacent(n,e){return this.url.searchParams.append(n,`adj.${e}`),this}overlaps(n,e){return typeof e=="string"?this.url.searchParams.append(n,`ov.${e}`):this.url.searchParams.append(n,`ov.{${e.join(",")}}`),this}textSearch(n,e,{config:s,type:a}={}){let l="";a==="plain"?l="pl":a==="phrase"?l="ph":a==="websearch"&&(l="w");const u=s===void 0?"":`(${s})`;return this.url.searchParams.append(n,`${l}fts${u}.${e}`),this}match(n){return Object.entries(n).filter(([e,s])=>s!==void 0).forEach(([e,s])=>{this.url.searchParams.append(e,`eq.${s}`)}),this}not(n,e,s){return this.url.searchParams.append(n,`not.${e}.${s}`),this}or(n,{foreignTable:e,referencedTable:s=e}={}){const a=s?`${s}.or`:"or";return this.url.searchParams.append(a,`(${n})`),this}filter(n,e,s){return this.url.searchParams.append(n,`${e}.${s}`),this}},uC=class{constructor(n,{headers:e={},schema:s,fetch:a,urlLengthLimit:l=8e3,retry:u}){this.url=n,this.headers=new Headers(e),this.schema=s,this.fetch=a,this.urlLengthLimit=l,this.retry=u}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(n,e){const{head:s=!1,count:a}=e??{},l=s?"HEAD":"GET";let u=!1;const c=(n??"*").split("").map(p=>/\s/.test(p)&&!u?"":(p==='"'&&(u=!u),p)).join(""),{url:d,headers:m}=this.cloneRequestState();return d.searchParams.set("select",c),a&&m.append("Prefer",`count=${a}`),new ta({method:l,url:d,headers:m,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(n,{count:e,defaultToNull:s=!0}={}){var a;const l="POST",{url:u,headers:c}=this.cloneRequestState();if(e&&c.append("Prefer",`count=${e}`),s||c.append("Prefer","missing=default"),Array.isArray(n)){const d=n.reduce((m,p)=>m.concat(Object.keys(p)),[]);if(d.length>0){const m=[...new Set(d)].map(p=>`"${p}"`);u.searchParams.set("columns",m.join(","))}}return new ta({method:l,url:u,headers:c,schema:this.schema,body:n,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(n,{onConflict:e,ignoreDuplicates:s=!1,count:a,defaultToNull:l=!0}={}){var u;const c="POST",{url:d,headers:m}=this.cloneRequestState();if(m.append("Prefer",`resolution=${s?"ignore":"merge"}-duplicates`),e!==void 0&&d.searchParams.set("on_conflict",e),a&&m.append("Prefer",`count=${a}`),l||m.append("Prefer","missing=default"),Array.isArray(n)){const p=n.reduce((g,v)=>g.concat(Object.keys(v)),[]);if(p.length>0){const g=[...new Set(p)].map(v=>`"${v}"`);d.searchParams.set("columns",g.join(","))}}return new ta({method:c,url:d,headers:m,schema:this.schema,body:n,fetch:(u=this.fetch)!==null&&u!==void 0?u:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(n,{count:e}={}){var s;const a="PATCH",{url:l,headers:u}=this.cloneRequestState();return e&&u.append("Prefer",`count=${e}`),new ta({method:a,url:l,headers:u,schema:this.schema,body:n,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:n}={}){var e;const s="DELETE",{url:a,headers:l}=this.cloneRequestState();return n&&l.append("Prefer",`count=${n}`),new ta({method:s,url:a,headers:l,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function Or(n){"@babel/helpers - typeof";return Or=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Or(n)}function cC(n,e){if(Or(n)!="object"||!n)return n;var s=n[Symbol.toPrimitive];if(s!==void 0){var a=s.call(n,e);if(Or(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function hC(n){var e=cC(n,"string");return Or(e)=="symbol"?e:e+""}function dC(n,e,s){return(e=hC(e))in n?Object.defineProperty(n,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):n[e]=s,n}function fv(n,e){var s=Object.keys(n);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(n);e&&(a=a.filter(function(l){return Object.getOwnPropertyDescriptor(n,l).enumerable})),s.push.apply(s,a)}return s}function yl(n){for(var e=1;e0?this.fetch=(p,g)=>{const v=new AbortController,w=setTimeout(()=>v.abort(),u),_=g==null?void 0:g.signal;if(_){if(_.aborted)return clearTimeout(w),m(p,g);const S=()=>{clearTimeout(w),v.abort()};return _.addEventListener("abort",S,{once:!0}),m(p,yl(yl({},g),{},{signal:v.signal})).finally(()=>{clearTimeout(w),_.removeEventListener("abort",S)})}return m(p,yl(yl({},g),{},{signal:v.signal})).finally(()=>clearTimeout(w))}:this.fetch=m,this.retry=d}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new uC(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new Uw(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,s={},{head:a=!1,get:l=!1,count:u}={}){var c;let d;const m=new URL(`${this.url}/rpc/${e}`);let p;const g=_=>_!==null&&typeof _=="object"&&(!Array.isArray(_)||_.some(g)),v=a&&Object.values(s).some(g);v?(d="POST",p=s):a||l?(d=a?"HEAD":"GET",Object.entries(s).filter(([_,S])=>S!==void 0).map(([_,S])=>[_,Array.isArray(S)?`{${S.join(",")}}`:`${S}`]).forEach(([_,S])=>{m.searchParams.append(_,S)})):(d="POST",p=s);const w=new Headers(this.headers);return v?w.set("Prefer",u?`count=${u},return=minimal`:"return=minimal"):u&&w.set("Prefer",`count=${u}`),new ta({method:d,url:m,headers:w,schema:this.schemaName,body:p,fetch:(c=this.fetch)!==null&&c!==void 0?c:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class mC{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};const s=globalThis;if(typeof globalThis<"u"&&typeof s.WebSocket<"u")return{type:"native",wsConstructor:s.WebSocket};const a=typeof global<"u"?global:void 0;if(a&&typeof a.WebSocket<"u")return{type:"native",wsConstructor:a.WebSocket};if(typeof globalThis<"u"&&typeof s.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&s.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const l=globalThis.process;if(l){const u=l.versions;if(u&&u.node)return{type:"unsupported",error:"Node.js detected but native WebSocket not found.",workaround:"Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let s=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(s+=` Suggested solution: ${e.workaround}`),new Error(s)}static isWebSocketSupported(){try{return this.detectEnvironment().type==="native"}catch{return!1}}}const pC="2.110.2",gC=`realtime-js/${pC}`,yC="1.0.0",Bw="2.0.0",vC=Bw,bC=1e4,wC=100,ki={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Lw={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},Cd={connecting:"connecting",closing:"closing",closed:"closed"};class xC{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,s){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return s(this._binaryEncodeUserBroadcastPush(e));let a=[e.join_ref,e.ref,e.topic,e.event,e.payload];return s(JSON.stringify(a))}_binaryEncodeUserBroadcastPush(e){var s;return this._isArrayBuffer((s=e.payload)===null||s===void 0?void 0:s.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var s,a;const l=(a=(s=e.payload)===null||s===void 0?void 0:s.payload)!==null&&a!==void 0?a:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,l)}_encodeJsonUserBroadcastPush(e){var s,a;const l=(a=(s=e.payload)===null||s===void 0?void 0:s.payload)!==null&&a!==void 0?a:{},c=new TextEncoder().encode(JSON.stringify(l)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,c)}_encodeUserBroadcastPush(e,s,a){var l,u;const c=e.topic,d=(l=e.ref)!==null&&l!==void 0?l:"",m=(u=e.join_ref)!==null&&u!==void 0?u:"",p=e.payload.event,g=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},v=Object.keys(g).length===0?"":JSON.stringify(g);if(m.length>255)throw new Error(`joinRef length ${m.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`ref length ${d.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`topic length ${c.length} exceeds maximum of 255`);if(p.length>255)throw new Error(`userEvent length ${p.length} exceeds maximum of 255`);if(v.length>255)throw new Error(`metadata length ${v.length} exceeds maximum of 255`);const w=this.USER_BROADCAST_PUSH_META_LENGTH+m.length+d.length+c.length+p.length+v.length,_=new ArrayBuffer(this.HEADER_LENGTH+w);let S=new DataView(_),E=0;S.setUint8(E++,this.KINDS.userBroadcastPush),S.setUint8(E++,m.length),S.setUint8(E++,d.length),S.setUint8(E++,c.length),S.setUint8(E++,p.length),S.setUint8(E++,v.length),S.setUint8(E++,s),Array.from(m,C=>S.setUint8(E++,C.charCodeAt(0))),Array.from(d,C=>S.setUint8(E++,C.charCodeAt(0))),Array.from(c,C=>S.setUint8(E++,C.charCodeAt(0))),Array.from(p,C=>S.setUint8(E++,C.charCodeAt(0))),Array.from(v,C=>S.setUint8(E++,C.charCodeAt(0)));var k=new Uint8Array(_.byteLength+a.byteLength);return k.set(new Uint8Array(_),0),k.set(new Uint8Array(a),_.byteLength),k.buffer}decode(e,s){if(this._isArrayBuffer(e)){let a=this._binaryDecode(e);return s(a)}if(typeof e=="string"){const a=JSON.parse(e),[l,u,c,d,m]=a;return s({join_ref:l,ref:u,topic:c,event:d,payload:m})}return s({})}_binaryDecode(e){const s=new DataView(e),a=s.getUint8(0),l=new TextDecoder;switch(a){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,s,l)}}_decodeUserBroadcast(e,s,a){const l=s.getUint8(1),u=s.getUint8(2),c=s.getUint8(3),d=s.getUint8(4);let m=this.HEADER_LENGTH+4;const p=a.decode(e.slice(m,m+l));m=m+l;const g=a.decode(e.slice(m,m+u));m=m+u;const v=a.decode(e.slice(m,m+c));m=m+c;const w=e.slice(m,e.byteLength),_=d===this.JSON_ENCODING?JSON.parse(a.decode(w)):w,S={type:this.BROADCAST_EVENT,event:g,payload:_};return c>0&&(S.meta=JSON.parse(v)),{join_ref:null,ref:null,topic:p,event:this.BROADCAST_EVENT,payload:S}}_isArrayBuffer(e){var s;return e instanceof ArrayBuffer||((s=e==null?void 0:e.constructor)===null||s===void 0?void 0:s.name)==="ArrayBuffer"}_pick(e,s){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([a])=>s.includes(a)))}}var Pe;(function(n){n.abstime="abstime",n.bool="bool",n.date="date",n.daterange="daterange",n.float4="float4",n.float8="float8",n.int2="int2",n.int4="int4",n.int4range="int4range",n.int8="int8",n.int8range="int8range",n.json="json",n.jsonb="jsonb",n.money="money",n.numeric="numeric",n.oid="oid",n.reltime="reltime",n.text="text",n.time="time",n.timestamp="timestamp",n.timestamptz="timestamptz",n.timetz="timetz",n.tsrange="tsrange",n.tstzrange="tstzrange"})(Pe||(Pe={}));const mv=(n,e,s={})=>{var a;const l=(a=s.skipTypes)!==null&&a!==void 0?a:[];return e?Object.keys(e).reduce((u,c)=>(u[c]=_C(c,n,e,l),u),{}):{}},_C=(n,e,s,a)=>{const l=e.find(d=>d.name===n),u=l==null?void 0:l.type,c=s[n];return u&&!a.includes(u)?zw(u,c):kd(c)},zw=(n,e)=>{if(n.charAt(0)==="_"){const s=n.slice(1,n.length);return AC(e,s)}switch(n){case Pe.bool:return SC(e);case Pe.float4:case Pe.float8:case Pe.int2:case Pe.int4:case Pe.int8:case Pe.numeric:case Pe.oid:return TC(e);case Pe.json:case Pe.jsonb:return EC(e);case Pe.timestamp:return RC(e);case Pe.abstime:case Pe.date:case Pe.daterange:case Pe.int4range:case Pe.int8range:case Pe.money:case Pe.reltime:case Pe.text:case Pe.time:case Pe.timestamptz:case Pe.timetz:case Pe.tsrange:case Pe.tstzrange:return kd(e);default:return kd(e)}},kd=n=>n,SC=n=>{switch(n){case"t":return!0;case"f":return!1;default:return n}},TC=n=>{if(typeof n=="string"){const e=parseFloat(n);if(!Number.isNaN(e))return e}return n},EC=n=>{if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n},AC=(n,e)=>{if(typeof n!="string")return n;const s=n.length-1,a=n[s];if(n[0]==="{"&&a==="}"){let u;const c=n.slice(1,s);try{u=JSON.parse("["+c+"]")}catch{u=c?c.split(","):[]}return u.map(d=>zw(e,d))}return n},RC=n=>typeof n=="string"?n.replace(" ","T"):n,Vw=n=>{const e=new URL(n);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var _r=n=>typeof n=="function"?n:function(){return n},CC=typeof self<"u"?self:null,na=typeof window<"u"?window:null,Tn=CC||na||globalThis,kC="2.0.0",jC=1e4,OC=1e3,An={connecting:0,open:1,closing:2,closed:3},Nt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Wn={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},jd={longpoll:"longpoll",websocket:"websocket"},NC={complete:4},Od="base64url.bearer.phx.",vl=class{constructor(n,e,s,a){this.channel=n,this.event=e,this.payload=s||function(){return{}},this.receivedResp=null,this.timeout=a,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(n){this.timeout=n,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(n,e){return this.hasReceived(n)&&e(this.receivedResp.response),this.recHooks.push({status:n,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:n,response:e,_ref:s}){this.recHooks.filter(a=>a.status===n).forEach(a=>a.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,n=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=n,this.matchReceive(n)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(n){return this.receivedResp&&this.receivedResp.status===n}trigger(n,e){this.channel.trigger(this.refEvent,{status:n,response:e})}},Pw=class{constructor(n,e){this.callback=n,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},DC=class{constructor(n,e,s){this.state=Nt.closed,this.topic=n,this.params=_r(e||{}),this.socket=s,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new vl(this,Wn.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Pw(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Nt.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this.joinPush.receive("error",a=>{this.state=Nt.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,a),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Nt.closed,this.socket.remove(this)}),this.onError(a=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,a),this.isJoining()&&this.joinPush.reset(),this.state=Nt.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new vl(this,Wn.leave,_r({}),this.timeout).send(),this.state=Nt.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Wn.reply,(a,l)=>{this.trigger(this.replyEventName(l),a)})}join(n=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=n,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(n=>n.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Nt.closed,this.bindings=[]}onClose(n){this.on(Wn.close,n)}onError(n){return this.on(Wn.error,e=>n(e))}on(n,e){let s=this.bindingRef++;return this.bindings.push({event:n,ref:s,callback:e}),s}off(n,e){this.bindings=this.bindings.filter(s=>!(s.event===n&&(typeof e>"u"||e===s.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(n,e,s=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${n}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let a=new vl(this,n,function(){return e},s);return this.canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}leave(n=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Nt.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Wn.close,"leave")},s=new vl(this,Wn.leave,_r({}),n);return s.receive("ok",()=>e()).receive("timeout",()=>e()),s.send(),this.canPush()||s.trigger("ok",{}),s}onMessage(n,e,s){return e}filterBindings(n,e,s){return!0}isMember(n,e,s,a){return this.topic!==n?!1:a&&a!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:n,event:e,payload:s,joinRef:a}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(n=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Nt.joining,this.joinPush.resend(n))}trigger(n,e,s,a){let l=this.onMessage(n,e,s,a);if(e&&!l)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let u=this.bindings.filter(c=>c.event===n&&this.filterBindings(c,e,s));for(let c=0;cm.abort(),l),d.signal=m.signal),Tn.fetch(e,d).then(p=>p.text()).then(p=>this.parseJSON(p)).then(p=>c&&c(p)).catch(p=>{p.name==="AbortError"&&u?u():c&&c(null)}),m}static xdomainRequest(n,e,s,a,l,u,c){return n.timeout=l,n.open(e,s),n.onload=()=>{let d=this.parseJSON(n.responseText);c&&c(d)},u&&(n.ontimeout=u),n.onprogress=()=>{},n.send(a),n}static xhrRequest(n,e,s,a,l,u,c,d){n.open(e,s,!0),n.timeout=u;for(let[m,p]of Object.entries(a))n.setRequestHeader(m,p);return n.onerror=()=>d&&d(null),n.onreadystatechange=()=>{if(n.readyState===NC.complete&&d){let m=this.parseJSON(n.responseText);d(m)}},c&&(n.ontimeout=c),n.send(l),n}static parseJSON(n){if(!n||n==="")return null;try{return JSON.parse(n)}catch{return console&&console.log("failed to parse JSON response",n),null}}static serialize(n,e){let s=[];for(var a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;let l=e?`${e}[${a}]`:a,u=n[a];typeof u=="object"?s.push(this.serialize(u,l)):s.push(encodeURIComponent(l)+"="+encodeURIComponent(u))}return s.join("&")}static appendParams(n,e){if(Object.keys(e).length===0)return n;let s=n.match(/\?/)?"&":"?";return`${n}${s}${this.serialize(e)}`}},MC=n=>{let e="",s=new Uint8Array(n),a=s.byteLength;for(let l=0;lthis.poll(),0)}normalizeEndpoint(n){return n.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+jd.websocket),"$1/"+jd.longpoll)}endpointURL(){return Il.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(n,e,s){this.close(n,e,s),this.readyState=An.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===An.open||this.readyState===An.connecting}poll(){const n={Accept:"application/json"};this.authToken&&(n["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",n,null,()=>this.ontimeout(),e=>{if(e){var{status:s,token:a,messages:l}=e;if(s===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=a}else s=0;switch(s){case 200:l.forEach(u=>{setTimeout(()=>this.onmessage({data:u}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=An.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${s}`)}})}send(n){typeof n!="string"&&(n=MC(n)),this.currentBatch?this.currentBatch.push(n):this.awaitingBatchAck?this.batchBuffer.push(n):(this.currentBatch=[n],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(n){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},n.join(` `),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(n,e,s){for(let l of this.reqs)l.abort();this.readyState=An.closed;let a=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:n,reason:e,wasClean:s});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",a)):this.onclose(a)}ajax(n,e,s,a,l){let u,c=()=>{this.reqs.delete(u),a()};u=Il.request(n,this.endpointURL(),e,s,this.timeout,c,d=>{this.reqs.delete(u),this.isActive()&&l(d)}),this.reqs.add(u)}},UC=class pr{constructor(e,s={}){let a=s.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(a.state,l=>{let{onJoin:u,onLeave:c,onSync:d}=this.caller;this.joinRef=this.channel.joinRef(),this.state=pr.syncState(this.state,l,u,c),this.pendingDiffs.forEach(m=>{this.state=pr.syncDiff(this.state,m,u,c)}),this.pendingDiffs=[],d()}),this.channel.on(a.diff,l=>{let{onJoin:u,onLeave:c,onSync:d}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(l):(this.state=pr.syncDiff(this.state,l,u,c),d())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return pr.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,s,a,l){let u=this.clone(e),c={},d={};return this.map(u,(m,p)=>{s[m]||(d[m]=p)}),this.map(s,(m,p)=>{let g=u[m];if(g){let v=p.metas.map(E=>E.phx_ref),w=g.metas.map(E=>E.phx_ref),_=p.metas.filter(E=>w.indexOf(E.phx_ref)<0),S=g.metas.filter(E=>v.indexOf(E.phx_ref)<0);_.length>0&&(c[m]=p,c[m].metas=_),S.length>0&&(d[m]=this.clone(g),d[m].metas=S)}else c[m]=p}),this.syncDiff(u,{joins:c,leaves:d},a,l)}static syncDiff(e,s,a,l){let{joins:u,leaves:c}=this.clone(s);return a||(a=function(){}),l||(l=function(){}),this.map(u,(d,m)=>{let p=e[d];if(e[d]=this.clone(m),p){let g=e[d].metas.map(w=>w.phx_ref),v=p.metas.filter(w=>g.indexOf(w.phx_ref)<0);e[d].metas.unshift(...v)}a(d,p,m)}),this.map(c,(d,m)=>{let p=e[d];if(!p)return;let g=m.metas.map(v=>v.phx_ref);p.metas=p.metas.filter(v=>g.indexOf(v.phx_ref)<0),l(d,p,m),p.metas.length===0&&delete e[d]}),e}static list(e,s){return s||(s=function(a,l){return l}),this.map(e,(a,l)=>s(a,l))}static map(e,s){return Object.getOwnPropertyNames(e).map(a=>s(a,e[a]))}static clone(e){return JSON.parse(JSON.stringify(e))}},bl={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(n,e){if(n.payload.constructor===ArrayBuffer)return e(this.binaryEncode(n));{let s=[n.join_ref,n.ref,n.topic,n.event,n.payload];return e(JSON.stringify(s))}},decode(n,e){if(n.constructor===ArrayBuffer)return e(this.binaryDecode(n));{let[s,a,l,u,c]=JSON.parse(n);return e({join_ref:s,ref:a,topic:l,event:u,payload:c})}},binaryEncode(n){let{join_ref:e,ref:s,event:a,topic:l,payload:u}=n,c=this.META_LENGTH+e.length+s.length+l.length+a.length,d=new ArrayBuffer(this.HEADER_LENGTH+c),m=new DataView(d),p=0;m.setUint8(p++,this.KINDS.push),m.setUint8(p++,e.length),m.setUint8(p++,s.length),m.setUint8(p++,l.length),m.setUint8(p++,a.length),Array.from(e,v=>m.setUint8(p++,v.charCodeAt(0))),Array.from(s,v=>m.setUint8(p++,v.charCodeAt(0))),Array.from(l,v=>m.setUint8(p++,v.charCodeAt(0))),Array.from(a,v=>m.setUint8(p++,v.charCodeAt(0)));var g=new Uint8Array(d.byteLength+u.byteLength);return g.set(new Uint8Array(d),0),g.set(new Uint8Array(u),d.byteLength),g.buffer},binaryDecode(n){let e=new DataView(n),s=e.getUint8(0),a=new TextDecoder;switch(s){case this.KINDS.push:return this.decodePush(n,e,a);case this.KINDS.reply:return this.decodeReply(n,e,a);case this.KINDS.broadcast:return this.decodeBroadcast(n,e,a)}},decodePush(n,e,s){let a=e.getUint8(1),l=e.getUint8(2),u=e.getUint8(3),c=this.HEADER_LENGTH+this.META_LENGTH-1,d=s.decode(n.slice(c,c+a));c=c+a;let m=s.decode(n.slice(c,c+l));c=c+l;let p=s.decode(n.slice(c,c+u));c=c+u;let g=n.slice(c,n.byteLength);return{join_ref:d,ref:null,topic:m,event:p,payload:g}},decodeReply(n,e,s){let a=e.getUint8(1),l=e.getUint8(2),u=e.getUint8(3),c=e.getUint8(4),d=this.HEADER_LENGTH+this.META_LENGTH,m=s.decode(n.slice(d,d+a));d=d+a;let p=s.decode(n.slice(d,d+l));d=d+l;let g=s.decode(n.slice(d,d+u));d=d+u;let v=s.decode(n.slice(d,d+c));d=d+c;let w=n.slice(d,n.byteLength),_={status:v,response:w};return{join_ref:m,ref:p,topic:g,event:Wn.reply,payload:_}},decodeBroadcast(n,e,s){let a=e.getUint8(1),l=e.getUint8(2),u=this.HEADER_LENGTH+2,c=s.decode(n.slice(u,u+a));u=u+a;let d=s.decode(n.slice(u,u+l));u=u+l;let m=n.slice(u,n.byteLength);return{join_ref:null,ref:null,topic:c,event:d,payload:m}}},BC=class{constructor(n,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||jC,this.transport=e.transport||Tn.WebSocket||Js,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null;let s=null;try{s=Tn&&Tn.sessionStorage}catch{}this.sessionStore=e.sessionStorage||s,this.establishedConnections=0,this.defaultEncoder=bl.encode.bind(bl),this.defaultDecoder=bl.decode.bind(bl),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Js?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let a=null;na&&na.addEventListener&&(na.addEventListener("pagehide",l=>{this.conn&&(this.disconnect(),a=this.connectClock)}),na.addEventListener("pageshow",l=>{a===this.connectClock&&(a=null,this.connect())}),na.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=l=>e.rejoinAfterMs?e.rejoinAfterMs(l):[1e3,2e3,5e3][l-1]||1e4,this.reconnectAfterMs=l=>e.reconnectAfterMs?e.reconnectAfterMs(l):[10,50,100,150,200,250,500,1e3,2e3][l-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(l,u,c)=>{console.log(`${l}: ${u}`,c)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=_r(e.params||{}),this.endPoint=`${n}/${jd.websocket}`,this.vsn=e.vsn||kC,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Pw(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return Js}replaceTransport(n){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=n}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let n=Il.appendParams(Il.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return n.charAt(0)!=="/"?n:n.charAt(1)==="/"?`${this.protocol()}:${n}`:`${this.protocol()}://${location.host}${n}`}disconnect(n,e,s){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,n&&n()},e,s)}connect(n){n&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=_r(n)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Js?this.connectWithFallback(Js,this.longPollFallbackMs):this.transportConnect())}log(n,e,s){this.logger&&this.logger(n,e,s)}hasLogger(){return this.logger!==null}onOpen(n){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,n]),e}onClose(n){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,n]),e}onError(n){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,n]),e}onMessage(n){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,n]),e}onHeartbeat(n){this.heartbeatCallback=n}ping(n){if(!this.isConnected())return!1;let e=this.makeRef(),s=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let a=this.onMessage(l=>{l.ref===e&&(this.off([a]),n(Date.now()-s))});return!0}transportName(n){switch(n){case Js:return"LongPoll";default:return n.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let n;this.authToken&&(n=["phoenix",`${Od}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),n),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(n){return this.sessionStore&&this.sessionStore.getItem(n)}storeSession(n,e){this.sessionStore&&this.sessionStore.setItem(n,e)}connectWithFallback(n,e=2500){clearTimeout(this.fallbackTimer);let s=!1,a=!0,l,u,c=this.transportName(n),d=m=>{this.log("transport",`falling back to ${c}...`,m),this.off([l,u]),a=!1,this.replaceTransport(n),this.transportConnect()};if(this.getSession(`phx:fallback:${c}`))return d("memorized");this.fallbackTimer=setTimeout(d,e),u=this.onError(m=>{this.log("transport","error",m),a&&!s&&(clearTimeout(this.fallbackTimer),d(m))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(s=!0,!a){let m=this.transportName(n);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${m}`,"true"),this.log("transport",`established ${m} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(d,e),this.ping(m=>{this.log("transport","connected to primary after",m),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(n){this.log("error","error in heartbeat callback",n)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),OC,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(n,e,s){if(!this.conn)return n&&n();const a=this.conn;this.waitForBufferDone(a,()=>{e?a.close(e,s||""):a.close(),this.waitForSocketClosed(a,()=>{this.conn===a&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),n&&n()})})}waitForBufferDone(n,e,s=1){if(s===5||!n.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(n,e,s+1)},150*s)}waitForSocketClosed(n,e,s=1){if(s===5||n.readyState===An.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(n,e,s+1)},150*s)}onConnClose(n){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",n),this.triggerChanError(n),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",n)}onConnError(n){this.hasLogger()&&this.log("transport","error",n);let e=this.transport,s=this.establishedConnections;this.triggerStateCallbacks("error",n,e,s),(e===this.transport||s>0)&&this.triggerChanError(n)}triggerChanError(n){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(Wn.error,n)})}connectionState(){switch(this.conn&&this.conn.readyState){case An.connecting:return"connecting";case An.open:return"open";case An.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(n){this.off(n.stateChangeRefs),this.channels=this.channels.filter(e=>e!==n)}off(n){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([s])=>n.indexOf(s)===-1)}channel(n,e={}){let s=new DC(n,e,this);return this.channels.push(s),s}push(n){if(this.hasLogger()){let{topic:e,event:s,payload:a,ref:l,join_ref:u}=n;this.log("push",`${e} ${s} (${u}, ${l})`,a)}this.isConnected()?this.encode(n,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(n,e=>this.conn.send(e)))}makeRef(){let n=this.ref+1;return n===this.ref?this.ref=0:this.ref=n,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(n){this.log("error","error in heartbeat callback",n)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(n){this.log("error","error in heartbeat callback",n)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(n=>n()),this.sendBuffer=[])}onConnMessage(n){this.decode(n.data,e=>{let{topic:s,event:a,payload:l,ref:u,join_ref:c}=e;if(u&&u===this.pendingHeartbeatRef){const d=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(l.status==="ok"?"ok":"error",d)}catch(m){this.log("error","error in heartbeat callback",m)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${l.status||""} ${s} ${a} ${u&&"("+u+")"||""}`.trim(),l);for(let d=0;d{try{a(...e)}catch(l){this.log("error",`error in ${n} callback`,l)}})}catch(s){this.log("error",`error triggering ${n} callbacks`,s)}}leaveOpenTopic(n){let e=this.channels.find(s=>s.topic===n&&(s.isJoined()||s.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${n}"`),e.leave())}};class Sr{constructor(e,s){const a=zC(s);this.presence=new UC(e.getChannel(),a),this.presence.onJoin((l,u,c)=>{const d=Sr.onJoinPayload(l,u,c);e.getChannel().trigger("presence",d)}),this.presence.onLeave((l,u,c)=>{const d=Sr.onLeavePayload(l,u,c);e.getChannel().trigger("presence",d)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return Sr.transformState(this.presence.state)}static transformState(e){return e=LC(e),Object.getOwnPropertyNames(e).reduce((s,a)=>{const l=e[a];return s[a]=Ml(l),s},{})}static onJoinPayload(e,s,a){const l=pv(s),u=Ml(a);return{event:"join",key:e,currentPresences:l,newPresences:u}}static onLeavePayload(e,s,a){const l=pv(s),u=Ml(a);return{event:"leave",key:e,currentPresences:l,leftPresences:u}}}function Ml(n){return n.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function LC(n){return JSON.parse(JSON.stringify(n))}function zC(n){return(n==null?void 0:n.events)&&{events:n.events}}function pv(n){return n!=null&&n.metas?Ml(n):[]}var gv;(function(n){n.SYNC="sync",n.JOIN="join",n.LEAVE="leave"})(gv||(gv={}));class VC{get state(){return this.presenceAdapter.state}constructor(e,s){this.channel=e,this.presenceAdapter=new Sr(this.channel.channelAdapter,s)}}function PC(n){if(n instanceof Error)return n;if(typeof n=="string")return new Error(n);if(n&&typeof n=="object"){const e=n;if(typeof e.code=="number"){const s=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${s}`,{cause:n})}return new Error("channel error: transport failure",{cause:n})}return new Error("channel error: connection lost")}class HC{constructor(e,s,a){const l=$C(a);this.channel=e.getSocket().channel(s,l),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,s){return this.channel.on(e,s)}off(e,s){this.channel.off(e,s)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,s,a){let l;try{l=this.channel.push(e,s,a)}catch{throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>wC){const u=this.channel.pushBuffer.shift();u.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${u.event}`,u.payload())}return l}updateJoinPayload(e){const s=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},s),e)}canPush(){return this.socket.isConnected()&&this.state===ki.joined}isJoined(){return this.state===ki.joined}isJoining(){return this.state===ki.joining}isClosed(){return this.state===ki.closed}isLeaving(){return this.state===ki.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function $C(n){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},n.config)}}const qC=/[,()"\\]/,GC=n=>qC.test(n)||n!==n.trim(),IC=n=>`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,yv=n=>{const e=n===null?"null":String(n);return GC(e)?IC(e):e},KC=n=>n===null?"null":String(n),FC=(n,e)=>{if(n==="in"){const s=Array.isArray(e)?e:[e];if(s.length===0)throw new Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(s)).map(l=>yv(l)).join(",")})`}return n==="is"?`is.${KC(e)}`:`${n}.${yv(e)}`};class YC{constructor(){this.filters=[]}add(e,s,a,l=!1){const u=l?"not.":"";return this.filters.push(`${e}=${u}${FC(s,a)}`),this}eq(e,s){return this.add(e,"eq",s)}neq(e,s){return this.add(e,"neq",s)}gt(e,s){return this.add(e,"gt",s)}gte(e,s){return this.add(e,"gte",s)}lt(e,s){return this.add(e,"lt",s)}lte(e,s){return this.add(e,"lte",s)}in(e,s){return this.add(e,"in",s)}like(e,s){return this.add(e,"like",s)}ilike(e,s){return this.add(e,"ilike",s)}match(e,s){return this.add(e,"match",s)}imatch(e,s){return this.add(e,"imatch",s)}is(e,s){return this.add(e,"is",s)}isDistinct(e,s){return this.add(e,"isdistinct",s)}not(e,s,a){return this.add(e,s,a,!0)}build(){return this.filters.join(",")}toString(){return this.build()}}var vv;(function(n){n.ALL="*",n.INSERT="INSERT",n.UPDATE="UPDATE",n.DELETE="DELETE"})(vv||(vv={}));var oa;(function(n){n.BROADCAST="broadcast",n.PRESENCE="presence",n.POSTGRES_CHANGES="postgres_changes",n.SYSTEM="system"})(oa||(oa={}));var ei;(function(n){n.SUBSCRIBED="SUBSCRIBED",n.TIMED_OUT="TIMED_OUT",n.CLOSED="CLOSED",n.CHANNEL_ERROR="CHANNEL_ERROR"})(ei||(ei={}));class Tr{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,s={config:{}},a){var l,u;if(this.topic=e,this.params=s,this.socket=a,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},s.config),this.channelAdapter=new HC(this.socket.socketAdapter,e,this.params),this.presence=new VC(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Vw(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((u=(l=this.params.config)===null||l===void 0?void 0:l.broadcast)===null||u===void 0)&&u.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,s=this.timeout){var a,l,u;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:c,presence:d,private:m}}=this.params,p=(l=(a=this.bindings.postgres_changes)===null||a===void 0?void 0:a.map(_=>_.filter))!==null&&l!==void 0?l:[],g=!!this.bindings[oa.PRESENCE]&&this.bindings[oa.PRESENCE].length>0||((u=this.params.config.presence)===null||u===void 0?void 0:u.enabled)===!0,v={},w={broadcast:c,presence:Object.assign(Object.assign({},d),{enabled:g}),postgres_changes:p,private:m};this.socket.accessTokenValue&&(v.access_token=this.socket.accessTokenValue),this._onError(_=>{e==null||e(ei.CHANNEL_ERROR,PC(_))}),this._onClose(()=>e==null?void 0:e(ei.CLOSED)),this.updateJoinPayload(Object.assign({config:w},v)),this._updateFilterMessage(),this.channelAdapter.subscribe(s).receive("ok",async({postgres_changes:_})=>{if(this.socket._isManualToken()||this.socket.setAuth(),_===void 0){e==null||e(ei.SUBSCRIBED);return}this._updatePostgresBindings(_,e)}).receive("error",_=>{this.state=ki.errored;const S=Object.values(_).join(", ")||"error";e==null||e(ei.CHANNEL_ERROR,new Error(S,{cause:_}))}).receive("timeout",()=>{e==null||e(ei.TIMED_OUT)})}return this}_updatePostgresBindings(e,s){var a;const l=this.bindings.postgres_changes,u=(a=l==null?void 0:l.length)!==null&&a!==void 0?a:0,c=[];for(let d=0;d{var c,d,m;const p=this.channelAdapter.push(e.type,e,s.timeout||this.timeout);e.type==="broadcast"&&!(!((m=(d=(c=this.params)===null||c===void 0?void 0:c.config)===null||d===void 0?void 0:d.broadcast)===null||m===void 0)&&m.ack)&&u("ok"),p.receive("ok",()=>u("ok")),p.receive("error",()=>u("error")),p.receive("timeout",()=>u("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(s=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>s("ok")).receive("timeout",()=>s("timed out")).receive("error",()=>s("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,s,a){const l=new AbortController,u=setTimeout(()=>l.abort(),a),c=await this.socket.fetch(e,Object.assign(Object.assign({},s),{signal:l.signal}));return clearTimeout(u),c}_on(e,s,a){const l=e.toLocaleLowerCase(),u=s==null?void 0:s.filter;(u instanceof YC||typeof u=="object"&&u!==null&&typeof u.build=="function")&&(s=Object.assign(Object.assign({},s),{filter:u.build()}));const c=this.channelAdapter.on(e,a),d={type:l,filter:s,callback:a,ref:c};return this.bindings[l]?this.bindings[l].push(d):this.bindings[l]=[d],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,s,a)=>{var l,u,c,d,m,p,g;const v=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(v,a))return!1;const w=(l=this.bindings[v])===null||l===void 0?void 0:l.find(_=>_.ref===e.ref);if(!w)return!0;if(["broadcast","presence","postgres_changes"].includes(v))if("id"in w){const _=w.id,S=(u=w.filter)===null||u===void 0?void 0:u.event;return _&&((c=s.ids)===null||c===void 0?void 0:c.includes(_))&&(S==="*"||(S==null?void 0:S.toLocaleLowerCase())===((d=s.data)===null||d===void 0?void 0:d.type.toLocaleLowerCase()))}else{const _=(p=(m=w==null?void 0:w.filter)===null||m===void 0?void 0:m.event)===null||p===void 0?void 0:p.toLocaleLowerCase();return _==="*"||_===((g=s==null?void 0:s.event)===null||g===void 0?void 0:g.toLocaleLowerCase())}else return w.type.toLocaleLowerCase()===v})}_notThisChannelEvent(e,s){const{close:a,error:l,leave:u,join:c}=Lw;return s&&[a,l,u,c].includes(e)&&s!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,s,a)=>{if(typeof s=="object"&&"ids"in s){const l=s.data,{schema:u,table:c,commit_timestamp:d,type:m,errors:p}=l;return Object.assign(Object.assign({},{schema:u,table:c,commit_timestamp:d,eventType:m,new:{},old:{},errors:p}),this._getPayloadRecords(l))}return s})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const s in e.bindings)for(const a of e.bindings[s])this._on(a.type,a.filter,a.callback)}static isFilterValueEqual(e,s){return(e??void 0)===(s??void 0)}_getPayloadRecords(e){const s={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(s.new=mv(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(s.old=mv(e.columns,e.old_record)),s}}class XC{constructor(e,s){this.socket=new BC(e,s)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,s,a,l=1e4){return new Promise(u=>{setTimeout(()=>u("timeout"),l),this.socket.disconnect(()=>{e(),u("ok")},s,a)})}push(e){this.socket.push(e)}log(e,s,a){this.socket.log(e,s,a)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Cd.connecting}isDisconnecting(){return this.socket.connectionState()==Cd.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const bv={HEARTBEAT_INTERVAL:25e3},JC=[1e3,2e3,5e3,1e4],QC=1e4;function ZC(){const n=new Map;return{get length(){return n.size},clear(){n.clear()},getItem(e){return n.has(e)?n.get(e):null},key(e){var s;return(s=Array.from(n.keys())[e])!==null&&s!==void 0?s:null},removeItem(e){n.delete(e)},setItem(e,s){n.set(e,String(s))}}}function WC(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return ZC()}const ek=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class tk{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,s){var a;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new xC,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=u=>u?(...c)=>u(...c):(...c)=>fetch(...c),!(!((a=s==null?void 0:s.params)===null||a===void 0)&&a.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=s.params.apikey;const l=this._initializeOptions(s);this.socketAdapter=new XC(e,l),this.httpEndpoint=Vw(e),this.fetch=this._resolveFetch(s==null?void 0:s.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const s=e.message;throw new Error(`WebSocket not available: ${s}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,s){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,s)}getChannels(){return this.channels}async removeChannel(e){const s=await e.unsubscribe();return s==="ok"&&e.teardown(),s}async removeAllChannels(){const e=this.channels.map(async a=>{const l=await a.unsubscribe();return a.teardown(),l}),s=await Promise.all(e);return await this.disconnect(),s}log(e,s,a){this.socketAdapter.log(e,s,a)}connectionState(){return this.socketAdapter.connectionState()||Cd.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,s={config:{}}){const a=`realtime:${e}`,l=this.getChannels().find(u=>u.topic===a);if(l)return l;{const u=new Tr(`realtime:${e}`,s,this);return this._cancelPendingDisconnect(),this.channels.push(u),u}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(s=>s.topic!==e.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e=null){let s,a=!1;if(e)s=e,a=!0;else if(this.accessToken)try{s=await this.accessToken()}catch(l){this.log("error","Error fetching access token from callback",l),s=this.accessTokenValue}else s=this.accessTokenValue;a?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=s&&(this.accessTokenValue=s,this.channels.forEach(l=>{const u={access_token:s,version:gC};s&&l.updateJoinPayload(u),l.joinedOnce&&l.channelAdapter.isJoined()&&l.channelAdapter.push(Lw.access_token,{access_token:s})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(s=>{this.log("error",`Error setting auth in ${e}`,s)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(s=>{this.log("error","error waiting for auth on connect",s)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(s,a)=>{s!=="disconnected"&&(s=="sent"&&this._setAuthSafely(),e&&e(s,a))}}_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=s=>{this.log("worker","worker error",s.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=s=>{s.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let s;if(e)s=e;else{const a=new Blob([ek],{type:"application/javascript"});s=URL.createObjectURL(a)}return s}_initializeOptions(e){var s,a,l,u,c,d,m,p,g,v,w,_;this.worker=(s=e==null?void 0:e.worker)!==null&&s!==void 0?s:!1,this.accessToken=(a=e==null?void 0:e.accessToken)!==null&&a!==void 0?a:null;const S={};S.timeout=(l=e==null?void 0:e.timeout)!==null&&l!==void 0?l:bC,S.heartbeatIntervalMs=(u=e==null?void 0:e.heartbeatIntervalMs)!==null&&u!==void 0?u:bv.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(c=e==null?void 0:e.disconnectOnEmptyChannelsAfterMs)!==null&&c!==void 0?c:2*((d=e==null?void 0:e.heartbeatIntervalMs)!==null&&d!==void 0?d:bv.HEARTBEAT_INTERVAL),S.transport=(m=e==null?void 0:e.transport)!==null&&m!==void 0?m:mC.getWebSocketConstructor(),S.params=e==null?void 0:e.params,S.logger=e==null?void 0:e.logger,S.heartbeatCallback=this._wrapHeartbeatCallback(e==null?void 0:e.heartbeatCallback),S.sessionStorage=(p=e==null?void 0:e.sessionStorage)!==null&&p!==void 0?p:WC(),S.reconnectAfterMs=(g=e==null?void 0:e.reconnectAfterMs)!==null&&g!==void 0?g:(N=>JC[N-1]||QC);let E,k;const C=(v=e==null?void 0:e.vsn)!==null&&v!==void 0?v:vC;switch(C){case yC:E=(N,O)=>O(JSON.stringify(N)),k=(N,O)=>O(JSON.parse(N));break;case Bw:E=this.serializer.encode.bind(this.serializer),k=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${S.vsn}`)}if(S.vsn=C,S.encode=(w=e==null?void 0:e.encode)!==null&&w!==void 0?w:E,S.decode=(_=e==null?void 0:e.decode)!==null&&_!==void 0?_:k,S.beforeReconnect=this._reconnectAuth.bind(this),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,S.params=Object.assign(Object.assign({},S.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl,S.autoSendHeartbeat=!this.worker}return S}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var Nr=class extends Error{constructor(n,e){var s;super(n),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&((s=e.icebergType)==null?void 0:s.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function nk(n,e,s){const a=new URL(e,n);if(s)for(const[l,u]of Object.entries(s))u!==void 0&&a.searchParams.set(l,u);return a.toString()}async function ik(n){return!n||n.type==="none"?{}:n.type==="bearer"?{Authorization:`Bearer ${n.token}`}:n.type==="header"?{[n.name]:n.value}:n.type==="custom"?await n.getHeaders():{}}function sk(n){const e=n.fetchImpl??globalThis.fetch;return{async request({method:s,path:a,query:l,body:u,headers:c}){const d=nk(n.baseUrl,a,l),m=await ik(n.auth),p=await e(d,{method:s,headers:{...u?{"Content-Type":"application/json"}:{},...m,...c},body:u?JSON.stringify(u):void 0}),g=await p.text(),v=(p.headers.get("content-type")||"").includes("application/json"),w=v&&g?JSON.parse(g):g;if(!p.ok){const _=v?w:void 0,S=_==null?void 0:_.error;throw new Nr((S==null?void 0:S.message)??`Request failed with status ${p.status}`,{status:p.status,icebergType:S==null?void 0:S.type,icebergCode:S==null?void 0:S.code,details:_})}return{status:p.status,headers:p.headers,data:w}}}}function wl(n){return n.join("")}var ak=class{constructor(n,e=""){this.client=n,this.prefix=e}async listNamespaces(n){const e=n?{parent:wl(n.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(a=>({namespace:a}))}async createNamespace(n,e){const s={namespace:n.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:s})).data}async dropNamespace(n){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${wl(n.namespace)}`})}async loadNamespaceMetadata(n){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${wl(n.namespace)}`})).data.properties}}async namespaceExists(n){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${wl(n.namespace)}`}),!0}catch(e){if(e instanceof Nr&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(n,e){try{return await this.createNamespace(n,e)}catch(s){if(s instanceof Nr&&s.status===409)return;throw s}}};function Qs(n){return n.join("")}var rk=class{constructor(n,e="",s){this.client=n,this.prefix=e,this.accessDelegation=s}async listTables(n){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Qs(n.namespace)}/tables`})).data.identifiers}async createTable(n,e){const s={};return this.accessDelegation&&(s["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Qs(n.namespace)}/tables`,body:e,headers:s})).data.metadata}async updateTable(n,e){const s=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Qs(n.namespace)}/tables/${n.name}`,body:e});return{"metadata-location":s.data["metadata-location"],metadata:s.data.metadata}}async dropTable(n,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Qs(n.namespace)}/tables/${n.name}`,query:{purgeRequested:String((e==null?void 0:e.purge)??!1)}})}async loadTable(n){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Qs(n.namespace)}/tables/${n.name}`,headers:e})).data.metadata}async tableExists(n){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Qs(n.namespace)}/tables/${n.name}`,headers:e}),!0}catch(s){if(s instanceof Nr&&s.status===404)return!1;throw s}}async createTableIfNotExists(n,e){try{return await this.createTable(n,e)}catch(s){if(s instanceof Nr&&s.status===409)return await this.loadTable({namespace:n.namespace,name:e.name});throw s}}},ok=class{constructor(n){var a;let e="v1";n.catalogName&&(e+=`/${n.catalogName}`);const s=n.baseUrl.endsWith("/")?n.baseUrl:`${n.baseUrl}/`;this.client=sk({baseUrl:s,auth:n.auth,fetchImpl:n.fetch}),this.accessDelegation=(a=n.accessDelegation)==null?void 0:a.join(","),this.namespaceOps=new ak(this.client,e),this.tableOps=new rk(this.client,e,this.accessDelegation)}async listNamespaces(n){return this.namespaceOps.listNamespaces(n)}async createNamespace(n,e){return this.namespaceOps.createNamespace(n,e)}async dropNamespace(n){await this.namespaceOps.dropNamespace(n)}async loadNamespaceMetadata(n){return this.namespaceOps.loadNamespaceMetadata(n)}async listTables(n){return this.tableOps.listTables(n)}async createTable(n,e){return this.tableOps.createTable(n,e)}async updateTable(n,e){return this.tableOps.updateTable(n,e)}async dropTable(n,e){await this.tableOps.dropTable(n,e)}async loadTable(n){return this.tableOps.loadTable(n)}async namespaceExists(n){return this.namespaceOps.namespaceExists(n)}async tableExists(n){return this.tableOps.tableExists(n)}async createNamespaceIfNotExists(n,e){return this.namespaceOps.createNamespaceIfNotExists(n,e)}async createTableIfNotExists(n,e){return this.tableOps.createTableIfNotExists(n,e)}};function Dr(n){"@babel/helpers - typeof";return Dr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Dr(n)}function lk(n,e){if(Dr(n)!="object"||!n)return n;var s=n[Symbol.toPrimitive];if(s!==void 0){var a=s.call(n,e);if(Dr(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function uk(n){var e=lk(n,"string");return Dr(e)=="symbol"?e:e+""}function ck(n,e,s){return(e=uk(e))in n?Object.defineProperty(n,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):n[e]=s,n}function wv(n,e){var s=Object.keys(n);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(n);e&&(a=a.filter(function(l){return Object.getOwnPropertyDescriptor(n,l).enumerable})),s.push.apply(s,a)}return s}function ce(n){for(var e=1;en?(...e)=>n(...e):(...e)=>fetch(...e),fk=n=>{if(typeof n!="object"||n===null)return!1;const e=Object.getPrototypeOf(n);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in n)&&!(Symbol.iterator in n)},Dd=n=>{if(Array.isArray(n))return n.map(s=>Dd(s));if(typeof n=="function"||n!==Object(n))return n;const e={};return Object.entries(n).forEach(([s,a])=>{const l=s.replace(/([-_][a-z])/gi,u=>u.toUpperCase().replace(/[-_]/g,""));e[l]=Dd(a)}),e},mk=n=>!n||typeof n!="string"||n.length===0||n.length>100||n.trim()!==n||n.includes("/")||n.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(n),xv=n=>{if(typeof n=="object"&&n!==null){const e=n;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){const s=e.error;if(typeof s.message=="string")return s.message}}return JSON.stringify(n)},pk=async(n,e,s,a)=>{if(n!==null&&typeof n=="object"&&"json"in n&&typeof n.json=="function"){const l=n;let u=parseInt(String(l.status),10);Number.isFinite(u)||(u=500),l.json().then(c=>{const d=(c==null?void 0:c.statusCode)||(c==null?void 0:c.code)||u+"";e(new Nd(xv(c),u,d,a))}).catch(()=>{const c=u+"";e(new Nd(l.statusText||`HTTP ${u} error`,u,c,a))})}else e(new Hw(xv(n),n,a))},gk=(n,e,s,a)=>{const l={method:n,headers:(e==null?void 0:e.headers)||{}};if(n==="GET"||n==="HEAD"||!a)return ce(ce({},l),s);if(fk(a)){var u;const c=(e==null?void 0:e.headers)||{};let d;for(const[m,p]of Object.entries(c))m.toLowerCase()==="content-type"&&(d=p);l.headers=Kl(c,"Content-Type",(u=d)!==null&&u!==void 0?u:"application/json"),l.body=JSON.stringify(a)}else l.body=a;return e!=null&&e.duplex&&(l.duplex=e.duplex),ce(ce({},l),s)};async function dr(n,e,s,a,l,u,c){return new Promise((d,m)=>{n(s,gk(e,a,l,u)).then(p=>{if(!p.ok)throw p;if(a!=null&&a.noResolveJson)return p;if(c==="vectors"){const g=p.headers.get("content-type");if(p.headers.get("content-length")==="0"||p.status===204)return{};if(!g||!g.includes("application/json"))return{}}return p.json()}).then(p=>d(p)).catch(p=>pk(p,m,a,c))})}function $w(n="storage"){return{get:async(e,s,a,l)=>dr(e,"GET",s,a,l,void 0,n),post:async(e,s,a,l,u)=>dr(e,"POST",s,l,u,a,n),put:async(e,s,a,l,u)=>dr(e,"PUT",s,l,u,a,n),head:async(e,s,a,l)=>dr(e,"HEAD",s,ce(ce({},a),{},{noResolveJson:!0}),l,void 0,n),remove:async(e,s,a,l,u)=>dr(e,"DELETE",s,l,u,a,n)}}const yk=$w("storage"),{get:Mr,post:dn,put:Md,head:vk,remove:Ur}=yk,qt=$w("vectors");var ma=class{constructor(n,e={},s,a="storage"){this.shouldThrowOnError=!1,this.url=n,this.headers=hk(e),this.fetch=dk(s),this.namespace=a}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(n,e){return this.headers=Kl(this.headers,n,e),this}async handleOperation(n){var e=this;try{return{data:await n(),error:null}}catch(s){if(e.shouldThrowOnError)throw s;if(ru(s))return{data:null,error:s};throw s}}};let qw;qw=Symbol.toStringTag;var bk=class{constructor(n,e){this.downloadFn=n,this.shouldThrowOnError=e,this[qw]="StreamDownloadBuilder",this.promise=null}then(n,e){return this.getPromise().then(n,e)}catch(n){return this.getPromise().catch(n)}finally(n){return this.getPromise().finally(n)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var n=this;try{return{data:(await n.downloadFn()).body,error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(ru(e))return{data:null,error:e};throw e}}};let Gw;Gw=Symbol.toStringTag;var wk=class{constructor(n,e){this.downloadFn=n,this.shouldThrowOnError=e,this[Gw]="BlobDownloadBuilder",this.promise=null}asStream(){return new bk(this.downloadFn,this.shouldThrowOnError)}then(n,e){return this.getPromise().then(n,e)}catch(n){return this.getPromise().catch(n)}finally(n){return this.getPromise().finally(n)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var n=this;try{return{data:await(await n.downloadFn()).blob(),error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(ru(e))return{data:null,error:e};throw e}}};const Fh={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},_v={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var xk=class extends ma{constructor(n,e={},s,a){super(n,e,a,"storage"),this.bucketId=s}async uploadOrUpdate(n,e,s,a){var l=this;return l.handleOperation(async()=>{let u;const c=ce(ce({},_v),a);let d=ce(ce({},l.headers),n==="POST"&&{"x-upsert":String(c.upsert)});const m=c.metadata;if(typeof Blob<"u"&&s instanceof Blob?(u=new FormData,u.append("cacheControl",c.cacheControl),m&&u.append("metadata",l.encodeMetadata(m)),u.append("",s)):typeof FormData<"u"&&s instanceof FormData?(u=s,u.has("cacheControl")||u.append("cacheControl",c.cacheControl),m&&!u.has("metadata")&&u.append("metadata",l.encodeMetadata(m))):(u=s,d["cache-control"]=`max-age=${c.cacheControl}`,d["content-type"]=c.contentType,m&&(d["x-metadata"]=l.toBase64(l.encodeMetadata(m))),(typeof ReadableStream<"u"&&u instanceof ReadableStream||u&&typeof u=="object"&&"pipe"in u&&typeof u.pipe=="function")&&!c.duplex&&(c.duplex="half")),a!=null&&a.headers)for(const[w,_]of Object.entries(a.headers))d=Kl(d,w,_);const p=l._removeEmptyFolders(e),g=l._getFinalPath(p),v=await(n=="PUT"?Md:dn)(l.fetch,`${l.url}/object/${g}`,u,ce({headers:d},c!=null&&c.duplex?{duplex:c.duplex}:{}));return{path:p,id:v.Id,fullPath:v.Key}})}async upload(n,e,s){return this.uploadOrUpdate("POST",n,e,s)}async uploadToSignedUrl(n,e,s,a){var l=this;const u=l._removeEmptyFolders(n),c=l._getFinalPath(u),d=new URL(l.url+`/object/upload/sign/${c}`);return d.searchParams.set("token",e),l.handleOperation(async()=>{let m;const p=ce(ce({},_v),a);let g=ce(ce({},l.headers),{"x-upsert":String(p.upsert)});const v=p.metadata;if(typeof Blob<"u"&&s instanceof Blob?(m=new FormData,m.append("cacheControl",p.cacheControl),v&&m.append("metadata",l.encodeMetadata(v)),m.append("",s)):typeof FormData<"u"&&s instanceof FormData?(m=s,m.has("cacheControl")||m.append("cacheControl",p.cacheControl),v&&!m.has("metadata")&&m.append("metadata",l.encodeMetadata(v))):(m=s,g["cache-control"]=`max-age=${p.cacheControl}`,g["content-type"]=p.contentType,v&&(g["x-metadata"]=l.toBase64(l.encodeMetadata(v))),(typeof ReadableStream<"u"&&m instanceof ReadableStream||m&&typeof m=="object"&&"pipe"in m&&typeof m.pipe=="function")&&!p.duplex&&(p.duplex="half")),a!=null&&a.headers)for(const[w,_]of Object.entries(a.headers))g=Kl(g,w,_);return{path:u,fullPath:(await Md(l.fetch,d.toString(),m,ce({headers:g},p!=null&&p.duplex?{duplex:p.duplex}:{}))).Key}})}async createSignedUploadUrl(n,e){var s=this;return s.handleOperation(async()=>{let a=s._getFinalPath(n);const l=ce({},s.headers);e!=null&&e.upsert&&(l["x-upsert"]="true");const u=await dn(s.fetch,`${s.url}/object/upload/sign/${a}`,{},{headers:l}),c=new URL(s.url+u.url),d=c.searchParams.get("token");if(!d)throw new au("No token returned by API");return{signedUrl:c.toString(),path:n,token:d}})}async update(n,e,s){return this.uploadOrUpdate("PUT",n,e,s)}async move(n,e,s){var a=this;return a.handleOperation(async()=>await dn(a.fetch,`${a.url}/object/move`,{bucketId:a.bucketId,sourceKey:n,destinationKey:e,destinationBucket:s==null?void 0:s.destinationBucket},{headers:a.headers}))}async copy(n,e,s){var a=this;return a.handleOperation(async()=>({path:(await dn(a.fetch,`${a.url}/object/copy`,{bucketId:a.bucketId,sourceKey:n,destinationKey:e,destinationBucket:s==null?void 0:s.destinationBucket},{headers:a.headers})).Key}))}async createSignedUrl(n,e,s){var a=this;return a.handleOperation(async()=>{let l=a._getFinalPath(n);const u=typeof(s==null?void 0:s.transform)=="object"&&s.transform!==null&&Object.keys(s.transform).length>0;let c=await dn(a.fetch,`${a.url}/object/sign/${l}`,ce({expiresIn:e},u?{transform:s.transform}:{}),{headers:a.headers});const d=new URLSearchParams;s!=null&&s.download&&d.set("download",s.download===!0?"":s.download),(s==null?void 0:s.cacheNonce)!=null&&d.set("cacheNonce",String(s.cacheNonce));const m=d.toString();return{signedUrl:encodeURI(`${a.url}${c.signedURL}${m?`&${m}`:""}`)}})}async createSignedUrls(n,e,s){var a=this;return a.handleOperation(async()=>{const l=await dn(a.fetch,`${a.url}/object/sign/${a.bucketId}`,{expiresIn:e,paths:n},{headers:a.headers}),u=new URLSearchParams;s!=null&&s.download&&u.set("download",s.download===!0?"":s.download),(s==null?void 0:s.cacheNonce)!=null&&u.set("cacheNonce",String(s.cacheNonce));const c=u.toString();return l.map(d=>ce(ce({},d),{},{signedUrl:d.signedURL?encodeURI(`${a.url}${d.signedURL}${c?`&${c}`:""}`):null}))})}download(n,e,s){const a=typeof(e==null?void 0:e.transform)=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",l=new URLSearchParams;e!=null&&e.transform&&this.applyTransformOptsToQuery(l,e.transform),(e==null?void 0:e.cacheNonce)!=null&&l.set("cacheNonce",String(e.cacheNonce));const u=l.toString(),c=this._getFinalPath(n),d=()=>Mr(this.fetch,`${this.url}/${a}/${c}${u?`?${u}`:""}`,{headers:this.headers,noResolveJson:!0},s);return new wk(d,this.shouldThrowOnError)}async info(n){var e=this;const s=e._getFinalPath(n);return e.handleOperation(async()=>Dd(await Mr(e.fetch,`${e.url}/object/info/${s}`,{headers:e.headers})))}async exists(n){var e=this;const s=e._getFinalPath(n);try{return await vk(e.fetch,`${e.url}/object/${s}`,{headers:e.headers}),{data:!0,error:null}}catch(l){if(e.shouldThrowOnError)throw l;if(ru(l)){var a;const u=l instanceof Nd?l.status:l instanceof Hw?(a=l.originalError)===null||a===void 0?void 0:a.status:void 0;if(u!==void 0&&[400,404].includes(u))return{data:!1,error:l}}throw l}}getPublicUrl(n,e){const s=this._getFinalPath(n),a=new URLSearchParams;e!=null&&e.download&&a.set("download",e.download===!0?"":e.download),e!=null&&e.transform&&this.applyTransformOptsToQuery(a,e.transform),(e==null?void 0:e.cacheNonce)!=null&&a.set("cacheNonce",String(e.cacheNonce));const l=a.toString(),u=typeof(e==null?void 0:e.transform)=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${u}/public/${s}`)+(l?`?${l}`:"")}}}async remove(n){var e=this;return e.handleOperation(async()=>await Ur(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:n},{headers:e.headers}))}async purgeCache(n,e,s){var a=this;return a.handleOperation(async()=>{const l=a._getFinalPath(n),u=new URLSearchParams;e!=null&&e.transformations&&u.set("transformations","true");const c=u.toString();return await Ur(a.fetch,`${a.url}/cdn/${l}${c?`?${c}`:""}`,{},{headers:a.headers},s)})}async list(n,e,s){var a=this;return a.handleOperation(async()=>{const l=e!=null&&e.sortBy?ce(ce({},Fh.sortBy),e.sortBy):Fh.sortBy,u=ce(ce(ce({},Fh),e),{},{sortBy:l,prefix:n||""});return await dn(a.fetch,`${a.url}/object/list/${a.bucketId}`,u,{headers:a.headers},s)})}async listV2(n,e){var s=this;return s.handleOperation(async()=>{const a=ce({},n);return await dn(s.fetch,`${s.url}/object/list-v2/${s.bucketId}`,a,{headers:s.headers},e)})}encodeMetadata(n){return JSON.stringify(n)}toBase64(n){return typeof Buffer<"u"?Buffer.from(n).toString("base64"):btoa(n)}_getFinalPath(n){return`${this.bucketId}/${n.replace(/^\/+/,"")}`}_removeEmptyFolders(n){return n.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(n,e){return e.width&&n.set("width",e.width.toString()),e.height&&n.set("height",e.height.toString()),e.resize&&n.set("resize",e.resize),e.format&&n.set("format",e.format),e.quality&&n.set("quality",e.quality.toString()),n}};const _k="2.110.2",qr={"X-Client-Info":`storage-js/${_k}`};var Sk=class extends ma{constructor(n,e={},s,a){const l=new URL(n);a!=null&&a.useNewHostname&&/supabase\.(co|in|red)$/.test(l.hostname)&&!l.hostname.includes("storage.supabase.")&&(l.hostname=l.hostname.replace("supabase.","storage.supabase."));const u=l.href.replace(/\/$/,""),c=ce(ce({},qr),e);super(u,c,s,"storage")}async listBuckets(n){var e=this;return e.handleOperation(async()=>{const s=e.listBucketOptionsToQueryString(n);return await Mr(e.fetch,`${e.url}/bucket${s}`,{headers:e.headers})})}async getBucket(n){var e=this;return e.handleOperation(async()=>await Mr(e.fetch,`${e.url}/bucket/${n}`,{headers:e.headers}))}async createBucket(n,e={public:!1}){var s=this;return s.handleOperation(async()=>await dn(s.fetch,`${s.url}/bucket`,{id:n,name:n,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:s.headers}))}async updateBucket(n,e){var s=this;return s.handleOperation(async()=>await Md(s.fetch,`${s.url}/bucket/${n}`,{id:n,name:n,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:s.headers}))}async emptyBucket(n){var e=this;return e.handleOperation(async()=>await dn(e.fetch,`${e.url}/bucket/${n}/empty`,{},{headers:e.headers}))}async deleteBucket(n){var e=this;return e.handleOperation(async()=>await Ur(e.fetch,`${e.url}/bucket/${n}`,{},{headers:e.headers}))}async purgeBucketCache(n,e,s){var a=this;return a.handleOperation(async()=>{const l=new URLSearchParams;e!=null&&e.transformations&&l.set("transformations","true");const u=l.toString();return await Ur(a.fetch,`${a.url}/cdn/${n}${u?`?${u}`:""}`,{},{headers:a.headers},s)})}listBucketOptionsToQueryString(n){const e={};return n&&("limit"in n&&(e.limit=String(n.limit)),"offset"in n&&(e.offset=String(n.offset)),n.search&&(e.search=n.search),n.sortColumn&&(e.sortColumn=n.sortColumn),n.sortOrder&&(e.sortOrder=n.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},Tk=class extends ma{constructor(n,e={},s){const a=n.replace(/\/$/,""),l=ce(ce({},qr),e);super(a,l,s,"storage")}async createBucket(n){var e=this;return e.handleOperation(async()=>await dn(e.fetch,`${e.url}/bucket`,{name:n},{headers:e.headers}))}async listBuckets(n){var e=this;return e.handleOperation(async()=>{const s=new URLSearchParams;(n==null?void 0:n.limit)!==void 0&&s.set("limit",n.limit.toString()),(n==null?void 0:n.offset)!==void 0&&s.set("offset",n.offset.toString()),n!=null&&n.sortColumn&&s.set("sortColumn",n.sortColumn),n!=null&&n.sortOrder&&s.set("sortOrder",n.sortOrder),n!=null&&n.search&&s.set("search",n.search);const a=s.toString(),l=a?`${e.url}/bucket?${a}`:`${e.url}/bucket`;return await Mr(e.fetch,l,{headers:e.headers})})}async deleteBucket(n){var e=this;return e.handleOperation(async()=>await Ur(e.fetch,`${e.url}/bucket/${n}`,{},{headers:e.headers}))}from(n){var e=this;if(!mk(n))throw new au("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const s=new ok({baseUrl:this.url,catalogName:n,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),a=this.shouldThrowOnError;return new Proxy(s,{get(l,u){const c=l[u];return typeof c!="function"?c:async(...d)=>{try{return{data:await c.apply(l,d),error:null}}catch(m){if(a)throw m;return{data:null,error:m}}}}})}},Ek=class extends ma{constructor(n,e={},s){const a=n.replace(/\/$/,""),l=ce(ce({},qr),{},{"Content-Type":"application/json"},e);super(a,l,s,"vectors")}async createIndex(n){var e=this;return e.handleOperation(async()=>await qt.post(e.fetch,`${e.url}/CreateIndex`,n,{headers:e.headers})||{})}async getIndex(n,e){var s=this;return s.handleOperation(async()=>await qt.post(s.fetch,`${s.url}/GetIndex`,{vectorBucketName:n,indexName:e},{headers:s.headers}))}async listIndexes(n){var e=this;return e.handleOperation(async()=>await qt.post(e.fetch,`${e.url}/ListIndexes`,n,{headers:e.headers}))}async deleteIndex(n,e){var s=this;return s.handleOperation(async()=>await qt.post(s.fetch,`${s.url}/DeleteIndex`,{vectorBucketName:n,indexName:e},{headers:s.headers})||{})}},Ak=class extends ma{constructor(n,e={},s){const a=n.replace(/\/$/,""),l=ce(ce({},qr),{},{"Content-Type":"application/json"},e);super(a,l,s,"vectors")}async putVectors(n){var e=this;if(n.vectors.length<1||n.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await qt.post(e.fetch,`${e.url}/PutVectors`,n,{headers:e.headers})||{})}async getVectors(n){var e=this;return e.handleOperation(async()=>await qt.post(e.fetch,`${e.url}/GetVectors`,n,{headers:e.headers}))}async listVectors(n){var e=this;if(n.segmentCount!==void 0){if(n.segmentCount<1||n.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(n.segmentIndex!==void 0&&(n.segmentIndex<0||n.segmentIndex>=n.segmentCount))throw new Error(`segmentIndex must be between 0 and ${n.segmentCount-1}`)}return e.handleOperation(async()=>await qt.post(e.fetch,`${e.url}/ListVectors`,n,{headers:e.headers}))}async queryVectors(n){var e=this;return e.handleOperation(async()=>await qt.post(e.fetch,`${e.url}/QueryVectors`,n,{headers:e.headers}))}async deleteVectors(n){var e=this;if(n.keys.length<1||n.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await qt.post(e.fetch,`${e.url}/DeleteVectors`,n,{headers:e.headers})||{})}},Rk=class extends ma{constructor(n,e={},s){const a=n.replace(/\/$/,""),l=ce(ce({},qr),{},{"Content-Type":"application/json"},e);super(a,l,s,"vectors")}async createBucket(n){var e=this;return e.handleOperation(async()=>await qt.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:n},{headers:e.headers})||{})}async getBucket(n){var e=this;return e.handleOperation(async()=>await qt.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:n},{headers:e.headers}))}async listBuckets(n={}){var e=this;return e.handleOperation(async()=>await qt.post(e.fetch,`${e.url}/ListVectorBuckets`,n,{headers:e.headers}))}async deleteBucket(n){var e=this;return e.handleOperation(async()=>await qt.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:n},{headers:e.headers})||{})}},Ck=class extends Rk{constructor(n,e={}){super(n,e.headers||{},e.fetch)}from(n){return new kk(this.url,this.headers,n,this.fetch)}async createBucket(n){var e=()=>super.createBucket,s=this;return e().call(s,n)}async getBucket(n){var e=()=>super.getBucket,s=this;return e().call(s,n)}async listBuckets(n={}){var e=()=>super.listBuckets,s=this;return e().call(s,n)}async deleteBucket(n){var e=()=>super.deleteBucket,s=this;return e().call(s,n)}},kk=class extends Ek{constructor(n,e,s,a){super(n,e,a),this.vectorBucketName=s}async createIndex(n){var e=()=>super.createIndex,s=this;return e().call(s,ce(ce({},n),{},{vectorBucketName:s.vectorBucketName}))}async listIndexes(n={}){var e=()=>super.listIndexes,s=this;return e().call(s,ce(ce({},n),{},{vectorBucketName:s.vectorBucketName}))}async getIndex(n){var e=()=>super.getIndex,s=this;return e().call(s,s.vectorBucketName,n)}async deleteIndex(n){var e=()=>super.deleteIndex,s=this;return e().call(s,s.vectorBucketName,n)}index(n){return new jk(this.url,this.headers,this.vectorBucketName,n,this.fetch)}},jk=class extends Ak{constructor(n,e,s,a,l){super(n,e,l),this.vectorBucketName=s,this.indexName=a}async putVectors(n){var e=()=>super.putVectors,s=this;return e().call(s,ce(ce({},n),{},{vectorBucketName:s.vectorBucketName,indexName:s.indexName}))}async getVectors(n){var e=()=>super.getVectors,s=this;return e().call(s,ce(ce({},n),{},{vectorBucketName:s.vectorBucketName,indexName:s.indexName}))}async listVectors(n={}){var e=()=>super.listVectors,s=this;return e().call(s,ce(ce({},n),{},{vectorBucketName:s.vectorBucketName,indexName:s.indexName}))}async queryVectors(n){var e=()=>super.queryVectors,s=this;return e().call(s,ce(ce({},n),{},{vectorBucketName:s.vectorBucketName,indexName:s.indexName}))}async deleteVectors(n){var e=()=>super.deleteVectors,s=this;return e().call(s,ce(ce({},n),{},{vectorBucketName:s.vectorBucketName,indexName:s.indexName}))}},Ok=class extends Sk{constructor(n,e={},s,a){super(n,e,s,a)}from(n){return new xk(this.url,this.headers,n,this.fetch)}get vectors(){return new Ck(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Tk(this.url+"/iceberg",this.headers,this.fetch)}};const Iw="2.110.2",ti=30*1e3,gr=3,Yh=gr*ti,Nk=2*ti,Dk="http://localhost:9999",Mk="supabase.auth.token",Uk={"X-Client-Info":`gotrue-js/${Iw}`},Ud="X-Supabase-Api-Version",Kw={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Bk=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Lk=600*1e3;class Br extends Error{constructor(e,s,a){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=s,this.code=a}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function W(n){return typeof n=="object"&&n!==null&&"__isAuthError"in n}class zk extends Br{constructor(e,s,a){super(e,s,a),this.name="AuthApiError",this.status=s,this.code=a}}function Vk(n){return W(n)&&n.name==="AuthApiError"}class fn extends Br{constructor(e,s){super(e),this.name="AuthUnknownError",this.originalError=s}}class kn extends Br{constructor(e,s,a,l){super(e,a,l),this.name=s,this.status=a}}class ht extends kn{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function xl(n){return W(n)&&n.name==="AuthSessionMissingError"}class Zs extends kn{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class _l extends kn{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Sl extends kn{constructor(e,s=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=s}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}function Pk(n){return W(n)&&n.name==="AuthImplicitGrantRedirectError"}class Sv extends kn{constructor(e,s=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=s}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class Hk extends kn{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class Bd extends kn{constructor(e,s){super(e,"AuthRetryableFetchError",s,void 0)}}function Tv(n){return W(n)&&n.name==="AuthRetryableFetchError"}class Ev extends kn{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}}function $k(n){return W(n)&&n.name==="AuthRefreshDiscardedError"}class Av extends kn{constructor(e,s,a){super(e,"AuthWeakPasswordError",s,"weak_password"),this.reasons=a}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class Fl extends kn{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Yl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Rv=` \r=`.split(""),qk=(()=>{const n=new Array(128);for(let e=0;e=6;){const a=e.queue>>e.queuedBits-6&63;s(Yl[a]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const a=e.queue>>e.queuedBits-6&63;s(Yl[a]),e.queuedBits-=6}}function Fw(n,e,s){const a=qk[n];if(a>-1)for(e.queue=e.queue<<6|a,e.queuedBits+=6;e.queuedBits>=8;)s(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(a===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`)}}function kv(n){const e=[],s=c=>{e.push(String.fromCodePoint(c))},a={utf8seq:0,codepoint:0},l={queue:0,queuedBits:0},u=c=>{Kk(c,a,s)};for(let c=0;c>6),e(128|n&63);return}else if(n<=65535){e(224|n>>12),e(128|n>>6&63),e(128|n&63);return}else if(n<=1114111){e(240|n>>18),e(128|n>>12&63),e(128|n>>6&63),e(128|n&63);return}throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`)}function Ik(n,e){for(let s=0;s55295&&a<=56319){const l=(a-55296)*1024&65535;a=(n.charCodeAt(s+1)-56320&65535|l)+65536,s+=1}Gk(a,e)}}function Kk(n,e,s){if(e.utf8seq===0){if(n<=127){s(n);return}for(let a=1;a<6;a+=1)if((n>>7-a&1)===0){e.utf8seq=a;break}if(e.utf8seq===2)e.codepoint=n&31;else if(e.utf8seq===3)e.codepoint=n&15;else if(e.utf8seq===4)e.codepoint=n&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(n<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|n&63,e.utf8seq-=1,e.utf8seq===0&&s(e.codepoint)}}function la(n){const e=[],s={queue:0,queuedBits:0},a=l=>{e.push(l)};for(let l=0;le.push(s)),new Uint8Array(e)}function ls(n){const e=[],s={queue:0,queuedBits:0},a=l=>{e.push(l)};return n.forEach(l=>Cv(l,s,a)),Cv(null,s,a),e.join("")}function Yk(n){return Math.round(Date.now()/1e3)+n}function Xk(){return Symbol("auth-callback")}const wt=()=>typeof window<"u"&&typeof document<"u",ts={tested:!1,writable:!1},Yw=()=>{if(!wt())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ts.tested)return ts.writable;const n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),ts.tested=!0,ts.writable=!0}catch{ts.tested=!0,ts.writable=!1}return ts.writable};function Jk(n){const e={},s=new URL(n);if(s.hash&&s.hash[0]==="#")try{new URLSearchParams(s.hash.substring(1)).forEach((l,u)=>{e[u]=l})}catch{}return s.searchParams.forEach((a,l)=>{e[l]=a}),e}const Xw=n=>n?(...e)=>n(...e):(...e)=>fetch(...e),Qk=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",ia=async(n,e,s)=>{await n.setItem(e,JSON.stringify(s))},un=async(n,e)=>{const s=await n.getItem(e);if(!s)return null;try{return JSON.parse(s)}catch{return null}},We=async(n,e)=>{await n.removeItem(e)};class ou{constructor(){this.promise=new ou.promiseConstructor((e,s)=>{this.resolve=e,this.reject=s})}}ou.promiseConstructor=Promise;function Tl(n){const e=n.split(".");if(e.length!==3)throw new Fl("Invalid JWT structure");for(let a=0;a{setTimeout(()=>e(null),n)})}function Wk(n,e){return new Promise((a,l)=>{(async()=>{for(let u=0;u<1/0;u++)try{const c=await n(u);if(!e(u,null,c)){a(c);return}}catch(c){if(!e(u,c)){l(c);return}}})()})}function ej(n){return("0"+n.toString(16)).substr(-2)}function tj(){const e=new Uint32Array(56);if(typeof crypto>"u"){const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",a=s.length;let l="";for(let u=0;u<56;u++)l+=s.charAt(Math.floor(Math.random()*a));return l}return crypto.getRandomValues(e),Array.from(e,ej).join("")}async function nj(n){const s=new TextEncoder().encode(n),a=await crypto.subtle.digest("SHA-256",s),l=new Uint8Array(a);return Array.from(l).map(u=>String.fromCharCode(u)).join("")}async function ij(n){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),n;const s=await nj(n);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ns(n,e,s=!1){const a=tj();let l=a;s&&(l+="/recovery"),await ia(n,`${e}-code-verifier`,l);const u=await ij(a);return[u,a===u?"plain":"s256"]}const sj=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function aj(n){const e=n.headers.get(Ud);if(!e||!e.match(sj))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function rj(n){if(!n)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(n<=e)throw new Error("JWT has expired")}function oj(n){switch(n){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const lj=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Qn(n){if(!lj.test(n))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function hn(n){if(!n.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function Xh(){const n={};return new Proxy(n,{get:(e,s)=>{if(s==="__isUserNotAvailableProxy")return!0;if(typeof s=="symbol"){const a=s.toString();if(a==="Symbol(Symbol.toPrimitive)"||a==="Symbol(Symbol.toStringTag)"||a==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${s}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,s)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${s}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,s)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${s}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function uj(n,e){return new Proxy(n,{get:(s,a,l)=>{if(a==="__isInsecureUserWarningProxy")return!0;if(typeof a=="symbol"){const u=a.toString();if(u==="Symbol(Symbol.toPrimitive)"||u==="Symbol(Symbol.toStringTag)"||u==="Symbol(util.inspect.custom)"||u==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(s,a,l)}return!e.value&&typeof a=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(s,a,l)}})}function jv(n){return JSON.parse(JSON.stringify(n))}const ss=n=>{if(typeof n=="object"&&n!==null){const e=n;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(n)},cj=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function Ov(n){var e;if(!Qk(n))throw new Bd(ss(n),0);if(cj.includes(n.status))throw new Bd(ss(n),n.status);let s;try{s=await n.json()}catch(u){throw new fn(ss(u),u)}let a;const l=aj(n);if(l&&l.getTime()>=Kw["2024-01-01"].timestamp&&typeof s=="object"&&s&&typeof s.code=="string"?a=s.code:typeof s=="object"&&s&&typeof s.error_code=="string"&&(a=s.error_code),a){if(a==="weak_password")throw new Av(ss(s),n.status,((e=s.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(a==="session_not_found")throw new ht}else if(typeof s=="object"&&s&&typeof s.weak_password=="object"&&s.weak_password&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.reasons.reduce((u,c)=>u&&typeof c=="string",!0))throw new Av(ss(s),n.status,s.weak_password.reasons);throw new zk(ss(s),n.status||500,a)}const hj=(n,e,s,a)=>{const l={method:n,headers:(e==null?void 0:e.headers)||{}};return n==="GET"?l:(l.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),l.body=JSON.stringify(a),Object.assign(Object.assign({},l),s))};async function ae(n,e,s,a){var l;const u=Object.assign({},a==null?void 0:a.headers);u[Ud]||(u[Ud]=Kw["2024-01-01"].name),a!=null&&a.jwt&&(u.Authorization=`Bearer ${a.jwt}`);const c=(l=a==null?void 0:a.query)!==null&&l!==void 0?l:{};a!=null&&a.redirectTo&&(c.redirect_to=a.redirectTo);const d=Object.keys(c).length?"?"+new URLSearchParams(c).toString():"",m=await dj(n,e,s+d,{headers:u,noResolveJson:a==null?void 0:a.noResolveJson},{},a==null?void 0:a.body);return a!=null&&a.xform?a==null?void 0:a.xform(m):{data:Object.assign({},m),error:null}}async function dj(n,e,s,a,l,u){const c=hj(e,a,l,u);let d;try{d=await n(s,Object.assign({},c))}catch(m){throw console.error(m),new Bd(ss(m),0)}if(d.ok||await Ov(d),a!=null&&a.noResolveJson)return d;try{return await d.json()}catch(m){await Ov(m)}}function tn(n){var e;let s=null;pj(n)&&(s=Object.assign({},n),n.expires_at||(s.expires_at=Yk(n.expires_in)));const a=(e=n.user)!==null&&e!==void 0?e:typeof(n==null?void 0:n.id)=="string"?n:null;return{data:{session:s,user:a},error:null}}function Nv(n){const e=tn(n);return!e.error&&n.weak_password&&typeof n.weak_password=="object"&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.message&&typeof n.weak_password.message=="string"&&n.weak_password.reasons.reduce((s,a)=>s&&typeof a=="string",!0)&&(e.data.weak_password=n.weak_password),e}function ji(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function fj(n){return{data:n,error:null}}function mj(n){const{action_link:e,email_otp:s,hashed_token:a,redirect_to:l,verification_type:u}=n,c=su(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),d={action_link:e,email_otp:s,hashed_token:a,redirect_to:l,verification_type:u},m=Object.assign({},c);return{data:{properties:d,user:m},error:null}}function Dv(n){return n}function pj(n){return!!n.access_token&&!!n.refresh_token&&!!n.expires_in}const Jh=["global","local","others"];class gj{constructor({url:e="",headers:s={},fetch:a,experimental:l}){this.url=e,this.headers=s,this.fetch=Xw(a),this.experimental=l??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,s=Jh[0]){if(Jh.indexOf(s)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Jh.join(", ")}`);try{return await ae(this.fetch,"POST",`${this.url}/logout?scope=${s}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(a){if(W(a))return{data:null,error:a};throw a}}async inviteUserByEmail(e,s={}){try{return await ae(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:s.data},headers:this.headers,redirectTo:s.redirectTo,xform:ji})}catch(a){if(W(a))return{data:{user:null},error:a};throw a}}async generateLink(e){try{const{options:s}=e,a=su(e,["options"]),l=Object.assign(Object.assign({},a),s);return"newEmail"in a&&(l.new_email=a==null?void 0:a.newEmail,delete l.newEmail),await ae(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:l,headers:this.headers,xform:mj,redirectTo:s==null?void 0:s.redirectTo})}catch(s){if(W(s))return{data:{properties:null,user:null},error:s};throw s}}async createUser(e){try{return await ae(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ji})}catch(s){if(W(s))return{data:{user:null},error:s};throw s}}async listUsers(e){var s,a,l,u,c,d,m;try{const p={nextPage:null,lastPage:0,total:0},g=await ae(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(a=(s=e==null?void 0:e.page)===null||s===void 0?void 0:s.toString())!==null&&a!==void 0?a:"",per_page:(u=(l=e==null?void 0:e.perPage)===null||l===void 0?void 0:l.toString())!==null&&u!==void 0?u:""},xform:Dv});if(g.error)throw g.error;const v=await g.json(),w=(c=g.headers.get("x-total-count"))!==null&&c!==void 0?c:0,_=(m=(d=g.headers.get("link"))===null||d===void 0?void 0:d.split(","))!==null&&m!==void 0?m:[];return _.length>0&&(_.forEach(S=>{const E=parseInt(S.split(";")[0].split("=")[1].substring(0,1)),k=JSON.parse(S.split(";")[1].split("=")[1]);p[`${k}Page`]=E}),p.total=parseInt(w)),{data:Object.assign(Object.assign({},v),p),error:null}}catch(p){if(W(p))return{data:{users:[]},error:p};throw p}}async getUserById(e){Qn(e);try{return await ae(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ji})}catch(s){if(W(s))return{data:{user:null},error:s};throw s}}async updateUserById(e,s){Qn(e);try{return await ae(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:s,headers:this.headers,xform:ji})}catch(a){if(W(a))return{data:{user:null},error:a};throw a}}async deleteUser(e,s=!1){Qn(e);try{return await ae(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:s},xform:ji})}catch(a){if(W(a))return{data:{user:null},error:a};throw a}}async _listFactors(e){Qn(e.userId);try{const{data:s,error:a}=await ae(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:l=>({data:{factors:l},error:null})});return{data:s,error:a}}catch(s){if(W(s))return{data:null,error:s};throw s}}async _deleteFactor(e){Qn(e.userId),Qn(e.id);try{return{data:await ae(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(s){if(W(s))return{data:null,error:s};throw s}}async _listOAuthClients(e){var s,a,l,u,c,d,m;try{const p={nextPage:null,lastPage:0,total:0},g=await ae(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(a=(s=e==null?void 0:e.page)===null||s===void 0?void 0:s.toString())!==null&&a!==void 0?a:"",per_page:(u=(l=e==null?void 0:e.perPage)===null||l===void 0?void 0:l.toString())!==null&&u!==void 0?u:""},xform:Dv});if(g.error)throw g.error;const v=await g.json(),w=(c=g.headers.get("x-total-count"))!==null&&c!==void 0?c:0,_=(m=(d=g.headers.get("link"))===null||d===void 0?void 0:d.split(","))!==null&&m!==void 0?m:[];return _.length>0&&(_.forEach(S=>{const E=parseInt(S.split(";")[0].split("=")[1].substring(0,1)),k=JSON.parse(S.split(";")[1].split("=")[1]);p[`${k}Page`]=E}),p.total=parseInt(w)),{data:Object.assign(Object.assign({},v),p),error:null}}catch(p){if(W(p))return{data:{clients:[]},error:p};throw p}}async _createOAuthClient(e){try{return await ae(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(W(s))return{data:null,error:s};throw s}}async _getOAuthClient(e){try{return await ae(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(W(s))return{data:null,error:s};throw s}}async _updateOAuthClient(e,s){try{return await ae(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:s,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(W(a))return{data:null,error:a};throw a}}async _deleteOAuthClient(e){try{return await ae(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(s){if(W(s))return{data:null,error:s};throw s}}async _regenerateOAuthClientSecret(e){try{return await ae(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(W(s))return{data:null,error:s};throw s}}async _listCustomProviders(e){try{const s={};return e!=null&&e.type&&(s.type=e.type),await ae(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:s,xform:a=>{var l;return{data:{providers:(l=a==null?void 0:a.providers)!==null&&l!==void 0?l:[]},error:null}}})}catch(s){if(W(s))return{data:{providers:[]},error:s};throw s}}async _createCustomProvider(e){try{return await ae(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(W(s))return{data:null,error:s};throw s}}async _getCustomProvider(e){try{return await ae(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(W(s))return{data:null,error:s};throw s}}async _updateCustomProvider(e,s){try{return await ae(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:s,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(W(a))return{data:null,error:a};throw a}}async _deleteCustomProvider(e){try{return await ae(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(s){if(W(s))return{data:null,error:s};throw s}}async _adminListPasskeys(e){hn(this.experimental),Qn(e.userId);try{return await ae(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(W(s))return{data:null,error:s};throw s}}async _adminDeletePasskey(e){hn(this.experimental),Qn(e.userId),Qn(e.passkeyId);try{return await ae(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(s){if(W(s))return{data:null,error:s};throw s}}}function Mv(n={}){return{getItem:e=>n[e]||null,setItem:(e,s)=>{n[e]=s},removeItem:e=>{delete n[e]}}}globalThis&&Yw()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class yj extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}function vj(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function Jw(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))throw new Error(`@supabase/auth-js: Address "${n}" is invalid.`);return n.toLowerCase()}function bj(n){return parseInt(n,16)}function wj(n){const e=new TextEncoder().encode(n);return"0x"+Array.from(e,a=>a.toString(16).padStart(2,"0")).join("")}function xj(n){var e;const{chainId:s,domain:a,expirationTime:l,issuedAt:u=new Date,nonce:c,notBefore:d,requestId:m,resources:p,scheme:g,uri:v,version:w}=n;{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(!a)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(c&&c.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${c}`);if(!v)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(w!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${w}`);if(!((e=n.statement)===null||e===void 0)&&e.includes(` `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${n.statement}`)}const _=Jw(n.address),S=g?`${g}://${a}`:a,E=n.statement?`${n.statement} `:"",k=`${S} wants you to sign in with your Ethereum account: ${_} ${E}`;let C=`URI: ${v} Version: ${w} Chain ID: ${s}${c?` Nonce: ${c}`:""} Issued At: ${u.toISOString()}`;if(l&&(C+=` Expiration Time: ${l.toISOString()}`),d&&(C+=` Not Before: ${d.toISOString()}`),m&&(C+=` Request ID: ${m}`),p){let N=` Resources:`;for(const O of p){if(!O||typeof O!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${O}`);N+=` - ${O}`}C+=N}return`${k} ${C}`}class st extends Error{constructor({message:e,code:s,cause:a,name:l}){var u;super(e,{cause:a}),this.__isWebAuthnError=!0,this.name=(u=l??(a instanceof Error?a.name:void 0))!==null&&u!==void 0?u:"Unknown Error",this.code=s}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class Xl extends st{constructor(e,s){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s,message:e}),this.name="WebAuthnUnknownError",this.originalError=s}}function _j({error:n,options:e}){var s,a,l;const{publicKey:u}=e;if(!u)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new st({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else if(n.name==="ConstraintError"){if(((s=u.authenticatorSelection)===null||s===void 0?void 0:s.requireResidentKey)===!0)return new st({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:n});if(e.mediation==="conditional"&&((a=u.authenticatorSelection)===null||a===void 0?void 0:a.userVerification)==="required")return new st({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:n});if(((l=u.authenticatorSelection)===null||l===void 0?void 0:l.userVerification)==="required")return new st({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:n})}else{if(n.name==="InvalidStateError")return new st({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:n});if(n.name==="NotAllowedError")return new st({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="NotSupportedError")return u.pubKeyCredParams.filter(d=>d.type==="public-key").length===0?new st({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:n}):new st({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:n});if(n.name==="SecurityError"){const c=window.location.hostname;if(Qw(c)){if(u.rp.id!==c)return new st({message:`The RP ID "${u.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new st({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="TypeError"){if(u.user.id.byteLength<1||u.user.id.byteLength>64)return new st({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:n})}else if(n.name==="UnknownError")return new st({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new st({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}function Sj({error:n,options:e}){const{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(n.name==="AbortError"){if(e.signal instanceof AbortSignal)return new st({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:n})}else{if(n.name==="NotAllowedError")return new st({message:n.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n});if(n.name==="SecurityError"){const a=window.location.hostname;if(Qw(a)){if(s.rpId!==a)return new st({message:`The RP ID "${s.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:n})}else return new st({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:n})}else if(n.name==="UnknownError")return new st({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:n})}return new st({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n})}class Tj{createNewAbortSignal(){if(this.controller){const s=new Error("Cancelling existing WebAuthn API call for new one");s.name="AbortError",this.controller.abort(s)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const Ld=new Tj;function Uv(n){if(!n)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(n);const{challenge:e,user:s,excludeCredentials:a}=n,l=su(n,["challenge","user","excludeCredentials"]),u=la(e).buffer,c=Object.assign(Object.assign({},s),{id:la(s.id).buffer}),d=Object.assign(Object.assign({},l),{challenge:u,user:c});if(a&&a.length>0){d.excludeCredentials=new Array(a.length);for(let m=0;m0){u.allowCredentials=new Array(s.length);for(let c=0;cl!==null&&typeof l=="object"&&!Array.isArray(l),s=l=>l instanceof ArrayBuffer||ArrayBuffer.isView(l),a={};for(const l of n)if(l)for(const u in l){const c=l[u];if(c!==void 0)if(Array.isArray(c))a[u]=c;else if(s(c))a[u]=c;else if(e(c)){const d=a[u];e(d)?a[u]=Ql(d,c):a[u]=Ql(c)}else a[u]=c}return a}function Rj(n,e){return Ql(Ej,n,e||{})}function Cj(n,e){return Ql(Aj,n,e||{})}class kj{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:s,friendlyName:a,signal:l},u){var c;try{const{data:d,error:m}=await this.client.mfa.challenge({factorId:e,webauthn:s});if(!d)return{data:null,error:m};const p=l??Ld.createNewAbortSignal();if(d.webauthn.type==="create"){const{user:g}=d.webauthn.credential_options.publicKey;if(!g.name){const v=a;if(v)g.name=`${g.id}:${v}`;else{const _=(await this.client.getUser()).data.user,S=((c=_==null?void 0:_.user_metadata)===null||c===void 0?void 0:c.name)||(_==null?void 0:_.email)||(_==null?void 0:_.id)||"User";g.name=`${g.id}:${S}`}}g.displayName||(g.displayName=g.name)}switch(d.webauthn.type){case"create":{const g=Rj(d.webauthn.credential_options.publicKey,u==null?void 0:u.create),{data:v,error:w}=await Zw({publicKey:g,signal:p});return v?{data:{factorId:e,challengeId:d.id,webauthn:{type:d.webauthn.type,credential_response:v}},error:null}:{data:null,error:w}}case"request":{const g=Cj(d.webauthn.credential_options.publicKey,u==null?void 0:u.request),{data:v,error:w}=await Ww(Object.assign(Object.assign({},d.webauthn.credential_options),{publicKey:g,signal:p}));return v?{data:{factorId:e,challengeId:d.id,webauthn:{type:d.webauthn.type,credential_response:v}},error:null}:{data:null,error:w}}}}catch(d){return W(d)?{data:null,error:d}:{data:null,error:new fn("Unexpected error in challenge",d)}}}async _verify({challengeId:e,factorId:s,webauthn:a}){return this.client.mfa.verify({factorId:s,challengeId:e,webauthn:a})}async _authenticate({factorId:e,webauthn:{rpId:s=typeof window<"u"?window.location.hostname:void 0,rpOrigins:a=typeof window<"u"?[window.location.origin]:void 0,signal:l}={}},u){if(!s)return{data:null,error:new Br("rpId is required for WebAuthn authentication")};try{if(!Jl())return{data:null,error:new fn("Browser does not support WebAuthn",null)};const{data:c,error:d}=await this.challenge({factorId:e,webauthn:{rpId:s,rpOrigins:a},signal:l},{request:u});if(!c)return{data:null,error:d};const{webauthn:m}=c;return this._verify({factorId:e,challengeId:c.challengeId,webauthn:{type:m.type,rpId:s,rpOrigins:a,credential_response:m.credential_response}})}catch(c){return W(c)?{data:null,error:c}:{data:null,error:new fn("Unexpected error in authenticate",c)}}}async _register({friendlyName:e,webauthn:{rpId:s=typeof window<"u"?window.location.hostname:void 0,rpOrigins:a=typeof window<"u"?[window.location.origin]:void 0,signal:l}={}},u){if(!s)return{data:null,error:new Br("rpId is required for WebAuthn registration")};try{if(!Jl())return{data:null,error:new fn("Browser does not support WebAuthn",null)};const{data:c,error:d}=await this._enroll({friendlyName:e});if(!c)return await this.client.mfa.listFactors().then(g=>{var v;return(v=g.data)===null||v===void 0?void 0:v.all.find(w=>w.factor_type==="webauthn"&&w.friendly_name===e&&w.status!=="unverified")}).then(g=>g?this.client.mfa.unenroll({factorId:g==null?void 0:g.id}):void 0),{data:null,error:d};const{data:m,error:p}=await this._challenge({factorId:c.id,friendlyName:c.friendly_name,webauthn:{rpId:s,rpOrigins:a},signal:l},{create:u});return m?this._verify({factorId:c.id,challengeId:m.challengeId,webauthn:{rpId:s,rpOrigins:a,type:m.webauthn.type,credential_response:m.webauthn.credential_response}}):{data:null,error:p}}catch(c){return W(c)?{data:null,error:c}:{data:null,error:new fn("Unexpected error in register",c)}}}}vj();const jj={url:Dk,storageKey:Mk,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Uk,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},Ws={};class Lr{get jwks(){var e,s;return(s=(e=Ws[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&s!==void 0?s:{keys:[]}}set jwks(e){Ws[this.storageKey]=Object.assign(Object.assign({},Ws[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,s;return(s=(e=Ws[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&s!==void 0?s:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ws[this.storageKey]=Object.assign(Object.assign({},Ws[this.storageKey]),{cachedAt:e})}constructor(e){var s,a,l;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const u=Object.assign(Object.assign({},jj),e);if(this.storageKey=u.storageKey,this.instanceID=(s=Lr.nextInstanceID[this.storageKey])!==null&&s!==void 0?s:0,Lr.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!u.debug,typeof u.debug=="function"&&(this.logger=u.debug),this.instanceID>0&&wt()){const c=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(c),this.logDebugMessages&&console.trace(c)}if(this.persistSession=u.persistSession,this.autoRefreshToken=u.autoRefreshToken,this.experimental=(a=u.experimental)!==null&&a!==void 0?a:{},this.admin=new gj({url:u.url,headers:u.headers,fetch:u.fetch,experimental:this.experimental}),this.url=u.url,this.headers=u.headers,this.fetch=Xw(u.fetch),this.detectSessionInUrl=u.detectSessionInUrl,this.flowType=u.flowType,this.hasCustomAuthorizationHeader=u.hasCustomAuthorizationHeader,this.throwOnError=u.throwOnError,this.lockAcquireTimeout=u.lockAcquireTimeout,u.lock!=null&&(this.lock=u.lock),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 kj(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(u.storage?this.storage=u.storage:Yw()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Mv(this.memoryStorage)),u.userStorage&&(this.userStorage=u.userStorage)):(this.memoryStorage={},this.storage=Mv(this.memoryStorage)),wt()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(c){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",c)}(l=this.broadcastChannel)===null||l===void 0||l.addEventListener("message",async c=>{this._debug("received broadcast notification from other tab or client",c),(c.data.event==="TOKEN_REFRESHED"||c.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(c.data.event,c.data.session,!1)}catch(d){this._debug("#broadcastChannel","error",d)}})}u.skipAutoInitialize||this.initialize().catch(c=>{this._debug("#initialize()","error",c)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Iw}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();const s=await this.initializePromise,a=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(const l of a)await this._notifyAllSubscribers(l.event,l.session,l.broadcast);return s}async _initialize(){var e;try{let s={},a="none";if(wt()&&(s=Jk(window.location.href),this._isImplicitGrantCallback(s)?a="implicit":await this._isPKCECallback(s)&&(a="pkce")),wt()&&this.detectSessionInUrl&&a!=="none"){const{data:l,error:u}=await this._getSessionFromURL(s,a);if(u){if(this._debug("#_initialize()","error detecting session from URL",u),Pk(u)){const m=(e=u.details)===null||e===void 0?void 0:e.code;if(m==="identity_already_exists"||m==="identity_not_found"||m==="single_identity_not_deletable")return{error:u}}return{error:u}}const{session:c,redirectType:d}=l;return this._debug("#_initialize()","detected session in URL",c,"redirect type",d),await this._saveSession(c),setTimeout(async()=>{d==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",c):await this._notifyAllSubscribers("SIGNED_IN",c)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(s){return W(s)?this._returnResult({error:s}):this._returnResult({error:new fn("Unexpected error during initialization",s)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var s,a,l;try{const u=await ae(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(a=(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.data)!==null&&a!==void 0?a:{},gotrue_meta_security:{captcha_token:(l=e==null?void 0:e.options)===null||l===void 0?void 0:l.captchaToken}},xform:tn}),{data:c,error:d}=u;if(d||!c)return this._returnResult({data:{user:null,session:null},error:d});const m=c.session,p=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",m)),this._returnResult({data:{user:p,session:m},error:null})}catch(u){if(W(u))return this._returnResult({data:{user:null,session:null},error:u});throw u}}async signUp(e){var s,a,l;try{let u;if("email"in e){const{email:g,password:v,options:w}=e;let _=null,S=null;this.flowType==="pkce"&&([_,S]=await ns(this.storage,this.storageKey)),u=await ae(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:w==null?void 0:w.emailRedirectTo,body:{email:g,password:v,data:(s=w==null?void 0:w.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:w==null?void 0:w.captchaToken},code_challenge:_,code_challenge_method:S},xform:tn})}else if("phone"in e){const{phone:g,password:v,options:w}=e;u=await ae(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:g,password:v,data:(a=w==null?void 0:w.data)!==null&&a!==void 0?a:{},channel:(l=w==null?void 0:w.channel)!==null&&l!==void 0?l:"sms",gotrue_meta_security:{captcha_token:w==null?void 0:w.captchaToken}},xform:tn})}else throw new _l("You must provide either an email or phone number and a password");const{data:c,error:d}=u;if(d||!c)return await We(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:d});const m=c.session,p=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",m)),this._returnResult({data:{user:p,session:m},error:null})}catch(u){if(await We(this.storage,`${this.storageKey}-code-verifier`),W(u))return this._returnResult({data:{user:null,session:null},error:u});throw u}}async signInWithPassword(e){try{let s;if("email"in e){const{email:u,password:c,options:d}=e;s=await ae(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:u,password:c,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:Nv})}else if("phone"in e){const{phone:u,password:c,options:d}=e;s=await ae(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:u,password:c,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:Nv})}else throw new _l("You must provide either an email or phone number and a password");const{data:a,error:l}=s;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a||!a.session||!a.user){const u=new Zs;return this._returnResult({data:{user:null,session:null},error:u})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:Object.assign({user:a.user,session:a.session},a.weak_password?{weakPassword:a.weak_password}:null),error:l})}catch(s){if(W(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithOAuth(e){var s,a,l,u;return await this._handleProviderSignIn(e.provider,{redirectTo:(s=e.options)===null||s===void 0?void 0:s.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:(u=e.options)===null||u===void 0?void 0:u.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e)):this._exchangeCodeForSession(e)}async signInWithWeb3(e){const{chain:s}=e;switch(s){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${s}"`)}}async signInWithEthereum(e){var s,a,l,u,c,d,m,p,g,v,w;let _,S;if("message"in e)_=e.message,S=e.signature;else{const{chain:E,wallet:k,statement:C,options:N}=e;let O;if(wt())if(typeof k=="object")O=k;else{const Z=window;if("ethereum"in Z&&typeof Z.ethereum=="object"&&"request"in Z.ethereum&&typeof Z.ethereum.request=="function")O=Z.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof k!="object"||!(N!=null&&N.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");O=k}const z=new URL((s=N==null?void 0:N.url)!==null&&s!==void 0?s:window.location.href),F=await O.request({method:"eth_requestAccounts"}).then(Z=>Z).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!F||F.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const J=Jw(F[0]);let G=(a=N==null?void 0:N.signInWithEthereum)===null||a===void 0?void 0:a.chainId;if(!G){const Z=await O.request({method:"eth_chainId"});G=bj(Z)}const Y={domain:z.host,address:J,statement:C,uri:z.href,version:"1",chainId:G,nonce:(l=N==null?void 0:N.signInWithEthereum)===null||l===void 0?void 0:l.nonce,issuedAt:(c=(u=N==null?void 0:N.signInWithEthereum)===null||u===void 0?void 0:u.issuedAt)!==null&&c!==void 0?c:new Date,expirationTime:(d=N==null?void 0:N.signInWithEthereum)===null||d===void 0?void 0:d.expirationTime,notBefore:(m=N==null?void 0:N.signInWithEthereum)===null||m===void 0?void 0:m.notBefore,requestId:(p=N==null?void 0:N.signInWithEthereum)===null||p===void 0?void 0:p.requestId,resources:(g=N==null?void 0:N.signInWithEthereum)===null||g===void 0?void 0:g.resources};_=xj(Y),S=await O.request({method:"personal_sign",params:[wj(_),J]})}try{const{data:E,error:k}=await ae(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:_,signature:S},!((v=e.options)===null||v===void 0)&&v.captchaToken?{gotrue_meta_security:{captcha_token:(w=e.options)===null||w===void 0?void 0:w.captchaToken}}:null),xform:tn});if(k)throw k;if(!E||!E.session||!E.user){const C=new Zs;return this._returnResult({data:{user:null,session:null},error:C})}return E.session&&(await this._saveSession(E.session),await this._notifyAllSubscribers("SIGNED_IN",E.session)),this._returnResult({data:Object.assign({},E),error:k})}catch(E){if(W(E))return this._returnResult({data:{user:null,session:null},error:E});throw E}}async signInWithSolana(e){var s,a,l,u,c,d,m,p,g,v,w,_;let S,E;if("message"in e)S=e.message,E=e.signature;else{const{chain:k,wallet:C,statement:N,options:O}=e;let z;if(wt())if(typeof C=="object")z=C;else{const J=window;if("solana"in J&&typeof J.solana=="object"&&("signIn"in J.solana&&typeof J.solana.signIn=="function"||"signMessage"in J.solana&&typeof J.solana.signMessage=="function"))z=J.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof C!="object"||!(O!=null&&O.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");z=C}const F=new URL((s=O==null?void 0:O.url)!==null&&s!==void 0?s:window.location.href);if("signIn"in z&&z.signIn){const J=await z.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},O==null?void 0:O.signInWithSolana),{version:"1",domain:F.host,uri:F.href}),N?{statement:N}:null));let G;if(Array.isArray(J)&&J[0]&&typeof J[0]=="object")G=J[0];else if(J&&typeof J=="object"&&"signedMessage"in J&&"signature"in J)G=J;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in G&&"signature"in G&&(typeof G.signedMessage=="string"||G.signedMessage instanceof Uint8Array)&&G.signature instanceof Uint8Array)S=typeof G.signedMessage=="string"?G.signedMessage:new TextDecoder().decode(G.signedMessage),E=G.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in z)||typeof z.signMessage!="function"||!("publicKey"in z)||typeof z!="object"||!z.publicKey||!("toBase58"in z.publicKey)||typeof z.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");S=[`${F.host} wants you to sign in with your Solana account:`,z.publicKey.toBase58(),...N?["",N,""]:[""],"Version: 1",`URI: ${F.href}`,`Issued At: ${(l=(a=O==null?void 0:O.signInWithSolana)===null||a===void 0?void 0:a.issuedAt)!==null&&l!==void 0?l:new Date().toISOString()}`,...!((u=O==null?void 0:O.signInWithSolana)===null||u===void 0)&&u.notBefore?[`Not Before: ${O.signInWithSolana.notBefore}`]:[],...!((c=O==null?void 0:O.signInWithSolana)===null||c===void 0)&&c.expirationTime?[`Expiration Time: ${O.signInWithSolana.expirationTime}`]:[],...!((d=O==null?void 0:O.signInWithSolana)===null||d===void 0)&&d.chainId?[`Chain ID: ${O.signInWithSolana.chainId}`]:[],...!((m=O==null?void 0:O.signInWithSolana)===null||m===void 0)&&m.nonce?[`Nonce: ${O.signInWithSolana.nonce}`]:[],...!((p=O==null?void 0:O.signInWithSolana)===null||p===void 0)&&p.requestId?[`Request ID: ${O.signInWithSolana.requestId}`]:[],...!((v=(g=O==null?void 0:O.signInWithSolana)===null||g===void 0?void 0:g.resources)===null||v===void 0)&&v.length?["Resources",...O.signInWithSolana.resources.map(G=>`- ${G}`)]:[]].join(` `);const J=await z.signMessage(new TextEncoder().encode(S),"utf8");if(!J||!(J instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");E=J}}try{const{data:k,error:C}=await ae(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:S,signature:ls(E)},!((w=e.options)===null||w===void 0)&&w.captchaToken?{gotrue_meta_security:{captcha_token:(_=e.options)===null||_===void 0?void 0:_.captchaToken}}:null),xform:tn});if(C)throw C;if(!k||!k.session||!k.user){const N=new Zs;return this._returnResult({data:{user:null,session:null},error:N})}return k.session&&(await this._saveSession(k.session),await this._notifyAllSubscribers("SIGNED_IN",k.session)),this._returnResult({data:Object.assign({},k),error:C})}catch(k){if(W(k))return this._returnResult({data:{user:null,session:null},error:k});throw k}}async _exchangeCodeForSession(e){const s=await un(this.storage,`${this.storageKey}-code-verifier`),[a,l]=(s??"").split("/");try{if(!a&&this.flowType==="pkce")throw new Hk;const{data:u,error:c}=await ae(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:a},xform:tn});if(await We(this.storage,`${this.storageKey}-code-verifier`),c)throw c;if(!u||!u.session||!u.user){const d=new Zs;return this._returnResult({data:{user:null,session:null,redirectType:null},error:d})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(l==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:l??null}),error:c})}catch(u){if(await We(this.storage,`${this.storageKey}-code-verifier`),W(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(e){try{const{options:s,provider:a,token:l,access_token:u,nonce:c}=e,d=await ae(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:a,id_token:l,access_token:u,nonce:c,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},xform:tn}),{data:m,error:p}=d;if(p)return this._returnResult({data:{user:null,session:null},error:p});if(!m||!m.session||!m.user){const g=new Zs;return this._returnResult({data:{user:null,session:null},error:g})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:m,error:p})}catch(s){if(W(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithOtp(e){var s,a,l,u,c;try{if("email"in e){const{email:d,options:m}=e;let p=null,g=null;this.flowType==="pkce"&&([p,g]=await ns(this.storage,this.storageKey));const{error:v}=await ae(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:d,data:(s=m==null?void 0:m.data)!==null&&s!==void 0?s:{},create_user:(a=m==null?void 0:m.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:p,code_challenge_method:g},redirectTo:m==null?void 0:m.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:v})}if("phone"in e){const{phone:d,options:m}=e,{data:p,error:g}=await ae(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:d,data:(l=m==null?void 0:m.data)!==null&&l!==void 0?l:{},create_user:(u=m==null?void 0:m.shouldCreateUser)!==null&&u!==void 0?u:!0,gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},channel:(c=m==null?void 0:m.channel)!==null&&c!==void 0?c:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:p==null?void 0:p.message_id},error:g})}throw new _l("You must provide either an email or phone number.")}catch(d){if(await We(this.storage,`${this.storageKey}-code-verifier`),W(d))return this._returnResult({data:{user:null,session:null},error:d});throw d}}async verifyOtp(e){var s,a;try{let l,u;"options"in e&&(l=(s=e.options)===null||s===void 0?void 0:s.redirectTo,u=(a=e.options)===null||a===void 0?void 0:a.captchaToken);const{data:c,error:d}=await ae(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:u}}),redirectTo:l,xform:tn});if(d)throw d;if(!c)throw new Error("An error occurred on token verification.");const m=c.session,p=c.user;return m!=null&&m.access_token&&(await this._saveSession(m),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",m)),this._returnResult({data:{user:p,session:m},error:null})}catch(l){if(W(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}}async signInWithSSO(e){var s,a,l,u,c;try{let d=null,m=null;this.flowType==="pkce"&&([d,m]=await ns(this.storage,this.storageKey));const p=await ae(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:(a=(s=e.options)===null||s===void 0?void 0:s.redirectTo)!==null&&a!==void 0?a:void 0}),!((l=e==null?void 0:e.options)===null||l===void 0)&&l.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:d,code_challenge_method:m}),headers:this.headers,xform:fj});return!((u=p.data)===null||u===void 0)&&u.url&&wt()&&!(!((c=e.options)===null||c===void 0)&&c.skipBrowserRedirect)&&window.location.assign(p.data.url),this._returnResult(p)}catch(d){if(await We(this.storage,`${this.storageKey}-code-verifier`),W(d))return this._returnResult({data:null,error:d});throw d}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:s},error:a}=e;if(a)throw a;if(!s)throw new ht;const{error:l}=await ae(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:s.access_token});return this._returnResult({data:{user:null,session:null},error:l})})}catch(e){if(W(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const s=`${this.url}/resend`;if("email"in e){const{email:a,type:l,options:u}=e;let c=null,d=null;this.flowType==="pkce"&&([c,d]=await ns(this.storage,this.storageKey));const{error:m}=await ae(this.fetch,"POST",s,{headers:this.headers,body:{email:a,type:l,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},code_challenge:c,code_challenge_method:d},redirectTo:u==null?void 0:u.emailRedirectTo});return m&&await We(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:m})}else if("phone"in e){const{phone:a,type:l,options:u}=e,{data:c,error:d}=await ae(this.fetch,"POST",s,{headers:this.headers,body:{phone:a,type:l,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:d})}throw new _l("You must provide either an email or phone number and a type")}catch(s){if(await We(this.storage,`${this.storageKey}-code-verifier`),W(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,s){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const a=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),l=(async()=>(await a,await s()))();return this.pendingInLock.push((async()=>{try{await l}catch{}})()),l}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const a=s();for(this.pendingInLock.push((async()=>{try{await a}catch{}})()),await a;this.pendingInLock.length;){const l=[...this.pendingInLock];await Promise.all(l),this.pendingInLock.splice(0,l.length)}return await a}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 s=await this.__loadSession();return await e(s)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const s=await un(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",s),s!==null&&(this._isValidSession(s)?e=s:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const a=e.expires_at?e.expires_at*1e3-Date.now()Date.now())){const d=await un(this.storage,this.storageKey);if(d&&d.refresh_token===e.refresh_token)return this._returnResult({data:{session:e},error:null})}return this._returnResult({data:{session:null},error:u})}return this._returnResult({data:{session:l},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let s;return this.lock!=null?s=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):s=await this._getUser(),s.data.user&&(this.suppressGetSessionWarning=!0),s}async _getUser(e){try{return e?await ae(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ji}):await this._useSession(async s=>{var a,l,u;const{data:c,error:d}=s;if(d)throw d;return!(!((a=c.session)===null||a===void 0)&&a.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ht}:await ae(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(u=(l=c.session)===null||l===void 0?void 0:l.access_token)!==null&&u!==void 0?u:void 0,xform:ji})})}catch(s){if(W(s))return xl(s)&&(await this._removeSession(),await We(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:s});throw s}}async updateUser(e,s={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,s)):await this._updateUser(e,s)}async _updateUser(e,s={}){try{return await this._useSession(async a=>{const{data:l,error:u}=a;if(u)throw u;if(!l.session)throw new ht;const c=l.session;let d=null,m=null;this.flowType==="pkce"&&e.email!=null&&([d,m]=await ns(this.storage,this.storageKey));const{data:p,error:g}=await ae(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:s==null?void 0:s.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:d,code_challenge_method:m}),jwt:c.access_token,xform:ji});if(g)throw g;return c.user=p.user,await this._saveSession(c),await this._notifyAllSubscribers("USER_UPDATED",c),this._returnResult({data:{user:c.user},error:null})})}catch(a){if(await We(this.storage,`${this.storageKey}-code-verifier`),W(a))return this._returnResult({data:{user:null},error:a});throw a}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ht;const s=Date.now()/1e3;let a=s,l=!0,u=null;const{payload:c}=Tl(e.access_token);if(c.exp&&(a=c.exp,l=a<=s),l){const{data:d,error:m}=await this._callRefreshToken(e.refresh_token);if(m)return this._returnResult({data:{user:null,session:null},error:m});if(!d)return{data:{user:null,session:null},error:null};u=d}else{const{data:d,error:m}=await this._getUser(e.access_token);if(m)return this._returnResult({data:{user:null,session:null},error:m});u={access_token:e.access_token,refresh_token:e.refresh_token,user:d.user,token_type:"bearer",expires_in:a-s,expires_at:a},await this._saveSession(u),await this._notifyAllSubscribers("SIGNED_IN",u)}return this._returnResult({data:{user:u.user,session:u},error:null})}catch(s){if(W(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async s=>{var a;if(!e){const{data:c,error:d}=s;if(d)throw d;e=(a=c.session)!==null&&a!==void 0?a:void 0}if(!(e!=null&&e.refresh_token))throw new ht;const{data:l,error:u}=await this._callRefreshToken(e.refresh_token);return u?this._returnResult({data:{user:null,session:null},error:u}):l?this._returnResult({data:{user:l.user,session:l},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(s){if(W(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async _getSessionFromURL(e,s){var a;try{if(!wt())throw new Sl("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Sl(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(s){case"implicit":if(this.flowType==="pkce")throw new Sv("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Sl("Not a valid implicit grant flow url.");break;default:}if(s==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Sv("No code detected.");const{data:O,error:z}=await this._exchangeCodeForSession(e.code);if(z)throw z;const F=new URL(window.location.href);return F.searchParams.delete("code"),window.history.replaceState(window.history.state,"",F.toString()),{data:{session:O.session,redirectType:(a=O.redirectType)!==null&&a!==void 0?a:null},error:null}}const{provider_token:l,provider_refresh_token:u,access_token:c,refresh_token:d,expires_in:m,expires_at:p,token_type:g}=e;if(!c||!m||!d||!g)throw new Sl("No session defined in URL");const v=Math.round(Date.now()/1e3),w=parseInt(m);let _=v+w;p&&(_=parseInt(p));const S=_-v;S*1e3<=ti&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${S}s, should have been closer to ${w}s`);const E=_-w;v-E>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",E,_,v):v-E<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",E,_,v);const{data:k,error:C}=await this._getUser(c);if(C)throw C;const N={provider_token:l,provider_refresh_token:u,access_token:c,expires_in:w,expires_at:_,refresh_token:d,token_type:g,user:k.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:N,redirectType:e.type},error:null})}catch(l){if(W(l))return this._returnResult({data:{session:null,redirectType:null},error:l});throw l}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){const s=await un(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&s)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async s=>{var a;const l=async()=>{await this._removeSession(),await We(this.storage,`${this.storageKey}-code-verifier`)},{data:u,error:c}=s;if(c&&!xl(c))return this._returnResult({error:c});const d=(a=u.session)===null||a===void 0?void 0:a.access_token;if(d){const{error:m}=await this.admin.signOut(d,e);if(m&&!(Vk(m)&&(m.status===404||m.status===401||m.status===403)||xl(m)))return e!=="others"&&await l(),this._returnResult({error:m})}return e!=="others"&&await l(),this._returnResult({error:null})})}onAuthStateChange(e){const s=Xk(),a={id:s,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",s),this.stateChangeEmitters.delete(s)}};return this._debug("#onAuthStateChange()","registered callback with id",s),this.stateChangeEmitters.set(s,a),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(s)}):await this._emitInitialSession(s)))(),{data:{subscription:a}}}async _emitInitialSession(e){return await this._useSession(async s=>{var a,l;try{const{data:{session:u},error:c}=s;if(c)throw c;await((a=this.stateChangeEmitters.get(e))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",u)),this._debug("INITIAL_SESSION","callback id",e,"session",u)}catch(u){await((l=this.stateChangeEmitters.get(e))===null||l===void 0?void 0:l.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",u),xl(u)?console.warn(u):console.error(u)}})}async resetPasswordForEmail(e,s={}){let a=null,l=null;this.flowType==="pkce"&&([a,l]=await ns(this.storage,this.storageKey,!0));try{return await ae(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:a,code_challenge_method:l,gotrue_meta_security:{captcha_token:s.captchaToken}},headers:this.headers,redirectTo:s.redirectTo})}catch(u){if(await We(this.storage,`${this.storageKey}-code-verifier`),W(u))return this._returnResult({data:null,error:u});throw u}}async getUserIdentities(){var e;try{const{data:s,error:a}=await this.getUser();if(a)throw a;return this._returnResult({data:{identities:(e=s.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(s){if(W(s))return this._returnResult({data:null,error:s});throw s}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var s;try{const{data:a,error:l}=await this._useSession(async u=>{var c,d,m,p,g;const{data:v,error:w}=u;if(w)throw w;const _=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(c=e.options)===null||c===void 0?void 0:c.redirectTo,scopes:(d=e.options)===null||d===void 0?void 0:d.scopes,queryParams:(m=e.options)===null||m===void 0?void 0:m.queryParams,skipBrowserRedirect:!0});return await ae(this.fetch,"GET",_,{headers:this.headers,jwt:(g=(p=v.session)===null||p===void 0?void 0:p.access_token)!==null&&g!==void 0?g:void 0})});if(l)throw l;return wt()&&!(!((s=e.options)===null||s===void 0)&&s.skipBrowserRedirect)&&window.location.assign(a==null?void 0:a.url),this._returnResult({data:{provider:e.provider,url:a==null?void 0:a.url},error:null})}catch(a){if(W(a))return this._returnResult({data:{provider:e.provider,url:null},error:a});throw a}}async linkIdentityIdToken(e){return await this._useSession(async s=>{var a;try{const{error:l,data:{session:u}}=s;if(l)throw l;const{options:c,provider:d,token:m,access_token:p,nonce:g}=e,v=await ae(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(a=u==null?void 0:u.access_token)!==null&&a!==void 0?a:void 0,body:{provider:d,id_token:m,access_token:p,nonce:g,link_identity:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken}},xform:tn}),{data:w,error:_}=v;return _?this._returnResult({data:{user:null,session:null},error:_}):!w||!w.session||!w.user?this._returnResult({data:{user:null,session:null},error:new Zs}):(w.session&&(await this._saveSession(w.session),await this._notifyAllSubscribers("USER_UPDATED",w.session)),this._returnResult({data:w,error:_}))}catch(l){if(await We(this.storage,`${this.storageKey}-code-verifier`),W(l))return this._returnResult({data:{user:null,session:null},error:l});throw l}})}async unlinkIdentity(e){try{return await this._useSession(async s=>{var a,l;const{data:u,error:c}=s;if(c)throw c;return await ae(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(l=(a=u.session)===null||a===void 0?void 0:a.access_token)!==null&&l!==void 0?l:void 0})})}catch(s){if(W(s))return this._returnResult({data:null,error:s});throw s}}async _refreshAccessToken(e){const s="#_refreshAccessToken()";this._debug(s,"begin");try{const a=Date.now();return await Wk(async l=>(l>0&&await Zk(200*Math.pow(2,l-1)),this._debug(s,"refreshing attempt",l),await ae(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:tn})),(l,u)=>{const c=200*Math.pow(2,l);return u&&Tv(u)&&Date.now()+c-aDate.now())?this._debug(l,"proactive refresh failed, access token still valid — preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:c,expiresAt:Date.now()+Nk},(s=this.refreshingDeferred)===null||s===void 0||s.resolve(c),c}throw(a=this.refreshingDeferred)===null||a===void 0||a.reject(u),u}finally{this.refreshingDeferred=null,this._debug(l,"end")}}async _notifyAllSubscribers(e,s,a=!0){if(this._pendingInitNotifications!==null&&a){this._pendingInitNotifications.push({event:e,session:s,broadcast:a});return}const l=`#_notifyAllSubscribers(${e})`;this._debug(l,"begin",s,`broadcast = ${a}`);try{this.broadcastChannel&&a&&this.broadcastChannel.postMessage({event:e,session:s});const u=[],c=Array.from(this.stateChangeEmitters.values()).map(async d=>{try{await d.callback(e,s)}catch(m){u.push(m)}});if(await Promise.all(c),u.length>0){for(let d=0;dthis._autoRefreshTokenTick(),ti);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const s=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=s,s&&typeof s=="object"&&typeof s.unref=="function"?s.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(s)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const s=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,s&&clearTimeout(s)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async s=>{const{data:{session:a}}=s;if(!a||!a.refresh_token||!a.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const l=Math.floor((a.expires_at*1e3-e)/ti);this._debug("#_autoRefreshTokenTick()",`access token expires in ${l} ticks, a tick lasts ${ti}ms, refresh threshold is ${gr} ticks`),l<=gr&&await this._callRefreshToken(a.refresh_token)})}catch(s){console.error("Auto refresh tick failed with error. This is likely a transient error.",s)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof yj)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{const e=Date.now();try{await this._useSession(async s=>{const{data:{session:a}}=s;if(!a||!a.refresh_token||!a.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const l=Math.floor((a.expires_at*1e3-e)/ti);this._debug("#_autoRefreshTokenTick()",`access token expires in ${l} ticks, a tick lasts ${ti}ms, refresh threshold is ${gr} ticks`),l<=gr&&await this._callRefreshToken(a.refresh_token)})}catch(s){console.error("Auto refresh tick failed with error. This is likely a transient error.",s)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!wt()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const s=`#_onVisibilityChanged(${e})`;if(this._debug(s,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(s,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(s,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,s,a){const l=[`provider=${encodeURIComponent(s)}`];if(a!=null&&a.redirectTo&&l.push(`redirect_to=${encodeURIComponent(a.redirectTo)}`),a!=null&&a.scopes&&l.push(`scopes=${encodeURIComponent(a.scopes)}`),this.flowType==="pkce"){const[u,c]=await ns(this.storage,this.storageKey),d=new URLSearchParams({code_challenge:`${encodeURIComponent(u)}`,code_challenge_method:`${encodeURIComponent(c)}`});l.push(d.toString())}if(a!=null&&a.queryParams){const u=new URLSearchParams(a.queryParams);l.push(u.toString())}return a!=null&&a.skipBrowserRedirect&&l.push(`skip_http_redirect=${a.skipBrowserRedirect}`),`${e}?${l.join("&")}`}async _unenroll(e){try{return await this._useSession(async s=>{var a;const{data:l,error:u}=s;return u?this._returnResult({data:null,error:u}):await ae(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(a=l==null?void 0:l.session)===null||a===void 0?void 0:a.access_token})})}catch(s){if(W(s))return this._returnResult({data:null,error:s});throw s}}async _enroll(e){try{return await this._useSession(async s=>{var a,l;const{data:u,error:c}=s;if(c)return this._returnResult({data:null,error:c});const d=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:m,error:p}=await ae(this.fetch,"POST",`${this.url}/factors`,{body:d,headers:this.headers,jwt:(a=u==null?void 0:u.session)===null||a===void 0?void 0:a.access_token});return p?this._returnResult({data:null,error:p}):(e.factorType==="totp"&&m.type==="totp"&&(!((l=m==null?void 0:m.totp)===null||l===void 0)&&l.qr_code)&&(m.totp.qr_code=`data:image/svg+xml;utf-8,${m.totp.qr_code}`),this._returnResult({data:m,error:null}))})}catch(s){if(W(s))return this._returnResult({data:null,error:s});throw s}}async _verify(e){const s=async()=>{try{return await this._useSession(async a=>{var l;const{data:u,error:c}=a;if(c)return this._returnResult({data:null,error:c});const d=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Lv(e.webauthn.credential_response):zv(e.webauthn.credential_response)})}:{code:e.code}),{data:m,error:p}=await ae(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:d,headers:this.headers,jwt:(l=u==null?void 0:u.session)===null||l===void 0?void 0:l.access_token});return p?this._returnResult({data:null,error:p}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+m.expires_in},m)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",m),this._returnResult({data:m,error:p}))})}catch(a){if(W(a))return this._returnResult({data:null,error:a});throw a}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,s):s()}async _challenge(e){const s=async()=>{try{return await this._useSession(async a=>{var l;const{data:u,error:c}=a;if(c)return this._returnResult({data:null,error:c});const d=await ae(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(l=u==null?void 0:u.session)===null||l===void 0?void 0:l.access_token});if(d.error)return d;const{data:m}=d;if(m.type!=="webauthn")return{data:m,error:null};switch(m.webauthn.type){case"create":return{data:Object.assign(Object.assign({},m),{webauthn:Object.assign(Object.assign({},m.webauthn),{credential_options:Object.assign(Object.assign({},m.webauthn.credential_options),{publicKey:Uv(m.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},m),{webauthn:Object.assign(Object.assign({},m.webauthn),{credential_options:Object.assign(Object.assign({},m.webauthn.credential_options),{publicKey:Bv(m.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(a){if(W(a))return this._returnResult({data:null,error:a});throw a}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,s):s()}async _challengeAndVerify(e){const{data:s,error:a}=await this._challenge({factorId:e.factorId});return a?this._returnResult({data:null,error:a}):await this._verify({factorId:e.factorId,challengeId:s.id,code:e.code})}async _listFactors(){var e;const{data:{user:s},error:a}=await this.getUser();if(a)return{data:null,error:a};const l={all:[],phone:[],totp:[],webauthn:[]};for(const u of(e=s==null?void 0:s.factors)!==null&&e!==void 0?e:[])l.all.push(u),u.status==="verified"&&l[u.factor_type].push(u);return{data:l,error:null}}async _getAuthenticatorAssuranceLevel(e){var s,a,l,u;if(e)try{const{payload:_}=Tl(e);let S=null;_.aal&&(S=_.aal);let E=S;const{data:{user:k},error:C}=await this.getUser(e);if(C)return this._returnResult({data:null,error:C});((a=(s=k==null?void 0:k.factors)===null||s===void 0?void 0:s.filter(z=>z.status==="verified"))!==null&&a!==void 0?a:[]).length>0&&(E="aal2");const O=_.amr||[];return{data:{currentLevel:S,nextLevel:E,currentAuthenticationMethods:O},error:null}}catch(_){if(W(_))return this._returnResult({data:null,error:_});throw _}const{data:{session:c},error:d}=await this.getSession();if(d)return this._returnResult({data:null,error:d});if(!c)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:m}=Tl(c.access_token);let p=null;m.aal&&(p=m.aal);let g=p;((u=(l=c.user.factors)===null||l===void 0?void 0:l.filter(_=>_.status==="verified"))!==null&&u!==void 0?u:[]).length>0&&(g="aal2");const w=m.amr||[];return{data:{currentLevel:p,nextLevel:g,currentAuthenticationMethods:w},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async s=>{const{data:{session:a},error:l}=s;return l?this._returnResult({data:null,error:l}):a?await ae(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:a.access_token,xform:u=>({data:u,error:null})}):this._returnResult({data:null,error:new ht})})}catch(s){if(W(s))return this._returnResult({data:null,error:s});throw s}}async _approveAuthorization(e,s){try{return await this._useSession(async a=>{const{data:{session:l},error:u}=a;if(u)return this._returnResult({data:null,error:u});if(!l)return this._returnResult({data:null,error:new ht});const c=await ae(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:l.access_token,body:{action:"approve"},xform:d=>({data:d,error:null})});return c.data&&c.data.redirect_url&&wt()&&!(s!=null&&s.skipBrowserRedirect)&&window.location.assign(c.data.redirect_url),c})}catch(a){if(W(a))return this._returnResult({data:null,error:a});throw a}}async _denyAuthorization(e,s){try{return await this._useSession(async a=>{const{data:{session:l},error:u}=a;if(u)return this._returnResult({data:null,error:u});if(!l)return this._returnResult({data:null,error:new ht});const c=await ae(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:l.access_token,body:{action:"deny"},xform:d=>({data:d,error:null})});return c.data&&c.data.redirect_url&&wt()&&!(s!=null&&s.skipBrowserRedirect)&&window.location.assign(c.data.redirect_url),c})}catch(a){if(W(a))return this._returnResult({data:null,error:a});throw a}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:s},error:a}=e;return a?this._returnResult({data:null,error:a}):s?await ae(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,xform:l=>({data:l,error:null})}):this._returnResult({data:null,error:new ht})})}catch(e){if(W(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async s=>{const{data:{session:a},error:l}=s;return l?this._returnResult({data:null,error:l}):a?(await ae(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:a.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new ht})})}catch(s){if(W(s))return this._returnResult({data:null,error:s});throw s}}async fetchJwk(e,s={keys:[]}){let a=s.keys.find(d=>d.kid===e);if(a)return a;const l=Date.now();if(a=this.jwks.keys.find(d=>d.kid===e),a&&this.jwks_cached_at+Lk>l)return a;const{data:u,error:c}=await ae(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(c)throw c;return!u.keys||u.keys.length===0||(this.jwks=u,this.jwks_cached_at=l,a=u.keys.find(d=>d.kid===e),!a)?null:a}async getClaims(e,s={}){try{let a=e;if(!a){const{data:_,error:S}=await this.getSession();if(S||!_.session)return this._returnResult({data:null,error:S});a=_.session.access_token}const{header:l,payload:u,signature:c,raw:{header:d,payload:m}}=Tl(a);if(!(s!=null&&s.allowExpired))try{rj(u.exp)}catch(_){throw new Fl(_ instanceof Error?_.message:"JWT validation failed")}const p=!l.alg||l.alg.startsWith("HS")||!l.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(l.kid,s!=null&&s.keys?{keys:s.keys}:s==null?void 0:s.jwks);if(!p){const{error:_}=await this.getUser(a);if(_)throw _;return{data:{claims:u,header:l,signature:c},error:null}}const g=oj(l.alg),v=await crypto.subtle.importKey("jwk",p,g,!0,["verify"]);if(!await crypto.subtle.verify(g,v,c,Fk(`${d}.${m}`)))throw new Fl("Invalid JWT signature");return{data:{claims:u,header:l,signature:c},error:null}}catch(a){if(W(a))return this._returnResult({data:null,error:a});throw a}}async signInWithPasskey(e){var s,a,l;hn(this.experimental);try{if(!Jl())return this._returnResult({data:null,error:new fn("Browser does not support WebAuthn",null)});const{data:u,error:c}=await this._startPasskeyAuthentication({options:{captchaToken:(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.captchaToken}});if(c||!u)return this._returnResult({data:null,error:c});const d=Bv(u.options),m=(l=(a=e==null?void 0:e.options)===null||a===void 0?void 0:a.signal)!==null&&l!==void 0?l:Ld.createNewAbortSignal(),{data:p,error:g}=await Ww({publicKey:d,signal:m});if(g||!p)return this._returnResult({data:null,error:g??new fn("WebAuthn ceremony failed",null)});const v=zv(p);return this._verifyPasskeyAuthentication({challengeId:u.challenge_id,credential:v})}catch(u){if(W(u))return this._returnResult({data:null,error:u});throw u}}async registerPasskey(e){var s,a;hn(this.experimental);try{if(!Jl())return this._returnResult({data:null,error:new fn("Browser does not support WebAuthn",null)});const{data:l,error:u}=await this._startPasskeyRegistration();if(u||!l)return this._returnResult({data:null,error:u});const c=Uv(l.options),d=(a=(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.signal)!==null&&a!==void 0?a:Ld.createNewAbortSignal(),{data:m,error:p}=await Zw({publicKey:c,signal:d});if(p||!m)return this._returnResult({data:null,error:p??new fn("WebAuthn ceremony failed",null)});const g=Lv(m);return this._verifyPasskeyRegistration({challengeId:l.challenge_id,credential:g})}catch(l){if(W(l))return this._returnResult({data:null,error:l});throw l}}async _startPasskeyRegistration(){hn(this.experimental);try{return await this._useSession(async e=>{const{data:{session:s},error:a}=e;if(a)return this._returnResult({data:null,error:a});if(!s)return this._returnResult({data:null,error:new ht});const{data:l,error:u}=await ae(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:s.access_token,body:{}});return u?this._returnResult({data:null,error:u}):this._returnResult({data:l,error:null})})}catch(e){if(W(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){hn(this.experimental);try{return await this._useSession(async s=>{const{data:{session:a},error:l}=s;if(l)return this._returnResult({data:null,error:l});if(!a)return this._returnResult({data:null,error:new ht});const{data:u,error:c}=await ae(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:a.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return c?this._returnResult({data:null,error:c}):this._returnResult({data:u,error:null})})}catch(s){if(W(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyAuthentication(e){var s;hn(this.experimental);try{const{data:a,error:l}=await ae(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.captchaToken}}});return l?this._returnResult({data:null,error:l}):this._returnResult({data:a,error:null})}catch(a){if(W(a))return this._returnResult({data:null,error:a});throw a}}async _verifyPasskeyAuthentication(e){hn(this.experimental);try{const{data:s,error:a}=await ae(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:tn});return a?this._returnResult({data:null,error:a}):(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:s,error:null}))}catch(s){if(W(s))return this._returnResult({data:null,error:s});throw s}}async _listPasskeys(){hn(this.experimental);try{return await this._useSession(async e=>{const{data:{session:s},error:a}=e;if(a)return this._returnResult({data:null,error:a});if(!s)return this._returnResult({data:null,error:new ht});const{data:l,error:u}=await ae(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:s.access_token,xform:c=>({data:c,error:null})});return u?this._returnResult({data:null,error:u}):this._returnResult({data:l,error:null})})}catch(e){if(W(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){hn(this.experimental);try{return await this._useSession(async s=>{const{data:{session:a},error:l}=s;if(l)return this._returnResult({data:null,error:l});if(!a)return this._returnResult({data:null,error:new ht});const{data:u,error:c}=await ae(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:a.access_token,body:{friendly_name:e.friendlyName}});return c?this._returnResult({data:null,error:c}):this._returnResult({data:u,error:null})})}catch(s){if(W(s))return this._returnResult({data:null,error:s});throw s}}async _deletePasskey(e){hn(this.experimental);try{return await this._useSession(async s=>{const{data:{session:a},error:l}=s;if(l)return this._returnResult({data:null,error:l});if(!a)return this._returnResult({data:null,error:new ht});const{error:u}=await ae(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:a.access_token,noResolveJson:!0});return u?this._returnResult({data:null,error:u}):this._returnResult({data:null,error:null})})}catch(s){if(W(s))return this._returnResult({data:null,error:s});throw s}}}Lr.nextInstanceID={};const Oj=Lr,Nj="2.110.2";let yr="",Zl;if(typeof Deno<"u"){var Qh;yr="deno",Zl=(Qh=Deno.version)===null||Qh===void 0?void 0:Qh.deno}else if(typeof document<"u")yr="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")yr="react-native";else{var Zh;yr="node",Zl=typeof process<"u"?(Zh=process.version)===null||Zh===void 0?void 0:Zh.replace(/^v/,""):void 0}const ex=[`runtime=${yr}`];Zl&&ex.push(`runtime-version=${Zl}`);const Dj={"X-Client-Info":`supabase-js/${Nj}; ${ex.join("; ")}`},Mj={headers:Dj},Uj={schema:"public"},Bj={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Lj={},zj={enabled:!1,respectSamplingDecision:!0};function Vj(n,e,s,a){function l(u){return u instanceof s?u:new s(function(c){c(u)})}return new(s||(s=Promise))(function(u,c){function d(g){try{p(a.next(g))}catch(v){c(v)}}function m(g){try{p(a.throw(g))}catch(v){c(v)}}function p(g){g.done?u(g.value):l(g.value).then(d,m)}p((a=a.apply(n,[])).next())})}let Wh=null;const Pj="@opentelemetry/api";function Hj(){return Wh===null&&(Wh=import(Pj).catch(()=>null)),Wh}function $j(){return Vj(this,void 0,void 0,function*(){try{const n=yield Hj();if(!n||!n.propagation||!n.context)return null;const e={};n.propagation.inject(n.context.active(),e);const s=e.traceparent;return s?{traceparent:s,tracestate:e.tracestate,baggage:e.baggage}:null}catch{return null}})}function qj(n){if(!n||typeof n!="string")return null;const e=n.split("-");if(e.length!==4)return null;const[s,a,l,u]=e;if(s.length!==2||a.length!==32||l.length!==16||u.length!==2)return null;const c=/^[0-9a-f]+$/i;return!c.test(s)||!c.test(a)||!c.test(l)||!c.test(u)||a==="00000000000000000000000000000000"||l==="0000000000000000"?null:{version:s,traceId:a,parentId:l,traceFlags:u,isSampled:(parseInt(u,16)&1)===1}}function Gj(n,e){if(!n||!e||e.length===0)return!1;let s;if(n instanceof URL)s=n;else try{s=new URL(n)}catch{return!1}for(const a of e)try{if(typeof a=="string"){if(Ij(s.hostname,a))return!0}else if(a instanceof RegExp){if(a.test(s.hostname))return!0}else if(typeof a=="function"&&a(s))return!0}catch{continue}return!1}function Ij(n,e){if(e===n)return!0;if(e.startsWith("*.")){const s=e.slice(2);if(n.endsWith(s)&&(n===s||n.endsWith("."+s)))return!0}return!1}function Kj(n){const e=[];try{const s=new URL(n);e.push(s.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function zr(n){"@babel/helpers - typeof";return zr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},zr(n)}function Fj(n,e){if(zr(n)!="object"||!n)return n;var s=n[Symbol.toPrimitive];if(s!==void 0){var a=s.call(n,e);if(zr(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Yj(n){var e=Fj(n,"string");return zr(e)=="symbol"?e:e+""}function Xj(n,e,s){return(e=Yj(e))in n?Object.defineProperty(n,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):n[e]=s,n}function Vv(n,e){var s=Object.keys(n);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(n);e&&(a=a.filter(function(l){return Object.getOwnPropertyDescriptor(n,l).enumerable})),s.push.apply(s,a)}return s}function Xe(n){for(var e=1;en?(...e)=>n(...e):(...e)=>fetch(...e),Qj=()=>Headers,Zj=(n,e,s,a,l)=>{const u=Jj(a),c=Qj(),d=(l==null?void 0:l.enabled)===!0,m=(l==null?void 0:l.respectSamplingDecision)!==!1,p=d?Kj(e):null;return async(g,v)=>{var w;const _=(w=await s())!==null&&w!==void 0?w:n;let S=new c(v==null?void 0:v.headers);if(S.has("apikey")||S.set("apikey",n),S.has("Authorization")||S.set("Authorization",`Bearer ${_}`),p){const E=await Wj(g,p,m);E&&(E.traceparent&&!S.has("traceparent")&&S.set("traceparent",E.traceparent),E.tracestate&&!S.has("tracestate")&&S.set("tracestate",E.tracestate),E.baggage&&!S.has("baggage")&&S.set("baggage",E.baggage))}return u(g,Xe(Xe({},v),{},{headers:S}))}};async function Wj(n,e,s){if(!Gj(typeof n=="string"||n instanceof URL?n:n.url,e))return null;const a=await $j();if(!a||!a.traceparent)return null;if(s){const l=qj(a.traceparent);if(l&&!l.isSampled)return null}return a}function Pv(n){return typeof n=="boolean"?{enabled:n}:n}function eO(n){return n.endsWith("/")?n:n+"/"}function tO(n,e){var s,a,l,u,c,d;const{db:m,auth:p,realtime:g,global:v}=n,{db:w,auth:_,realtime:S,global:E}=e,k=Pv(n.tracePropagation),C=Pv(e.tracePropagation),N={db:Xe(Xe({},w),m),auth:Xe(Xe({},_),p),realtime:Xe(Xe({},S),g),storage:{},global:Xe(Xe(Xe({},E),v),{},{headers:Xe(Xe({},(s=E==null?void 0:E.headers)!==null&&s!==void 0?s:{}),(a=v==null?void 0:v.headers)!==null&&a!==void 0?a:{})}),tracePropagation:{enabled:(l=(u=k==null?void 0:k.enabled)!==null&&u!==void 0?u:C==null?void 0:C.enabled)!==null&&l!==void 0?l:!1,respectSamplingDecision:(c=(d=k==null?void 0:k.respectSamplingDecision)!==null&&d!==void 0?d:C==null?void 0:C.respectSamplingDecision)!==null&&c!==void 0?c:!0},accessToken:async()=>""};return n.accessToken?N.accessToken=n.accessToken:delete N.accessToken,N}function nO(n){const e=n==null?void 0:n.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(eO(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var iO=class extends Oj{constructor(n){super(n)}},sO=class{constructor(n,e,s){var a,l;this.supabaseUrl=n,this.supabaseKey=e;const u=nO(n);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",u),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",u),this.storageUrl=new URL("storage/v1",u),this.functionsUrl=new URL("functions/v1",u);const c=`sb-${u.hostname.split(".")[0]}-auth-token`,d={db:Uj,realtime:Lj,auth:Xe(Xe({},Bj),{},{storageKey:c}),global:Mj,tracePropagation:zj},m=tO(s??{},d);if(this.settings=m,this.storageKey=(a=m.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(l=m.global.headers)!==null&&l!==void 0?l:{},m.accessToken)this.accessToken=m.accessToken,this.auth=new Proxy({},{get:(g,v)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(v)} is not possible`)}});else{var p;this.auth=this._initSupabaseAuthClient((p=m.auth)!==null&&p!==void 0?p:{},this.headers,m.global.fetch)}this.fetch=Zj(e,n,this._getAccessToken.bind(this),m.global.fetch,m.tracePropagation),this.realtime=this._initRealtimeClient(Xe({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},m.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(g=>this.realtime.setAuth(g)).catch(g=>console.warn("Failed to set initial Realtime auth token:",g)),this.rest=new fC(new URL("rest/v1",u).href,{headers:this.headers,schema:m.db.schema,fetch:this.fetch,timeout:m.db.timeout,urlLengthLimit:m.db.urlLengthLimit}),this.storage=new Ok(this.storageUrl.href,this.headers,this.fetch,s==null?void 0:s.storage),m.accessToken||this._listenForAuthEvents()}get functions(){return new sC(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(n){return this.rest.from(n)}schema(n){return this.rest.schema(n)}rpc(n,e={},s={head:!1,get:!1,count:void 0}){return this.rest.rpc(n,e,s)}channel(n,e={config:{}}){return this.realtime.channel(n,e)}getChannels(){return this.realtime.getChannels()}removeChannel(n){return this.realtime.removeChannel(n)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var n=this,e,s;if(n.accessToken)return await n.accessToken();const{data:a}=await n.auth.getSession();return(e=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&e!==void 0?e:n.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:n,persistSession:e,detectSessionInUrl:s,storage:a,userStorage:l,storageKey:u,flowType:c,lock:d,debug:m,throwOnError:p,experimental:g,lockAcquireTimeout:v,skipAutoInitialize:w},_,S){const E={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new iO({url:this.authUrl.href,headers:Xe(Xe({},E),_),storageKey:u,autoRefreshToken:n,persistSession:e,detectSessionInUrl:s,storage:a,userStorage:l,flowType:c,lock:d,debug:m,throwOnError:p,experimental:g,fetch:S,lockAcquireTimeout:v,skipAutoInitialize:w,hasCustomAuthorizationHeader:Object.keys(this.headers).some(k=>k.toLowerCase()==="authorization")})}_initRealtimeClient(n){return new tk(this.realtimeUrl.href,Xe(Xe({},n),{},{params:Xe(Xe({},{apikey:this.supabaseKey}),n==null?void 0:n.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((n,e)=>{this._handleTokenChanged(n,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(n,e,s){(n==="TOKEN_REFRESHED"||n==="SIGNED_IN")&&this.changedAccessToken!==s?(this.changedAccessToken=s,this.realtime.setAuth(s)):n==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const aO=(n,e,s)=>new sO(n,e,s);function rO(){if(typeof window<"u")return!1;const n=globalThis.process;if(!n)return!1;const e=n.version;if(e==null)return!1;const s=e.match(/^v(\d+)\./);return s?parseInt(s[1],10)<=20:!1}rO()&&console.warn("⚠️ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");const oO="https://dbit.digitalcompass.agency",tx="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJhbm9uIiwKICAgICJpc3MiOiAic3VwYWJhc2UtZGVtbyIsCiAgICAiaWF0IjogMTY0MTc2OTIwMCwKICAgICJleHAiOiAxNzk5NTM1NjAwCn0.dc_X5iR_VP_qT0zsiyj_I_OZ2T9FtRU2BBNWN8Bu4GE",Er=!!tx,ni=Er?aO(oO,tx,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!0}}):null;function lO(){return new URL("/cruce-cuentas/",window.location.origin).toString()}function uO({onShowToast:n}){const[e,s]=P.useState(!1),a=async()=>{if(!Er||!ni){n("El acceso con Google aún no está disponible. Contacta a IT.","error");return}s(!0);const{error:l}=await ni.auth.signInWithOAuth({provider:"google",options:{redirectTo:lO(),queryParams:{access_type:"offline",prompt:"select_account"}}});l&&(s(!1),n("No se pudo iniciar sesión con Google. Intenta nuevamente.","error"))};return b.jsxs("div",{className:"min-h-screen w-full flex flex-col justify-between bg-[#F5F5F5] relative overflow-hidden font-sans",children:[b.jsx("div",{className:"h-1.5 w-full bg-[#4F758B]"}),b.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:b.jsxs(mn.div,{initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,ease:"easeOut"},className:"w-full max-w-md bg-white border border-[#D0D0D0] p-8 shadow-xl flex flex-col items-center gap-6",children:[b.jsx("div",{className:"w-full flex justify-center py-2",children:b.jsx("img",{alt:"Logo GOMEZLEE MARKETING",className:"h-14 object-contain",src:"https://dbit.digitalcompass.agency/storage/v1/object/public/public-assets/GLM_completo.png",referrerPolicy:"no-referrer"})}),b.jsx("div",{className:"text-center w-full",children:b.jsx("h1",{className:"text-2xl font-bold text-[#4F758B] tracking-tight",children:"Portal de Cruce de Cuentas GLM"})}),b.jsx("button",{onClick:a,disabled:e||!Er,className:"w-full relative overflow-hidden flex items-center justify-center gap-3 bg-[#6CC24A] hover:bg-[#5bb03c] disabled:bg-neutral-300 disabled:cursor-not-allowed text-white font-semibold py-3.5 px-6 transition-all duration-150 transform active:scale-[0.99] select-none text-sm tracking-wide",children:e?b.jsxs("div",{className:"flex items-center gap-2",children:[b.jsxs("svg",{className:"animate-spin h-5 w-5 text-white",fill:"none",viewBox:"0 0 24 24",children:[b.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),b.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),b.jsx("span",{children:"Redirigiendo a Google..."})]}):b.jsxs(b.Fragment,{children:[b.jsxs("svg",{className:"w-5 h-5 flex-shrink-0 fill-current text-white",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[b.jsx("path",{d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"}),b.jsx("path",{d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),b.jsx("path",{d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"}),b.jsx("path",{d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"})]}),b.jsx("span",{children:"Continuar con Google"})]})}),!Er&&b.jsxs("div",{className:"w-full flex items-start gap-2 border border-amber-200 bg-amber-50 px-3 py-2 text-[11px] text-amber-800 leading-relaxed",children:[b.jsx(vf,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),b.jsx("span",{children:"El acceso con Google está pendiente de activación."})]})]})})]})}const cO="https://dbit.digitalcompass.agency/storage/v1/object/public/public-assets/GLM_completo.png";function hO({onSelect:n}){return b.jsxs("div",{className:"min-h-screen bg-[#F5F5F5] flex flex-col font-sans",children:[b.jsx("div",{className:"h-1.5 bg-[#6CC24A]"}),b.jsx("main",{className:"flex-1 flex items-center justify-center px-4 py-10",children:b.jsxs(mn.section,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},className:"w-full max-w-3xl bg-white border border-[#D0D0D0] shadow-xl p-6 sm:p-9",children:[b.jsx("img",{src:cO,alt:"GomezLee Marketing",className:"h-14 object-contain mb-7"}),b.jsxs("div",{className:"flex items-start gap-3 mb-7",children:[b.jsx("div",{className:"bg-[#4F758B]/10 p-2.5 rounded-full",children:b.jsx(Aw,{className:"w-5 h-5 text-[#4F758B]"})}),b.jsxs("div",{children:[b.jsx("h1",{className:"text-xl sm:text-2xl font-black text-[#4F758B] uppercase tracking-tight",children:"Selecciona el país"}),b.jsx("p",{className:"text-sm text-neutral-500 mt-1",children:"El portal cargará las reglas, la moneda y los reportes correspondientes."})]})]}),b.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:jr.map(e=>b.jsxs("button",{type:"button",disabled:!e.enabled,onClick:()=>e.enabled&&n(e.code),className:`text-left border p-5 transition-all min-h-[150px] flex flex-col justify-between ${e.enabled?"border-[#4F758B]/30 hover:border-[#4F758B] hover:shadow-md bg-white":"border-neutral-200 bg-neutral-50 cursor-not-allowed opacity-70"}`,children:[b.jsxs("div",{className:"flex items-start justify-between gap-3",children:[b.jsx("img",{src:e.flag,alt:"",className:"w-12 h-8 sm:w-16 sm:h-10 object-cover shadow-sm border border-neutral-200","aria-hidden":"true"}),e.enabled?b.jsx(L2,{className:"w-5 h-5 text-[#6CC24A]"}):b.jsx(cR,{className:"w-4 h-4 text-neutral-400"})]}),b.jsxs("div",{children:[b.jsx("p",{className:"font-black text-[#4F758B] uppercase tracking-wide",children:e.name}),b.jsx("p",{className:"text-xs text-neutral-500 mt-1",children:e.enabled?`Moneda ${e.currency}`:"Próximamente"})]})]},e.code))})]})})]})}const dO=["ymadera@gomezleemarketing.com","iaracena@gomezleemarketing.com","mgomez@gomezleemarketing.com","jgomez@gomezleemarketing.com"];function fO(n){return(n??"").trim().toLowerCase()}function mO(n){return dO.includes(fO(n))}const Hv=!0,zd="glm_cruce_selected_country",pO={name:"Isaac Aracena",email:"iaracena@gomezleemarketing.com"};function gO(n){const e=(n==null?void 0:n.user_metadata)??{},s=e.full_name||e.name||e.display_name;if(s)return String(s);const a=String((n==null?void 0:n.email)??"Usuario GLM");return a.includes("@")?a.split("@")[0]:a}function yO(){try{const n=window.localStorage.getItem(zd),e=jr.find(s=>s.code===n&&s.enabled);return(e==null?void 0:e.code)??null}catch{return null}}function vO(){const[n,e]=P.useState("cruce"),[s,a]=P.useState(!1),[l,u]=P.useState(null),[c,d]=P.useState([]),[m,p]=P.useState(!1),[g,v]=P.useState(null),[w,_]=P.useState(0),[S,E]=P.useState(()=>yO()),[k,C]=P.useState(null),[N,O]=P.useState(Hv),[z,F]=P.useState(null),J=P.useMemo(()=>Er&&ni,[]),G=S?J0(S):null,Y=(ue,D)=>{F({message:ue,type:D})};P.useEffect(()=>{if(!J||!ni){O(!1);return}let ue=!0;const D=async re=>{if(!(re!=null&&re.email)){C(null);return}if(!mO(re.email)){await ni.auth.signOut(),C(null),Y("Tu usuario no tiene acceso autorizado a este módulo.","error");return}C({name:gO(re),email:re.email})};(async()=>{var me;const{data:re}=await ni.auth.getSession();ue&&(await D((me=re.session)==null?void 0:me.user),O(!1))})();const{data:ee}=ni.auth.onAuthStateChange(async(re,me)=>{await D(me==null?void 0:me.user)});return()=>{ue=!1,ee.subscription.unsubscribe()}},[J]);const Z=()=>{u(null),d([]),p(!1),v(null),_(ue=>ue+1)},te=async()=>{ni&&await ni.auth.signOut(),C(null),E(null),window.localStorage.removeItem(zd),Z(),e("cruce"),Y("Sesión cerrada correctamente.","success")},de=()=>{Z(),e("cruce"),Y("Nuevo cruce iniciado.","success")},fe=ue=>{const D=J0(ue);if(!D.enabled){Y(`${D.name} estará disponible próximamente.`,"info");return}S&&S!==ue&&Z(),E(ue),window.localStorage.setItem(zd,ue),e("cruce"),a(!1)},qe=()=>{E(null),a(!1)};if(N)return b.jsx("div",{className:"min-h-screen bg-[#F5F5F5] flex items-center justify-center text-[#4F758B] font-black uppercase tracking-wider",children:"Validando acceso..."});if(!k)return b.jsxs(b.Fragment,{children:[b.jsx(uO,{onShowToast:Y}),b.jsx(as,{children:z&&b.jsx(Kh,{message:z.message,type:z.type,onClose:()=>F(null)})})]});if(!G)return b.jsxs(b.Fragment,{children:[b.jsx(hO,{onSelect:fe}),b.jsx(as,{children:z&&b.jsx(Kh,{message:z.message,type:z.type,onClose:()=>F(null)})})]});const X=k??pO;return b.jsxs("div",{className:"min-h-screen bg-[#F5F5F5] selection:bg-[#6CC24A] selection:text-white antialiased font-sans flex flex-col",children:[b.jsxs(mn.div,{initial:{opacity:0},animate:{opacity:1},className:"min-h-screen flex w-full relative overflow-x-hidden",children:[b.jsx(as,{children:s&&b.jsx(mn.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>a(!1),className:"fixed inset-0 bg-black/45 z-45 md:hidden"},"backdrop")}),b.jsx(AR,{currentView:n,onViewChange:ue=>{e(ue),a(!1)},onNewCruce:()=>{de(),a(!1)},isSidebarOpen:s,onCloseSidebar:()=>a(!1),user:X,isAuthEnabled:Hv,onLogout:te,country:G,onCountryChange:fe,onChooseAnotherCountry:qe}),b.jsx("div",{className:"pl-0 md:pl-64 flex-1 flex flex-col w-full min-h-screen transition-all duration-300",children:b.jsx(as,{mode:"wait",children:n==="cruce"?b.jsx(mn.div,{initial:{opacity:0,x:10},animate:{opacity:1,x:0},exit:{opacity:0,x:-10},transition:{duration:.2},className:"flex-1 flex flex-col",children:b.jsx(KR,{onShowToast:Y,uploadedPayroll:l,setUploadedPayroll:u,uploadedBankFiles:c,setUploadedBankFiles:d,isCruceExecuted:m,setIsCruceExecuted:p,response:g,setResponse:v,onOpenSidebar:()=>a(!0),operatorName:X.name,operatorEmail:X.email,resetToken:w,country:G})},`view-cruce-${G.code}`):b.jsx(mn.div,{initial:{opacity:0,x:10},animate:{opacity:1,x:0},exit:{opacity:0,x:-10},transition:{duration:.2},className:"flex-1 flex flex-col",children:b.jsx(eC,{onShowToast:Y,onOpenSidebar:()=>a(!0),operatorName:X.name,operatorEmail:X.email,country:G})},`view-history-${G.code}`)})})]},`interface-${G.code}`),b.jsx(as,{children:z&&b.jsx(Kh,{message:z.message,type:z.type,onClose:()=>F(null)})})]})}jS.createRoot(document.getElementById("root")).render(b.jsx(P.StrictMode,{children:b.jsx(vO,{})}));