From db692c14d35680c51672427776dd1b963df36b37 Mon Sep 17 00:00:00 2001 From: Albert Bot Date: Tue, 17 Feb 2026 15:54:50 +0000 Subject: [PATCH] Albert cashflow dashboard update (2026-02-17) --- .../{index-C-01c4zb.js => index-3pDSgaSo.js} | 64 ++++++++----------- index.html | 2 +- 2 files changed, 28 insertions(+), 38 deletions(-) rename assets/{index-C-01c4zb.js => index-3pDSgaSo.js} (64%) diff --git a/assets/index-C-01c4zb.js b/assets/index-3pDSgaSo.js similarity index 64% rename from assets/index-C-01c4zb.js rename to assets/index-3pDSgaSo.js index 9e3b091..98c9dc9 100644 --- a/assets/index-C-01c4zb.js +++ b/assets/index-3pDSgaSo.js @@ -1,4 +1,4 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();function xh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ku={exports:{}},oi={},Gu={exports:{}},I={};/** +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();function Th(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Gu={exports:{}},ii={},Ju={exports:{}},I={};/** * @license React * react.production.min.js * @@ -6,7 +6,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Wr=Symbol.for("react.element"),Th=Symbol.for("react.portal"),bh=Symbol.for("react.fragment"),Ch=Symbol.for("react.strict_mode"),Oh=Symbol.for("react.profiler"),jh=Symbol.for("react.provider"),Rh=Symbol.for("react.context"),Ph=Symbol.for("react.forward_ref"),Ah=Symbol.for("react.suspense"),Nh=Symbol.for("react.memo"),Ih=Symbol.for("react.lazy"),dl=Symbol.iterator;function Lh(e){return e===null||typeof e!="object"?null:(e=dl&&e[dl]||e["@@iterator"],typeof e=="function"?e:null)}var Ju={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Qu=Object.assign,Yu={};function Bn(e,t,n){this.props=e,this.context=t,this.refs=Yu,this.updater=n||Ju}Bn.prototype.isReactComponent={};Bn.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Bn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Xu(){}Xu.prototype=Bn.prototype;function pa(e,t,n){this.props=e,this.context=t,this.refs=Yu,this.updater=n||Ju}var ga=pa.prototype=new Xu;ga.constructor=pa;Qu(ga,Bn.prototype);ga.isPureReactComponent=!0;var hl=Array.isArray,Zu=Object.prototype.hasOwnProperty,ma={current:null},ec={key:!0,ref:!0,__self:!0,__source:!0};function tc(e,t,n){var r,s={},i=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(i=""+t.key),t)Zu.call(t,r)&&!ec.hasOwnProperty(r)&&(s[r]=t[r]);var a=arguments.length-2;if(a===1)s.children=n;else if(1>>1,re=C[Q];if(0>>1;Qs(Oi,N))$ts(Qr,Oi)?(C[Q]=Qr,C[$t]=N,Q=$t):(C[Q]=Oi,C[Lt]=N,Q=Lt);else if($ts(Qr,N))C[Q]=Qr,C[$t]=N,Q=$t;else break e}}return A}function s(C,A){var N=C.sortIndex-A.sortIndex;return N!==0?N:C.id-A.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],u=[],c=1,p=null,h=3,m=!1,y=!1,w=!1,S=typeof setTimeout=="function"?setTimeout:null,f=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function g(C){for(var A=n(u);A!==null;){if(A.callback===null)r(u);else if(A.startTime<=C)r(u),A.sortIndex=A.expirationTime,t(l,A);else break;A=n(u)}}function _(C){if(w=!1,g(C),!y)if(n(l)!==null)y=!0,bi(E);else{var A=n(u);A!==null&&Ci(_,A.startTime-C)}}function E(C,A){y=!1,w&&(w=!1,f(O),O=-1),m=!0;var N=h;try{for(g(A),p=n(l);p!==null&&(!(p.expirationTime>A)||C&&!ze());){var Q=p.callback;if(typeof Q=="function"){p.callback=null,h=p.priorityLevel;var re=Q(p.expirationTime<=A);A=e.unstable_now(),typeof re=="function"?p.callback=re:p===n(l)&&r(l),g(A)}else r(l);p=n(l)}if(p!==null)var Jr=!0;else{var Lt=n(u);Lt!==null&&Ci(_,Lt.startTime-A),Jr=!1}return Jr}finally{p=null,h=N,m=!1}}var x=!1,T=null,O=-1,U=5,L=-1;function ze(){return!(e.unstable_now()-LC||125Q?(C.sortIndex=N,t(u,C),n(l)===null&&C===n(u)&&(w?(f(O),O=-1):w=!0,Ci(_,N-Q))):(C.sortIndex=re,t(l,C),y||m||(y=!0,bi(E))),C},e.unstable_shouldYield=ze,e.unstable_wrapCallback=function(C){var A=h;return function(){var N=h;h=A;try{return C.apply(this,arguments)}finally{h=N}}}})(ac);oc.exports=ac;var qh=oc.exports;/** + */(function(e){function t(C,P){var N=C.length;C.push(P);e:for(;0>>1,re=C[Q];if(0>>1;Qs(Oi,N))$ts(Jr,Oi)?(C[Q]=Jr,C[$t]=N,Q=$t):(C[Q]=Oi,C[Lt]=N,Q=Lt);else if($ts(Jr,N))C[Q]=Jr,C[$t]=N,Q=$t;else break e}}return P}function s(C,P){var N=C.sortIndex-P.sortIndex;return N!==0?N:C.id-P.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],u=[],c=1,p=null,h=3,m=!1,v=!1,y=!1,k=typeof setTimeout=="function"?setTimeout:null,f=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function g(C){for(var P=n(u);P!==null;){if(P.callback===null)r(u);else if(P.startTime<=C)r(u),P.sortIndex=P.expirationTime,t(l,P);else break;P=n(u)}}function _(C){if(y=!1,g(C),!v)if(n(l)!==null)v=!0,xi(E);else{var P=n(u);P!==null&&Ci(_,P.startTime-C)}}function E(C,P){v=!1,y&&(y=!1,f(O),O=-1),m=!0;var N=h;try{for(g(P),p=n(l);p!==null&&(!(p.expirationTime>P)||C&&!ze());){var Q=p.callback;if(typeof Q=="function"){p.callback=null,h=p.priorityLevel;var re=Q(p.expirationTime<=P);P=e.unstable_now(),typeof re=="function"?p.callback=re:p===n(l)&&r(l),g(P)}else r(l);p=n(l)}if(p!==null)var Gr=!0;else{var Lt=n(u);Lt!==null&&Ci(_,Lt.startTime-P),Gr=!1}return Gr}finally{p=null,h=N,m=!1}}var T=!1,b=null,O=-1,U=5,L=-1;function ze(){return!(e.unstable_now()-LC||125Q?(C.sortIndex=N,t(u,C),n(l)===null&&C===n(u)&&(y?(f(O),O=-1):y=!0,Ci(_,N-Q))):(C.sortIndex=re,t(l,C),v||m||(v=!0,xi(E))),C},e.unstable_shouldYield=ze,e.unstable_wrapCallback=function(C){var P=h;return function(){var N=h;h=P;try{return C.apply(this,arguments)}finally{h=N}}}})(ac);oc.exports=ac;var Kh=oc.exports;/** * @license React * react-dom.production.min.js * @@ -30,66 +30,56 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var Kh=z,je=qh;function k(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),co=Object.prototype.hasOwnProperty,Gh=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,pl={},gl={};function Jh(e){return co.call(gl,e)?!0:co.call(pl,e)?!1:Gh.test(e)?gl[e]=!0:(pl[e]=!0,!1)}function Qh(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Yh(e,t,n,r){if(t===null||typeof t>"u"||Qh(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ye(e,t,n,r,s,i,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=o}var ce={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ce[e]=new ye(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ce[t]=new ye(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){ce[e]=new ye(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ce[e]=new ye(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){ce[e]=new ye(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){ce[e]=new ye(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){ce[e]=new ye(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){ce[e]=new ye(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){ce[e]=new ye(e,5,!1,e.toLowerCase(),null,!1,!1)});var ya=/[\-:]([a-z])/g;function wa(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(ya,wa);ce[t]=new ye(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ya,wa);ce[t]=new ye(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ya,wa);ce[t]=new ye(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){ce[e]=new ye(e,1,!1,e.toLowerCase(),null,!1,!1)});ce.xlinkHref=new ye("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){ce[e]=new ye(e,1,!1,e.toLowerCase(),null,!0,!0)});function _a(e,t,n,r){var s=ce.hasOwnProperty(t)?ce[t]:null;(s!==null?s.type!==0:r||!(2"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),co=Object.prototype.hasOwnProperty,Jh=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,pl={},gl={};function Qh(e){return co.call(gl,e)?!0:co.call(pl,e)?!1:Jh.test(e)?gl[e]=!0:(pl[e]=!0,!1)}function Yh(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Xh(e,t,n,r){if(t===null||typeof t>"u"||Yh(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ye(e,t,n,r,s,i,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=o}var ce={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ce[e]=new ye(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ce[t]=new ye(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){ce[e]=new ye(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ce[e]=new ye(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){ce[e]=new ye(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){ce[e]=new ye(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){ce[e]=new ye(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){ce[e]=new ye(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){ce[e]=new ye(e,5,!1,e.toLowerCase(),null,!1,!1)});var ya=/[\-:]([a-z])/g;function wa(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(ya,wa);ce[t]=new ye(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ya,wa);ce[t]=new ye(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ya,wa);ce[t]=new ye(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){ce[e]=new ye(e,1,!1,e.toLowerCase(),null,!1,!1)});ce.xlinkHref=new ye("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){ce[e]=new ye(e,1,!1,e.toLowerCase(),null,!0,!0)});function _a(e,t,n,r){var s=ce.hasOwnProperty(t)?ce[t]:null;(s!==null?s.type!==0:r||!(2a||s[o]!==i[a]){var l=` -`+s[o].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{Pi=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?rr(e):""}function Xh(e){switch(e.tag){case 5:return rr(e.type);case 16:return rr("Lazy");case 13:return rr("Suspense");case 19:return rr("SuspenseList");case 0:case 2:case 15:return e=Ai(e.type,!1),e;case 11:return e=Ai(e.type.render,!1),e;case 1:return e=Ai(e.type,!0),e;default:return""}}function go(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case gn:return"Fragment";case pn:return"Portal";case ho:return"Profiler";case Sa:return"StrictMode";case fo:return"Suspense";case po:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case cc:return(e.displayName||"Context")+".Consumer";case uc:return(e._context.displayName||"Context")+".Provider";case ka:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ea:return t=e.displayName||null,t!==null?t:go(e.type)||"Memo";case pt:t=e._payload,e=e._init;try{return go(e(t))}catch{}}return null}function Zh(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return go(t);case 8:return t===Sa?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Rt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function hc(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function ef(e){var t=hc(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Zr(e){e._valueTracker||(e._valueTracker=ef(e))}function fc(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=hc(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Ns(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function mo(e,t){var n=t.checked;return K({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function vl(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Rt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function pc(e,t){t=t.checked,t!=null&&_a(e,"checked",t,!1)}function vo(e,t){pc(e,t);var n=Rt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?yo(e,t.type,n):t.hasOwnProperty("defaultValue")&&yo(e,t.type,Rt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function yl(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function yo(e,t,n){(t!=="number"||Ns(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var sr=Array.isArray;function Cn(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=es.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function _r(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var lr={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},tf=["Webkit","ms","Moz","O"];Object.keys(lr).forEach(function(e){tf.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),lr[t]=lr[e]})});function yc(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||lr.hasOwnProperty(e)&&lr[e]?(""+t).trim():t+"px"}function wc(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=yc(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var nf=K({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function So(e,t){if(t){if(nf[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(k(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(k(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(k(61))}if(t.style!=null&&typeof t.style!="object")throw Error(k(62))}}function ko(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Eo=null;function xa(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var xo=null,On=null,jn=null;function Sl(e){if(e=qr(e)){if(typeof xo!="function")throw Error(k(280));var t=e.stateNode;t&&(t=di(t),xo(e.stateNode,e.type,t))}}function _c(e){On?jn?jn.push(e):jn=[e]:On=e}function Sc(){if(On){var e=On,t=jn;if(jn=On=null,Sl(e),t)for(e=0;e>>=0,e===0?32:31-(pf(e)/gf|0)|0}var ts=64,ns=4194304;function ir(e){switch(e&-e){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: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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Us(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,i=e.pingedLanes,o=n&268435455;if(o!==0){var a=o&~s;a!==0?r=ir(a):(i&=o,i!==0&&(r=ir(i)))}else o=n&~s,o!==0?r=ir(o):i!==0&&(r=ir(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,i=t&-t,s>=i||s===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Vr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ke(t),e[t]=n}function wf(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=cr),Rl=" ",Pl=!1;function Bc(e,t){switch(e){case"keyup":return Kf.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Fc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var mn=!1;function Jf(e,t){switch(e){case"compositionend":return Fc(t);case"keypress":return t.which!==32?null:(Pl=!0,Rl);case"textInput":return e=t.data,e===Rl&&Pl?null:e;default:return null}}function Qf(e,t){if(mn)return e==="compositionend"||!Aa&&Bc(e,t)?(e=zc(),xs=ja=_t=null,mn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Ll(n)}}function qc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?qc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Kc(){for(var e=window,t=Ns();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Ns(e.document)}return t}function Na(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function ip(e){var t=Kc(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&qc(n.ownerDocument.documentElement,n)){if(r!==null&&Na(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,i=Math.min(r.start,s);r=r.end===void 0?i:Math.min(r.end,s),!e.extend&&i>r&&(s=r,r=i,i=s),s=$l(n,i);var o=$l(n,r);s&&o&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,vn=null,Ro=null,hr=null,Po=!1;function Ul(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Po||vn==null||vn!==Ns(r)||(r=vn,"selectionStart"in r&&Na(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),hr&&br(hr,r)||(hr=r,r=Ms(Ro,"onSelect"),0_n||(e.current=Uo[_n],Uo[_n]=null,_n--)}function B(e,t){_n++,Uo[_n]=e.current,e.current=t}var Pt={},pe=Nt(Pt),Se=Nt(!1),Qt=Pt;function Ln(e,t){var n=e.type.contextTypes;if(!n)return Pt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in n)s[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function ke(e){return e=e.childContextTypes,e!=null}function Fs(){W(Se),W(pe)}function Vl(e,t,n){if(pe.current!==Pt)throw Error(k(168));B(pe,t),B(Se,n)}function nd(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(k(108,Zh(e)||"Unknown",s));return K({},n,r)}function Ws(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Pt,Qt=pe.current,B(pe,e),B(Se,Se.current),!0}function Hl(e,t,n){var r=e.stateNode;if(!r)throw Error(k(169));n?(e=nd(e,t,Qt),r.__reactInternalMemoizedMergedChildContext=e,W(Se),W(pe),B(pe,e)):W(Se),B(Se,n)}var rt=null,hi=!1,qi=!1;function rd(e){rt===null?rt=[e]:rt.push(e)}function vp(e){hi=!0,rd(e)}function It(){if(!qi&&rt!==null){qi=!0;var e=0,t=D;try{var n=rt;for(D=1;e>=o,s-=o,st=1<<32-Ke(t)+s|n<O?(U=T,T=null):U=T.sibling;var L=h(f,T,g[O],_);if(L===null){T===null&&(T=U);break}e&&T&&L.alternate===null&&t(f,T),d=i(L,d,O),x===null?E=L:x.sibling=L,x=L,T=U}if(O===g.length)return n(f,T),V&&zt(f,O),E;if(T===null){for(;OO?(U=T,T=null):U=T.sibling;var ze=h(f,T,L.value,_);if(ze===null){T===null&&(T=U);break}e&&T&&ze.alternate===null&&t(f,T),d=i(ze,d,O),x===null?E=ze:x.sibling=ze,x=ze,T=U}if(L.done)return n(f,T),V&&zt(f,O),E;if(T===null){for(;!L.done;O++,L=g.next())L=p(f,L.value,_),L!==null&&(d=i(L,d,O),x===null?E=L:x.sibling=L,x=L);return V&&zt(f,O),E}for(T=r(f,T);!L.done;O++,L=g.next())L=m(T,f,O,L.value,_),L!==null&&(e&&L.alternate!==null&&T.delete(L.key===null?O:L.key),d=i(L,d,O),x===null?E=L:x.sibling=L,x=L);return e&&T.forEach(function(qn){return t(f,qn)}),V&&zt(f,O),E}function S(f,d,g,_){if(typeof g=="object"&&g!==null&&g.type===gn&&g.key===null&&(g=g.props.children),typeof g=="object"&&g!==null){switch(g.$$typeof){case Xr:e:{for(var E=g.key,x=d;x!==null;){if(x.key===E){if(E=g.type,E===gn){if(x.tag===7){n(f,x.sibling),d=s(x,g.props.children),d.return=f,f=d;break e}}else if(x.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===pt&&Gl(E)===x.type){n(f,x.sibling),d=s(x,g.props),d.ref=Zn(f,x,g),d.return=f,f=d;break e}n(f,x);break}else t(f,x);x=x.sibling}g.type===gn?(d=Jt(g.props.children,f.mode,_,g.key),d.return=f,f=d):(_=As(g.type,g.key,g.props,null,f.mode,_),_.ref=Zn(f,d,g),_.return=f,f=_)}return o(f);case pn:e:{for(x=g.key;d!==null;){if(d.key===x)if(d.tag===4&&d.stateNode.containerInfo===g.containerInfo&&d.stateNode.implementation===g.implementation){n(f,d.sibling),d=s(d,g.children||[]),d.return=f,f=d;break e}else{n(f,d);break}else t(f,d);d=d.sibling}d=eo(g,f.mode,_),d.return=f,f=d}return o(f);case pt:return x=g._init,S(f,d,x(g._payload),_)}if(sr(g))return y(f,d,g,_);if(Gn(g))return w(f,d,g,_);us(f,g)}return typeof g=="string"&&g!==""||typeof g=="number"?(g=""+g,d!==null&&d.tag===6?(n(f,d.sibling),d=s(d,g),d.return=f,f=d):(n(f,d),d=Zi(g,f.mode,_),d.return=f,f=d),o(f)):n(f,d)}return S}var Un=ad(!0),ld=ad(!1),qs=Nt(null),Ks=null,En=null,Ua=null;function Da(){Ua=En=Ks=null}function za(e){var t=qs.current;W(qs),e._currentValue=t}function Mo(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Pn(e,t){Ks=e,Ua=En=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(_e=!0),e.firstContext=null)}function Ue(e){var t=e._currentValue;if(Ua!==e)if(e={context:e,memoizedValue:t,next:null},En===null){if(Ks===null)throw Error(k(308));En=e,Ks.dependencies={lanes:0,firstContext:e}}else En=En.next=e;return t}var Ht=null;function Ma(e){Ht===null?Ht=[e]:Ht.push(e)}function ud(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,Ma(t)):(n.next=s.next,s.next=n),t.interleaved=n,ut(e,r)}function ut(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var gt=!1;function Ba(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function cd(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function ot(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function bt(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,$&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,ut(e,n)}return s=r.interleaved,s===null?(t.next=t,Ma(r)):(t.next=s.next,s.next=t),r.interleaved=t,ut(e,n)}function bs(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ba(e,n)}}function Jl(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?s=i=o:i=i.next=o,n=n.next}while(n!==null);i===null?s=i=t:i=i.next=t}else s=i=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Gs(e,t,n,r){var s=e.updateQueue;gt=!1;var i=s.firstBaseUpdate,o=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var l=a,u=l.next;l.next=null,o===null?i=u:o.next=u,o=l;var c=e.alternate;c!==null&&(c=c.updateQueue,a=c.lastBaseUpdate,a!==o&&(a===null?c.firstBaseUpdate=u:a.next=u,c.lastBaseUpdate=l))}if(i!==null){var p=s.baseState;o=0,c=u=l=null,a=i;do{var h=a.lane,m=a.eventTime;if((r&h)===h){c!==null&&(c=c.next={eventTime:m,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var y=e,w=a;switch(h=t,m=n,w.tag){case 1:if(y=w.payload,typeof y=="function"){p=y.call(m,p,h);break e}p=y;break e;case 3:y.flags=y.flags&-65537|128;case 0:if(y=w.payload,h=typeof y=="function"?y.call(m,p,h):y,h==null)break e;p=K({},p,h);break e;case 2:gt=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,h=s.effects,h===null?s.effects=[a]:h.push(a))}else m={eventTime:m,lane:h,tag:a.tag,payload:a.payload,callback:a.callback,next:null},c===null?(u=c=m,l=p):c=c.next=m,o|=h;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;h=a,a=h.next,h.next=null,s.lastBaseUpdate=h,s.shared.pending=null}}while(!0);if(c===null&&(l=p),s.baseState=l,s.firstBaseUpdate=u,s.lastBaseUpdate=c,t=s.shared.interleaved,t!==null){s=t;do o|=s.lane,s=s.next;while(s!==t)}else i===null&&(s.shared.lanes=0);Zt|=o,e.lanes=o,e.memoizedState=p}}function Ql(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Gi.transition;Gi.transition={};try{e(!1),t()}finally{D=n,Gi.transition=r}}function Cd(){return De().memoizedState}function Sp(e,t,n){var r=Ot(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Od(e))jd(t,n);else if(n=ud(e,t,n,r),n!==null){var s=me();Ge(n,e,r,s),Rd(n,t,r)}}function kp(e,t,n){var r=Ot(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Od(e))jd(t,s);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var o=t.lastRenderedState,a=i(o,n);if(s.hasEagerState=!0,s.eagerState=a,Je(a,o)){var l=t.interleaved;l===null?(s.next=s,Ma(t)):(s.next=l.next,l.next=s),t.interleaved=s;return}}catch{}finally{}n=ud(e,t,s,r),n!==null&&(s=me(),Ge(n,e,r,s),Rd(n,t,r))}}function Od(e){var t=e.alternate;return e===q||t!==null&&t===q}function jd(e,t){fr=Qs=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Rd(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ba(e,n)}}var Ys={readContext:Ue,useCallback:de,useContext:de,useEffect:de,useImperativeHandle:de,useInsertionEffect:de,useLayoutEffect:de,useMemo:de,useReducer:de,useRef:de,useState:de,useDebugValue:de,useDeferredValue:de,useTransition:de,useMutableSource:de,useSyncExternalStore:de,useId:de,unstable_isNewReconciler:!1},Ep={readContext:Ue,useCallback:function(e,t){return Ye().memoizedState=[e,t===void 0?null:t],e},useContext:Ue,useEffect:Xl,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Os(4194308,4,kd.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Os(4194308,4,e,t)},useInsertionEffect:function(e,t){return Os(4,2,e,t)},useMemo:function(e,t){var n=Ye();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Ye();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Sp.bind(null,q,e),[r.memoizedState,e]},useRef:function(e){var t=Ye();return e={current:e},t.memoizedState=e},useState:Yl,useDebugValue:Ja,useDeferredValue:function(e){return Ye().memoizedState=e},useTransition:function(){var e=Yl(!1),t=e[0];return e=_p.bind(null,e[1]),Ye().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=q,s=Ye();if(V){if(n===void 0)throw Error(k(407));n=n()}else{if(n=t(),ie===null)throw Error(k(349));Xt&30||pd(r,t,n)}s.memoizedState=n;var i={value:n,getSnapshot:t};return s.queue=i,Xl(md.bind(null,r,i,e),[e]),r.flags|=2048,Ir(9,gd.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Ye(),t=ie.identifierPrefix;if(V){var n=it,r=st;n=(r&~(1<<32-Ke(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Ar++,0")&&(l=l.replace("",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{Ai=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?nr(e):""}function Zh(e){switch(e.tag){case 5:return nr(e.type);case 16:return nr("Lazy");case 13:return nr("Suspense");case 19:return nr("SuspenseList");case 0:case 2:case 15:return e=Pi(e.type,!1),e;case 11:return e=Pi(e.type.render,!1),e;case 1:return e=Pi(e.type,!0),e;default:return""}}function go(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case gn:return"Fragment";case pn:return"Portal";case ho:return"Profiler";case ka:return"StrictMode";case fo:return"Suspense";case po:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case cc:return(e.displayName||"Context")+".Consumer";case uc:return(e._context.displayName||"Context")+".Provider";case Sa:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ea:return t=e.displayName||null,t!==null?t:go(e.type)||"Memo";case pt:t=e._payload,e=e._init;try{return go(e(t))}catch{}}return null}function ef(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return go(t);case 8:return t===ka?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function jt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function hc(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function tf(e){var t=hc(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Xr(e){e._valueTracker||(e._valueTracker=tf(e))}function fc(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=hc(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Ps(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function mo(e,t){var n=t.checked;return K({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function vl(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=jt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function pc(e,t){t=t.checked,t!=null&&_a(e,"checked",t,!1)}function vo(e,t){pc(e,t);var n=jt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?yo(e,t.type,n):t.hasOwnProperty("defaultValue")&&yo(e,t.type,jt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function yl(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function yo(e,t,n){(t!=="number"||Ps(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var rr=Array.isArray;function Cn(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=Zr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function wr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var ar={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},nf=["Webkit","ms","Moz","O"];Object.keys(ar).forEach(function(e){nf.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ar[t]=ar[e]})});function yc(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||ar.hasOwnProperty(e)&&ar[e]?(""+t).trim():t+"px"}function wc(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=yc(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var rf=K({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ko(e,t){if(t){if(rf[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(S(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(S(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(S(61))}if(t.style!=null&&typeof t.style!="object")throw Error(S(62))}}function So(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Eo=null;function Ta(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var To=null,On=null,Rn=null;function kl(e){if(e=Hr(e)){if(typeof To!="function")throw Error(S(280));var t=e.stateNode;t&&(t=ci(t),To(e.stateNode,e.type,t))}}function _c(e){On?Rn?Rn.push(e):Rn=[e]:On=e}function kc(){if(On){var e=On,t=Rn;if(Rn=On=null,kl(e),t)for(e=0;e>>=0,e===0?32:31-(gf(e)/mf|0)|0}var es=64,ts=4194304;function sr(e){switch(e&-e){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: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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function $s(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,i=e.pingedLanes,o=n&268435455;if(o!==0){var a=o&~s;a!==0?r=sr(a):(i&=o,i!==0&&(r=sr(i)))}else o=n&~s,o!==0?r=sr(o):i!==0&&(r=sr(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,i=t&-t,s>=i||s===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Wr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ke(t),e[t]=n}function _f(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=ur),jl=" ",Al=!1;function Mc(e,t){switch(e){case"keyup":return Gf.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Fc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var mn=!1;function Qf(e,t){switch(e){case"compositionend":return Fc(t);case"keypress":return t.which!==32?null:(Al=!0,jl);case"textInput":return e=t.data,e===jl&&Al?null:e;default:return null}}function Yf(e,t){if(mn)return e==="compositionend"||!Pa&&Mc(e,t)?(e=zc(),Es=Ra=_t=null,mn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Ll(n)}}function qc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?qc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Kc(){for(var e=window,t=Ps();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Ps(e.document)}return t}function Na(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function op(e){var t=Kc(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&qc(n.ownerDocument.documentElement,n)){if(r!==null&&Na(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,i=Math.min(r.start,s);r=r.end===void 0?i:Math.min(r.end,s),!e.extend&&i>r&&(s=r,r=i,i=s),s=$l(n,i);var o=$l(n,r);s&&o&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,vn=null,jo=null,dr=null,Ao=!1;function Ul(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ao||vn==null||vn!==Ps(r)||(r=vn,"selectionStart"in r&&Na(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),dr&&br(dr,r)||(dr=r,r=zs(jo,"onSelect"),0_n||(e.current=Uo[_n],Uo[_n]=null,_n--)}function M(e,t){_n++,Uo[_n]=e.current,e.current=t}var At={},pe=Nt(At),ke=Nt(!1),Qt=At;function Ln(e,t){var n=e.type.contextTypes;if(!n)return At;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in n)s[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function Se(e){return e=e.childContextTypes,e!=null}function Ms(){W(ke),W(pe)}function Vl(e,t,n){if(pe.current!==At)throw Error(S(168));M(pe,t),M(ke,n)}function nd(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(S(108,ef(e)||"Unknown",s));return K({},n,r)}function Fs(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||At,Qt=pe.current,M(pe,e),M(ke,ke.current),!0}function Hl(e,t,n){var r=e.stateNode;if(!r)throw Error(S(169));n?(e=nd(e,t,Qt),r.__reactInternalMemoizedMergedChildContext=e,W(ke),W(pe),M(pe,e)):W(ke),M(ke,n)}var rt=null,di=!1,qi=!1;function rd(e){rt===null?rt=[e]:rt.push(e)}function yp(e){di=!0,rd(e)}function It(){if(!qi&&rt!==null){qi=!0;var e=0,t=D;try{var n=rt;for(D=1;e>=o,s-=o,st=1<<32-Ke(t)+s|n<O?(U=b,b=null):U=b.sibling;var L=h(f,b,g[O],_);if(L===null){b===null&&(b=U);break}e&&b&&L.alternate===null&&t(f,b),d=i(L,d,O),T===null?E=L:T.sibling=L,T=L,b=U}if(O===g.length)return n(f,b),V&&zt(f,O),E;if(b===null){for(;OO?(U=b,b=null):U=b.sibling;var ze=h(f,b,L.value,_);if(ze===null){b===null&&(b=U);break}e&&b&&ze.alternate===null&&t(f,b),d=i(ze,d,O),T===null?E=ze:T.sibling=ze,T=ze,b=U}if(L.done)return n(f,b),V&&zt(f,O),E;if(b===null){for(;!L.done;O++,L=g.next())L=p(f,L.value,_),L!==null&&(d=i(L,d,O),T===null?E=L:T.sibling=L,T=L);return V&&zt(f,O),E}for(b=r(f,b);!L.done;O++,L=g.next())L=m(b,f,O,L.value,_),L!==null&&(e&&L.alternate!==null&&b.delete(L.key===null?O:L.key),d=i(L,d,O),T===null?E=L:T.sibling=L,T=L);return e&&b.forEach(function(Hn){return t(f,Hn)}),V&&zt(f,O),E}function k(f,d,g,_){if(typeof g=="object"&&g!==null&&g.type===gn&&g.key===null&&(g=g.props.children),typeof g=="object"&&g!==null){switch(g.$$typeof){case Yr:e:{for(var E=g.key,T=d;T!==null;){if(T.key===E){if(E=g.type,E===gn){if(T.tag===7){n(f,T.sibling),d=s(T,g.props.children),d.return=f,f=d;break e}}else if(T.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===pt&&Gl(E)===T.type){n(f,T.sibling),d=s(T,g.props),d.ref=Xn(f,T,g),d.return=f,f=d;break e}n(f,T);break}else t(f,T);T=T.sibling}g.type===gn?(d=Jt(g.props.children,f.mode,_,g.key),d.return=f,f=d):(_=As(g.type,g.key,g.props,null,f.mode,_),_.ref=Xn(f,d,g),_.return=f,f=_)}return o(f);case pn:e:{for(T=g.key;d!==null;){if(d.key===T)if(d.tag===4&&d.stateNode.containerInfo===g.containerInfo&&d.stateNode.implementation===g.implementation){n(f,d.sibling),d=s(d,g.children||[]),d.return=f,f=d;break e}else{n(f,d);break}else t(f,d);d=d.sibling}d=eo(g,f.mode,_),d.return=f,f=d}return o(f);case pt:return T=g._init,k(f,d,T(g._payload),_)}if(rr(g))return v(f,d,g,_);if(Kn(g))return y(f,d,g,_);ls(f,g)}return typeof g=="string"&&g!==""||typeof g=="number"?(g=""+g,d!==null&&d.tag===6?(n(f,d.sibling),d=s(d,g),d.return=f,f=d):(n(f,d),d=Zi(g,f.mode,_),d.return=f,f=d),o(f)):n(f,d)}return k}var Un=ad(!0),ld=ad(!1),Hs=Nt(null),qs=null,En=null,Ua=null;function Da(){Ua=En=qs=null}function za(e){var t=Hs.current;W(Hs),e._currentValue=t}function Bo(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function An(e,t){qs=e,Ua=En=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(_e=!0),e.firstContext=null)}function Ue(e){var t=e._currentValue;if(Ua!==e)if(e={context:e,memoizedValue:t,next:null},En===null){if(qs===null)throw Error(S(308));En=e,qs.dependencies={lanes:0,firstContext:e}}else En=En.next=e;return t}var Ht=null;function Ba(e){Ht===null?Ht=[e]:Ht.push(e)}function ud(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,Ba(t)):(n.next=s.next,s.next=n),t.interleaved=n,ut(e,r)}function ut(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var gt=!1;function Ma(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function cd(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function ot(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function xt(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,$&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,ut(e,n)}return s=r.interleaved,s===null?(t.next=t,Ba(r)):(t.next=s.next,s.next=t),r.interleaved=t,ut(e,n)}function bs(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,xa(e,n)}}function Jl(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?s=i=o:i=i.next=o,n=n.next}while(n!==null);i===null?s=i=t:i=i.next=t}else s=i=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Ks(e,t,n,r){var s=e.updateQueue;gt=!1;var i=s.firstBaseUpdate,o=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var l=a,u=l.next;l.next=null,o===null?i=u:o.next=u,o=l;var c=e.alternate;c!==null&&(c=c.updateQueue,a=c.lastBaseUpdate,a!==o&&(a===null?c.firstBaseUpdate=u:a.next=u,c.lastBaseUpdate=l))}if(i!==null){var p=s.baseState;o=0,c=u=l=null,a=i;do{var h=a.lane,m=a.eventTime;if((r&h)===h){c!==null&&(c=c.next={eventTime:m,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var v=e,y=a;switch(h=t,m=n,y.tag){case 1:if(v=y.payload,typeof v=="function"){p=v.call(m,p,h);break e}p=v;break e;case 3:v.flags=v.flags&-65537|128;case 0:if(v=y.payload,h=typeof v=="function"?v.call(m,p,h):v,h==null)break e;p=K({},p,h);break e;case 2:gt=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,h=s.effects,h===null?s.effects=[a]:h.push(a))}else m={eventTime:m,lane:h,tag:a.tag,payload:a.payload,callback:a.callback,next:null},c===null?(u=c=m,l=p):c=c.next=m,o|=h;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;h=a,a=h.next,h.next=null,s.lastBaseUpdate=h,s.shared.pending=null}}while(!0);if(c===null&&(l=p),s.baseState=l,s.firstBaseUpdate=u,s.lastBaseUpdate=c,t=s.shared.interleaved,t!==null){s=t;do o|=s.lane,s=s.next;while(s!==t)}else i===null&&(s.shared.lanes=0);Zt|=o,e.lanes=o,e.memoizedState=p}}function Ql(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Gi.transition;Gi.transition={};try{e(!1),t()}finally{D=n,Gi.transition=r}}function Cd(){return De().memoizedState}function Sp(e,t,n){var r=Ot(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Od(e))Rd(t,n);else if(n=ud(e,t,n,r),n!==null){var s=me();Ge(n,e,r,s),jd(n,t,r)}}function Ep(e,t,n){var r=Ot(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Od(e))Rd(t,s);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var o=t.lastRenderedState,a=i(o,n);if(s.hasEagerState=!0,s.eagerState=a,Je(a,o)){var l=t.interleaved;l===null?(s.next=s,Ba(t)):(s.next=l.next,l.next=s),t.interleaved=s;return}}catch{}finally{}n=ud(e,t,s,r),n!==null&&(s=me(),Ge(n,e,r,s),jd(n,t,r))}}function Od(e){var t=e.alternate;return e===q||t!==null&&t===q}function Rd(e,t){hr=Js=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function jd(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,xa(e,n)}}var Qs={readContext:Ue,useCallback:de,useContext:de,useEffect:de,useImperativeHandle:de,useInsertionEffect:de,useLayoutEffect:de,useMemo:de,useReducer:de,useRef:de,useState:de,useDebugValue:de,useDeferredValue:de,useTransition:de,useMutableSource:de,useSyncExternalStore:de,useId:de,unstable_isNewReconciler:!1},Tp={readContext:Ue,useCallback:function(e,t){return Ye().memoizedState=[e,t===void 0?null:t],e},useContext:Ue,useEffect:Xl,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Cs(4194308,4,Sd.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Cs(4194308,4,e,t)},useInsertionEffect:function(e,t){return Cs(4,2,e,t)},useMemo:function(e,t){var n=Ye();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Ye();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Sp.bind(null,q,e),[r.memoizedState,e]},useRef:function(e){var t=Ye();return e={current:e},t.memoizedState=e},useState:Yl,useDebugValue:Ja,useDeferredValue:function(e){return Ye().memoizedState=e},useTransition:function(){var e=Yl(!1),t=e[0];return e=kp.bind(null,e[1]),Ye().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=q,s=Ye();if(V){if(n===void 0)throw Error(S(407));n=n()}else{if(n=t(),ie===null)throw Error(S(349));Xt&30||pd(r,t,n)}s.memoizedState=n;var i={value:n,getSnapshot:t};return s.queue=i,Xl(md.bind(null,r,i,e),[e]),r.flags|=2048,Nr(9,gd.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Ye(),t=ie.identifierPrefix;if(V){var n=it,r=st;n=(r&~(1<<32-Ke(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Ar++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[Xe]=t,e[jr]=r,Md(e,t,!1,!1),t.stateNode=e;e:{switch(o=ko(n,r),n){case"dialog":F("cancel",e),F("close",e),s=r;break;case"iframe":case"object":case"embed":F("load",e),s=r;break;case"video":case"audio":for(s=0;sMn&&(t.flags|=128,r=!0,er(i,!1),t.lanes=4194304)}else{if(!r)if(e=Js(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),er(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!V)return he(t),null}else 2*Y()-i.renderingStartTime>Mn&&n!==1073741824&&(t.flags|=128,r=!0,er(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(n=i.last,n!==null?n.sibling=o:t.child=o,i.last=o)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Y(),t.sibling=null,n=H.current,B(H,r?n&1|2:n&1),t):(he(t),null);case 22:case 23:return tl(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Te&1073741824&&(he(t),t.subtreeFlags&6&&(t.flags|=8192)):he(t),null;case 24:return null;case 25:return null}throw Error(k(156,t.tag))}function Pp(e,t){switch(La(t),t.tag){case 1:return ke(t.type)&&Fs(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Dn(),W(Se),W(pe),Va(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Wa(t),null;case 13:if(W(H),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(k(340));$n()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return W(H),null;case 4:return Dn(),null;case 10:return za(t.type._context),null;case 22:case 23:return tl(),null;case 24:return null;default:return null}}var ds=!1,fe=!1,Ap=typeof WeakSet=="function"?WeakSet:Set,b=null;function xn(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){J(e,t,r)}else n.current=null}function Jo(e,t,n){try{n()}catch(r){J(e,t,r)}}var uu=!1;function Np(e,t){if(Ao=Ds,e=Kc(),Na(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var o=0,a=-1,l=-1,u=0,c=0,p=e,h=null;t:for(;;){for(var m;p!==n||s!==0&&p.nodeType!==3||(a=o+s),p!==i||r!==0&&p.nodeType!==3||(l=o+r),p.nodeType===3&&(o+=p.nodeValue.length),(m=p.firstChild)!==null;)h=p,p=m;for(;;){if(p===e)break t;if(h===n&&++u===s&&(a=o),h===i&&++c===r&&(l=o),(m=p.nextSibling)!==null)break;p=h,h=p.parentNode}p=m}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(No={focusedElem:e,selectionRange:n},Ds=!1,b=t;b!==null;)if(t=b,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,b=e;else for(;b!==null;){t=b;try{var y=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(y!==null){var w=y.memoizedProps,S=y.memoizedState,f=t.stateNode,d=f.getSnapshotBeforeUpdate(t.elementType===t.type?w:Fe(t.type,w),S);f.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var g=t.stateNode.containerInfo;g.nodeType===1?g.textContent="":g.nodeType===9&&g.documentElement&&g.removeChild(g.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(k(163))}}catch(_){J(t,t.return,_)}if(e=t.sibling,e!==null){e.return=t.return,b=e;break}b=t.return}return y=uu,uu=!1,y}function pr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var i=s.destroy;s.destroy=void 0,i!==void 0&&Jo(t,n,i)}s=s.next}while(s!==r)}}function gi(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Qo(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Wd(e){var t=e.alternate;t!==null&&(e.alternate=null,Wd(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Xe],delete t[jr],delete t[$o],delete t[gp],delete t[mp])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Vd(e){return e.tag===5||e.tag===3||e.tag===4}function cu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Vd(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Yo(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Bs));else if(r!==4&&(e=e.child,e!==null))for(Yo(e,t,n),e=e.sibling;e!==null;)Yo(e,t,n),e=e.sibling}function Xo(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Xo(e,t,n),e=e.sibling;e!==null;)Xo(e,t,n),e=e.sibling}var le=null,Ve=!1;function ft(e,t,n){for(n=n.child;n!==null;)Hd(e,t,n),n=n.sibling}function Hd(e,t,n){if(Ze&&typeof Ze.onCommitFiberUnmount=="function")try{Ze.onCommitFiberUnmount(ai,n)}catch{}switch(n.tag){case 5:fe||xn(n,t);case 6:var r=le,s=Ve;le=null,ft(e,t,n),le=r,Ve=s,le!==null&&(Ve?(e=le,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):le.removeChild(n.stateNode));break;case 18:le!==null&&(Ve?(e=le,n=n.stateNode,e.nodeType===8?Hi(e.parentNode,n):e.nodeType===1&&Hi(e,n),xr(e)):Hi(le,n.stateNode));break;case 4:r=le,s=Ve,le=n.stateNode.containerInfo,Ve=!0,ft(e,t,n),le=r,Ve=s;break;case 0:case 11:case 14:case 15:if(!fe&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var i=s,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&Jo(n,t,o),s=s.next}while(s!==r)}ft(e,t,n);break;case 1:if(!fe&&(xn(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){J(n,t,a)}ft(e,t,n);break;case 21:ft(e,t,n);break;case 22:n.mode&1?(fe=(r=fe)||n.memoizedState!==null,ft(e,t,n),fe=r):ft(e,t,n);break;default:ft(e,t,n)}}function du(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Ap),t.forEach(function(r){var s=Fp.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Me(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=o),r&=~i}if(r=s,r=Y()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Lp(r/1960))-r,10e?16:e,St===null)var r=!1;else{if(e=St,St=null,ei=0,$&6)throw Error(k(331));var s=$;for($|=4,b=e.current;b!==null;){var i=b,o=i.child;if(b.flags&16){var a=i.deletions;if(a!==null){for(var l=0;lY()-Za?Gt(e,0):Xa|=n),Ee(e,t)}function Zd(e,t){t===0&&(e.mode&1?(t=ns,ns<<=1,!(ns&130023424)&&(ns=4194304)):t=1);var n=me();e=ut(e,t),e!==null&&(Vr(e,t,n),Ee(e,n))}function Bp(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Zd(e,n)}function Fp(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(k(314))}r!==null&&r.delete(t),Zd(e,n)}var eh;eh=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Se.current)_e=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return _e=!1,jp(e,t,n);_e=!!(e.flags&131072)}else _e=!1,V&&t.flags&1048576&&sd(t,Hs,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;js(e,t),e=t.pendingProps;var s=Ln(t,pe.current);Pn(t,n),s=qa(null,t,r,e,s,n);var i=Ka();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,ke(r)?(i=!0,Ws(t)):i=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Ba(t),s.updater=pi,t.stateNode=s,s._reactInternals=t,Fo(t,r,e,n),t=Ho(null,t,r,!0,i,n)):(t.tag=0,V&&i&&Ia(t),ge(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(js(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=Vp(r),e=Fe(r,e),s){case 0:t=Vo(null,t,r,e,n);break e;case 1:t=ou(null,t,r,e,n);break e;case 11:t=su(null,t,r,e,n);break e;case 14:t=iu(null,t,r,Fe(r.type,e),n);break e}throw Error(k(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Fe(r,s),Vo(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Fe(r,s),ou(e,t,r,s,n);case 3:e:{if(Ud(t),e===null)throw Error(k(387));r=t.pendingProps,i=t.memoizedState,s=i.element,cd(e,t),Gs(t,r,null,n);var o=t.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){s=zn(Error(k(423)),t),t=au(e,t,r,n,s);break e}else if(r!==s){s=zn(Error(k(424)),t),t=au(e,t,r,n,s);break e}else for(Ce=Tt(t.stateNode.containerInfo.firstChild),Oe=t,V=!0,qe=null,n=ld(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if($n(),r===s){t=ct(e,t,n);break e}ge(e,t,r,n)}t=t.child}return t;case 5:return dd(t),e===null&&zo(t),r=t.type,s=t.pendingProps,i=e!==null?e.memoizedProps:null,o=s.children,Io(r,s)?o=null:i!==null&&Io(r,i)&&(t.flags|=32),$d(e,t),ge(e,t,o,n),t.child;case 6:return e===null&&zo(t),null;case 13:return Dd(e,t,n);case 4:return Fa(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Un(t,null,r,n):ge(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Fe(r,s),su(e,t,r,s,n);case 7:return ge(e,t,t.pendingProps,n),t.child;case 8:return ge(e,t,t.pendingProps.children,n),t.child;case 12:return ge(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,i=t.memoizedProps,o=s.value,B(qs,r._currentValue),r._currentValue=o,i!==null)if(Je(i.value,o)){if(i.children===s.children&&!Se.current){t=ct(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(i.tag===1){l=ot(-1,n&-n),l.tag=2;var u=i.updateQueue;if(u!==null){u=u.shared;var c=u.pending;c===null?l.next=l:(l.next=c.next,c.next=l),u.pending=l}}i.lanes|=n,l=i.alternate,l!==null&&(l.lanes|=n),Mo(i.return,n,t),a.lanes|=n;break}l=l.next}}else if(i.tag===10)o=i.type===t.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(k(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),Mo(o,n,t),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===t){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ge(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,Pn(t,n),s=Ue(s),r=r(s),t.flags|=1,ge(e,t,r,n),t.child;case 14:return r=t.type,s=Fe(r,t.pendingProps),s=Fe(r.type,s),iu(e,t,r,s,n);case 15:return Id(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Fe(r,s),js(e,t),t.tag=1,ke(r)?(e=!0,Ws(t)):e=!1,Pn(t,n),Pd(t,r,s),Fo(t,r,s,n),Ho(null,t,r,!0,e,n);case 19:return zd(e,t,n);case 22:return Ld(e,t,n)}throw Error(k(156,t.tag))};function th(e,t){return Oc(e,t)}function Wp(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ie(e,t,n,r){return new Wp(e,t,n,r)}function rl(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Vp(e){if(typeof e=="function")return rl(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ka)return 11;if(e===Ea)return 14}return 2}function jt(e,t){var n=e.alternate;return n===null?(n=Ie(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function As(e,t,n,r,s,i){var o=2;if(r=e,typeof e=="function")rl(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case gn:return Jt(n.children,s,i,t);case Sa:o=8,s|=8;break;case ho:return e=Ie(12,n,t,s|2),e.elementType=ho,e.lanes=i,e;case fo:return e=Ie(13,n,t,s),e.elementType=fo,e.lanes=i,e;case po:return e=Ie(19,n,t,s),e.elementType=po,e.lanes=i,e;case dc:return vi(n,s,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case uc:o=10;break e;case cc:o=9;break e;case ka:o=11;break e;case Ea:o=14;break e;case pt:o=16,r=null;break e}throw Error(k(130,e==null?e:typeof e,""))}return t=Ie(o,n,t,s),t.elementType=e,t.type=r,t.lanes=i,t}function Jt(e,t,n,r){return e=Ie(7,e,r,t),e.lanes=n,e}function vi(e,t,n,r){return e=Ie(22,e,r,t),e.elementType=dc,e.lanes=n,e.stateNode={isHidden:!1},e}function Zi(e,t,n){return e=Ie(6,e,null,t),e.lanes=n,e}function eo(e,t,n){return t=Ie(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Hp(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ii(0),this.expirationTimes=Ii(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ii(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function sl(e,t,n,r,s,i,o,a,l){return e=new Hp(e,t,n,a,l),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ie(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ba(i),e}function qp(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(ih)}catch(e){console.error(e)}}ih(),ic.exports=Re;var Yp=ic.exports,wu=Yp;uo.createRoot=wu.createRoot,uo.hydrateRoot=wu.hydrateRoot;/** +`+i.stack}return{value:e,source:t,stack:s,digest:null}}function Yi(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function Wo(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var Cp=typeof WeakMap=="function"?WeakMap:Map;function Pd(e,t,n){n=ot(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){Xs||(Xs=!0,Zo=r),Wo(e,t)},n}function Nd(e,t,n){n=ot(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var s=t.value;n.payload=function(){return r(s)},n.callback=function(){Wo(e,t)}}var i=e.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(n.callback=function(){Wo(e,t),typeof r!="function"&&(Ct===null?Ct=new Set([this]):Ct.add(this));var o=t.stack;this.componentDidCatch(t.value,{componentStack:o!==null?o:""})}),n}function tu(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Cp;var s=new Set;r.set(t,s)}else s=r.get(t),s===void 0&&(s=new Set,r.set(t,s));s.has(n)||(s.add(n),e=Mp.bind(null,e,t,n),t.then(e,e))}function nu(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function ru(e,t,n,r,s){return e.mode&1?(e.flags|=65536,e.lanes=s,e):(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=ot(-1,1),t.tag=2,xt(n,t,1))),n.lanes|=1),e)}var Op=dt.ReactCurrentOwner,_e=!1;function ge(e,t,n,r){t.child=e===null?ld(t,null,n,r):Un(t,e.child,n,r)}function su(e,t,n,r,s){n=n.render;var i=t.ref;return An(t,s),r=qa(e,t,n,r,i,s),n=Ka(),e!==null&&!_e?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~s,ct(e,t,s)):(V&&n&&Ia(t),t.flags|=1,ge(e,t,r,s),t.child)}function iu(e,t,n,r,s){if(e===null){var i=n.type;return typeof i=="function"&&!rl(i)&&i.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=i,Id(e,t,i,r,s)):(e=As(n.type,null,r,t,t.mode,s),e.ref=t.ref,e.return=t,t.child=e)}if(i=e.child,!(e.lanes&s)){var o=i.memoizedProps;if(n=n.compare,n=n!==null?n:br,n(o,r)&&e.ref===t.ref)return ct(e,t,s)}return t.flags|=1,e=Rt(i,r),e.ref=t.ref,e.return=t,t.child=e}function Id(e,t,n,r,s){if(e!==null){var i=e.memoizedProps;if(br(i,r)&&e.ref===t.ref)if(_e=!1,t.pendingProps=r=i,(e.lanes&s)!==0)e.flags&131072&&(_e=!0);else return t.lanes=e.lanes,ct(e,t,s)}return Vo(e,t,n,r,s)}function Ld(e,t,n){var r=t.pendingProps,s=r.children,i=e!==null?e.memoizedState:null;if(r.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},M(bn,be),be|=n;else{if(!(n&1073741824))return e=i!==null?i.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,M(bn,be),be|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=i!==null?i.baseLanes:n,M(bn,be),be|=r}else i!==null?(r=i.baseLanes|n,t.memoizedState=null):r=n,M(bn,be),be|=r;return ge(e,t,s,n),t.child}function $d(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function Vo(e,t,n,r,s){var i=Se(n)?Qt:pe.current;return i=Ln(t,i),An(t,s),n=qa(e,t,n,r,i,s),r=Ka(),e!==null&&!_e?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~s,ct(e,t,s)):(V&&r&&Ia(t),t.flags|=1,ge(e,t,n,s),t.child)}function ou(e,t,n,r,s){if(Se(n)){var i=!0;Fs(t)}else i=!1;if(An(t,s),t.stateNode===null)Os(e,t),Ad(t,n,r),Fo(t,n,r,s),r=!0;else if(e===null){var o=t.stateNode,a=t.memoizedProps;o.props=a;var l=o.context,u=n.contextType;typeof u=="object"&&u!==null?u=Ue(u):(u=Se(n)?Qt:pe.current,u=Ln(t,u));var c=n.getDerivedStateFromProps,p=typeof c=="function"||typeof o.getSnapshotBeforeUpdate=="function";p||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==r||l!==u)&&eu(t,o,r,u),gt=!1;var h=t.memoizedState;o.state=h,Ks(t,r,o,s),l=t.memoizedState,a!==r||h!==l||ke.current||gt?(typeof c=="function"&&(Mo(t,n,c,r),l=t.memoizedState),(a=gt||Zl(t,n,a,r,h,l,u))?(p||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount=="function"&&(t.flags|=4194308)):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=l),o.props=r,o.state=l,o.context=u,r=a):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{o=t.stateNode,cd(e,t),a=t.memoizedProps,u=t.type===t.elementType?a:Fe(t.type,a),o.props=u,p=t.pendingProps,h=o.context,l=n.contextType,typeof l=="object"&&l!==null?l=Ue(l):(l=Se(n)?Qt:pe.current,l=Ln(t,l));var m=n.getDerivedStateFromProps;(c=typeof m=="function"||typeof o.getSnapshotBeforeUpdate=="function")||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==p||h!==l)&&eu(t,o,r,l),gt=!1,h=t.memoizedState,o.state=h,Ks(t,r,o,s);var v=t.memoizedState;a!==p||h!==v||ke.current||gt?(typeof m=="function"&&(Mo(t,n,m,r),v=t.memoizedState),(u=gt||Zl(t,n,u,r,h,v,l)||!1)?(c||typeof o.UNSAFE_componentWillUpdate!="function"&&typeof o.componentWillUpdate!="function"||(typeof o.componentWillUpdate=="function"&&o.componentWillUpdate(r,v,l),typeof o.UNSAFE_componentWillUpdate=="function"&&o.UNSAFE_componentWillUpdate(r,v,l)),typeof o.componentDidUpdate=="function"&&(t.flags|=4),typeof o.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof o.componentDidUpdate!="function"||a===e.memoizedProps&&h===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||a===e.memoizedProps&&h===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=v),o.props=r,o.state=v,o.context=l,r=u):(typeof o.componentDidUpdate!="function"||a===e.memoizedProps&&h===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||a===e.memoizedProps&&h===e.memoizedState||(t.flags|=1024),r=!1)}return Ho(e,t,n,r,i,s)}function Ho(e,t,n,r,s,i){$d(e,t);var o=(t.flags&128)!==0;if(!r&&!o)return s&&Hl(t,n,!1),ct(e,t,i);r=t.stateNode,Op.current=t;var a=o&&typeof n.getDerivedStateFromError!="function"?null:r.render();return t.flags|=1,e!==null&&o?(t.child=Un(t,e.child,null,i),t.child=Un(t,null,a,i)):ge(e,t,a,i),t.memoizedState=r.state,s&&Hl(t,n,!0),t.child}function Ud(e){var t=e.stateNode;t.pendingContext?Vl(e,t.pendingContext,t.pendingContext!==t.context):t.context&&Vl(e,t.context,!1),Fa(e,t.containerInfo)}function au(e,t,n,r,s){return $n(),$a(s),t.flags|=256,ge(e,t,n,r),t.child}var qo={dehydrated:null,treeContext:null,retryLane:0};function Ko(e){return{baseLanes:e,cachePool:null,transitions:null}}function Dd(e,t,n){var r=t.pendingProps,s=H.current,i=!1,o=(t.flags&128)!==0,a;if((a=o)||(a=e!==null&&e.memoizedState===null?!1:(s&2)!==0),a?(i=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(s|=1),M(H,s&1),e===null)return zo(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.mode&1?e.data==="$!"?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(o=r.children,e=r.fallback,i?(r=t.mode,i=t.child,o={mode:"hidden",children:o},!(r&1)&&i!==null?(i.childLanes=0,i.pendingProps=o):i=mi(o,r,0,null),e=Jt(e,r,n,null),i.return=t,e.return=t,i.sibling=e,t.child=i,t.child.memoizedState=Ko(n),t.memoizedState=qo,e):Qa(t,o));if(s=e.memoizedState,s!==null&&(a=s.dehydrated,a!==null))return Rp(e,t,o,r,a,s,n);if(i){i=r.fallback,o=t.mode,s=e.child,a=s.sibling;var l={mode:"hidden",children:r.children};return!(o&1)&&t.child!==s?(r=t.child,r.childLanes=0,r.pendingProps=l,t.deletions=null):(r=Rt(s,l),r.subtreeFlags=s.subtreeFlags&14680064),a!==null?i=Rt(a,i):(i=Jt(i,o,n,null),i.flags|=2),i.return=t,r.return=t,r.sibling=i,t.child=r,r=i,i=t.child,o=e.child.memoizedState,o=o===null?Ko(n):{baseLanes:o.baseLanes|n,cachePool:null,transitions:o.transitions},i.memoizedState=o,i.childLanes=e.childLanes&~n,t.memoizedState=qo,r}return i=e.child,e=i.sibling,r=Rt(i,{mode:"visible",children:r.children}),!(t.mode&1)&&(r.lanes=n),r.return=t,r.sibling=null,e!==null&&(n=t.deletions,n===null?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=r,t.memoizedState=null,r}function Qa(e,t){return t=mi({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function us(e,t,n,r){return r!==null&&$a(r),Un(t,e.child,null,n),e=Qa(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function Rp(e,t,n,r,s,i,o){if(n)return t.flags&256?(t.flags&=-257,r=Yi(Error(S(422))),us(e,t,o,r)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(i=r.fallback,s=t.mode,r=mi({mode:"visible",children:r.children},s,0,null),i=Jt(i,s,o,null),i.flags|=2,r.return=t,i.return=t,r.sibling=i,t.child=r,t.mode&1&&Un(t,e.child,null,o),t.child.memoizedState=Ko(o),t.memoizedState=qo,i);if(!(t.mode&1))return us(e,t,o,null);if(s.data==="$!"){if(r=s.nextSibling&&s.nextSibling.dataset,r)var a=r.dgst;return r=a,i=Error(S(419)),r=Yi(i,r,void 0),us(e,t,o,r)}if(a=(o&e.childLanes)!==0,_e||a){if(r=ie,r!==null){switch(o&-o){case 4:s=2;break;case 16:s=8;break;case 64: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:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:s=32;break;case 536870912:s=268435456;break;default:s=0}s=s&(r.suspendedLanes|o)?0:s,s!==0&&s!==i.retryLane&&(i.retryLane=s,ut(e,s),Ge(r,e,s,-1))}return nl(),r=Yi(Error(S(421))),us(e,t,o,r)}return s.data==="$?"?(t.flags|=128,t.child=e.child,t=Fp.bind(null,e),s._reactRetry=t,null):(e=i.treeContext,Ce=bt(s.nextSibling),Oe=t,V=!0,qe=null,e!==null&&(Pe[Ne++]=st,Pe[Ne++]=it,Pe[Ne++]=Yt,st=e.id,it=e.overflow,Yt=t),t=Qa(t,r.children),t.flags|=4096,t)}function lu(e,t,n){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),Bo(e.return,t,n)}function Xi(e,t,n,r,s){var i=e.memoizedState;i===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:s}:(i.isBackwards=t,i.rendering=null,i.renderingStartTime=0,i.last=r,i.tail=n,i.tailMode=s)}function zd(e,t,n){var r=t.pendingProps,s=r.revealOrder,i=r.tail;if(ge(e,t,r.children,n),r=H.current,r&2)r=r&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&lu(e,n,t);else if(e.tag===19)lu(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(M(H,r),!(t.mode&1))t.memoizedState=null;else switch(s){case"forwards":for(n=t.child,s=null;n!==null;)e=n.alternate,e!==null&&Gs(e)===null&&(s=n),n=n.sibling;n=s,n===null?(s=t.child,t.child=null):(s=n.sibling,n.sibling=null),Xi(t,!1,s,n,i);break;case"backwards":for(n=null,s=t.child,t.child=null;s!==null;){if(e=s.alternate,e!==null&&Gs(e)===null){t.child=s;break}e=s.sibling,s.sibling=n,n=s,s=e}Xi(t,!0,n,null,i);break;case"together":Xi(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function Os(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function ct(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),Zt|=t.lanes,!(n&t.childLanes))return null;if(e!==null&&t.child!==e.child)throw Error(S(153));if(t.child!==null){for(e=t.child,n=Rt(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=Rt(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function jp(e,t,n){switch(t.tag){case 3:Ud(t),$n();break;case 5:dd(t);break;case 1:Se(t.type)&&Fs(t);break;case 4:Fa(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,s=t.memoizedProps.value;M(Hs,r._currentValue),r._currentValue=s;break;case 13:if(r=t.memoizedState,r!==null)return r.dehydrated!==null?(M(H,H.current&1),t.flags|=128,null):n&t.child.childLanes?Dd(e,t,n):(M(H,H.current&1),e=ct(e,t,n),e!==null?e.sibling:null);M(H,H.current&1);break;case 19:if(r=(n&t.childLanes)!==0,e.flags&128){if(r)return zd(e,t,n);t.flags|=128}if(s=t.memoizedState,s!==null&&(s.rendering=null,s.tail=null,s.lastEffect=null),M(H,H.current),r)break;return null;case 22:case 23:return t.lanes=0,Ld(e,t,n)}return ct(e,t,n)}var Bd,Go,Md,Fd;Bd=function(e,t){for(var n=t.child;n!==null;){if(n.tag===5||n.tag===6)e.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===t)break;for(;n.sibling===null;){if(n.return===null||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};Go=function(){};Md=function(e,t,n,r){var s=e.memoizedProps;if(s!==r){e=t.stateNode,qt(et.current);var i=null;switch(n){case"input":s=mo(e,s),r=mo(e,r),i=[];break;case"select":s=K({},s,{value:void 0}),r=K({},r,{value:void 0}),i=[];break;case"textarea":s=wo(e,s),r=wo(e,r),i=[];break;default:typeof s.onClick!="function"&&typeof r.onClick=="function"&&(e.onclick=Bs)}ko(n,r);var o;n=null;for(u in s)if(!r.hasOwnProperty(u)&&s.hasOwnProperty(u)&&s[u]!=null)if(u==="style"){var a=s[u];for(o in a)a.hasOwnProperty(o)&&(n||(n={}),n[o]="")}else u!=="dangerouslySetInnerHTML"&&u!=="children"&&u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&u!=="autoFocus"&&(yr.hasOwnProperty(u)?i||(i=[]):(i=i||[]).push(u,null));for(u in r){var l=r[u];if(a=s!=null?s[u]:void 0,r.hasOwnProperty(u)&&l!==a&&(l!=null||a!=null))if(u==="style")if(a){for(o in a)!a.hasOwnProperty(o)||l&&l.hasOwnProperty(o)||(n||(n={}),n[o]="");for(o in l)l.hasOwnProperty(o)&&a[o]!==l[o]&&(n||(n={}),n[o]=l[o])}else n||(i||(i=[]),i.push(u,n)),n=l;else u==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,a=a?a.__html:void 0,l!=null&&a!==l&&(i=i||[]).push(u,l)):u==="children"?typeof l!="string"&&typeof l!="number"||(i=i||[]).push(u,""+l):u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&(yr.hasOwnProperty(u)?(l!=null&&u==="onScroll"&&F("scroll",e),i||a===l||(i=[])):(i=i||[]).push(u,l))}n&&(i=i||[]).push("style",n);var u=i;(t.updateQueue=u)&&(t.flags|=4)}};Fd=function(e,t,n,r){n!==r&&(t.flags|=4)};function Zn(e,t){if(!V)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function he(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,r=0;if(t)for(var s=e.child;s!==null;)n|=s.lanes|s.childLanes,r|=s.subtreeFlags&14680064,r|=s.flags&14680064,s.return=e,s=s.sibling;else for(s=e.child;s!==null;)n|=s.lanes|s.childLanes,r|=s.subtreeFlags,r|=s.flags,s.return=e,s=s.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function Ap(e,t,n){var r=t.pendingProps;switch(La(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return he(t),null;case 1:return Se(t.type)&&Ms(),he(t),null;case 3:return r=t.stateNode,Dn(),W(ke),W(pe),Va(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(e===null||e.child===null)&&(as(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,qe!==null&&(na(qe),qe=null))),Go(e,t),he(t),null;case 5:Wa(t);var s=qt(jr.current);if(n=t.type,e!==null&&t.stateNode!=null)Md(e,t,n,r,s),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!r){if(t.stateNode===null)throw Error(S(166));return he(t),null}if(e=qt(et.current),as(t)){r=t.stateNode,n=t.type;var i=t.memoizedProps;switch(r[Xe]=t,r[Or]=i,e=(t.mode&1)!==0,n){case"dialog":F("cancel",r),F("close",r);break;case"iframe":case"object":case"embed":F("load",r);break;case"video":case"audio":for(s=0;s<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[Xe]=t,e[Or]=r,Bd(e,t,!1,!1),t.stateNode=e;e:{switch(o=So(n,r),n){case"dialog":F("cancel",e),F("close",e),s=r;break;case"iframe":case"object":case"embed":F("load",e),s=r;break;case"video":case"audio":for(s=0;sBn&&(t.flags|=128,r=!0,Zn(i,!1),t.lanes=4194304)}else{if(!r)if(e=Gs(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Zn(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!V)return he(t),null}else 2*Y()-i.renderingStartTime>Bn&&n!==1073741824&&(t.flags|=128,r=!0,Zn(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(n=i.last,n!==null?n.sibling=o:t.child=o,i.last=o)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Y(),t.sibling=null,n=H.current,M(H,r?n&1|2:n&1),t):(he(t),null);case 22:case 23:return tl(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?be&1073741824&&(he(t),t.subtreeFlags&6&&(t.flags|=8192)):he(t),null;case 24:return null;case 25:return null}throw Error(S(156,t.tag))}function Pp(e,t){switch(La(t),t.tag){case 1:return Se(t.type)&&Ms(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Dn(),W(ke),W(pe),Va(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Wa(t),null;case 13:if(W(H),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(S(340));$n()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return W(H),null;case 4:return Dn(),null;case 10:return za(t.type._context),null;case 22:case 23:return tl(),null;case 24:return null;default:return null}}var cs=!1,fe=!1,Np=typeof WeakSet=="function"?WeakSet:Set,x=null;function Tn(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){J(e,t,r)}else n.current=null}function Jo(e,t,n){try{n()}catch(r){J(e,t,r)}}var uu=!1;function Ip(e,t){if(Po=Us,e=Kc(),Na(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var o=0,a=-1,l=-1,u=0,c=0,p=e,h=null;t:for(;;){for(var m;p!==n||s!==0&&p.nodeType!==3||(a=o+s),p!==i||r!==0&&p.nodeType!==3||(l=o+r),p.nodeType===3&&(o+=p.nodeValue.length),(m=p.firstChild)!==null;)h=p,p=m;for(;;){if(p===e)break t;if(h===n&&++u===s&&(a=o),h===i&&++c===r&&(l=o),(m=p.nextSibling)!==null)break;p=h,h=p.parentNode}p=m}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(No={focusedElem:e,selectionRange:n},Us=!1,x=t;x!==null;)if(t=x,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,x=e;else for(;x!==null;){t=x;try{var v=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(v!==null){var y=v.memoizedProps,k=v.memoizedState,f=t.stateNode,d=f.getSnapshotBeforeUpdate(t.elementType===t.type?y:Fe(t.type,y),k);f.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var g=t.stateNode.containerInfo;g.nodeType===1?g.textContent="":g.nodeType===9&&g.documentElement&&g.removeChild(g.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(S(163))}}catch(_){J(t,t.return,_)}if(e=t.sibling,e!==null){e.return=t.return,x=e;break}x=t.return}return v=uu,uu=!1,v}function fr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var i=s.destroy;s.destroy=void 0,i!==void 0&&Jo(t,n,i)}s=s.next}while(s!==r)}}function pi(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Qo(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Wd(e){var t=e.alternate;t!==null&&(e.alternate=null,Wd(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Xe],delete t[Or],delete t[$o],delete t[mp],delete t[vp])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Vd(e){return e.tag===5||e.tag===3||e.tag===4}function cu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Vd(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Yo(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Bs));else if(r!==4&&(e=e.child,e!==null))for(Yo(e,t,n),e=e.sibling;e!==null;)Yo(e,t,n),e=e.sibling}function Xo(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Xo(e,t,n),e=e.sibling;e!==null;)Xo(e,t,n),e=e.sibling}var le=null,Ve=!1;function ft(e,t,n){for(n=n.child;n!==null;)Hd(e,t,n),n=n.sibling}function Hd(e,t,n){if(Ze&&typeof Ze.onCommitFiberUnmount=="function")try{Ze.onCommitFiberUnmount(oi,n)}catch{}switch(n.tag){case 5:fe||Tn(n,t);case 6:var r=le,s=Ve;le=null,ft(e,t,n),le=r,Ve=s,le!==null&&(Ve?(e=le,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):le.removeChild(n.stateNode));break;case 18:le!==null&&(Ve?(e=le,n=n.stateNode,e.nodeType===8?Hi(e.parentNode,n):e.nodeType===1&&Hi(e,n),Er(e)):Hi(le,n.stateNode));break;case 4:r=le,s=Ve,le=n.stateNode.containerInfo,Ve=!0,ft(e,t,n),le=r,Ve=s;break;case 0:case 11:case 14:case 15:if(!fe&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var i=s,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&Jo(n,t,o),s=s.next}while(s!==r)}ft(e,t,n);break;case 1:if(!fe&&(Tn(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){J(n,t,a)}ft(e,t,n);break;case 21:ft(e,t,n);break;case 22:n.mode&1?(fe=(r=fe)||n.memoizedState!==null,ft(e,t,n),fe=r):ft(e,t,n);break;default:ft(e,t,n)}}function du(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Np),t.forEach(function(r){var s=Wp.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function Be(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=o),r&=~i}if(r=s,r=Y()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*$p(r/1960))-r,10e?16:e,kt===null)var r=!1;else{if(e=kt,kt=null,Zs=0,$&6)throw Error(S(331));var s=$;for($|=4,x=e.current;x!==null;){var i=x,o=i.child;if(x.flags&16){var a=i.deletions;if(a!==null){for(var l=0;lY()-Za?Gt(e,0):Xa|=n),Ee(e,t)}function Zd(e,t){t===0&&(e.mode&1?(t=ts,ts<<=1,!(ts&130023424)&&(ts=4194304)):t=1);var n=me();e=ut(e,t),e!==null&&(Wr(e,t,n),Ee(e,n))}function Fp(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Zd(e,n)}function Wp(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(S(314))}r!==null&&r.delete(t),Zd(e,n)}var eh;eh=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ke.current)_e=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return _e=!1,jp(e,t,n);_e=!!(e.flags&131072)}else _e=!1,V&&t.flags&1048576&&sd(t,Vs,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Os(e,t),e=t.pendingProps;var s=Ln(t,pe.current);An(t,n),s=qa(null,t,r,e,s,n);var i=Ka();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Se(r)?(i=!0,Fs(t)):i=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Ma(t),s.updater=fi,t.stateNode=s,s._reactInternals=t,Fo(t,r,e,n),t=Ho(null,t,r,!0,i,n)):(t.tag=0,V&&i&&Ia(t),ge(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Os(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=Hp(r),e=Fe(r,e),s){case 0:t=Vo(null,t,r,e,n);break e;case 1:t=ou(null,t,r,e,n);break e;case 11:t=su(null,t,r,e,n);break e;case 14:t=iu(null,t,r,Fe(r.type,e),n);break e}throw Error(S(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Fe(r,s),Vo(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Fe(r,s),ou(e,t,r,s,n);case 3:e:{if(Ud(t),e===null)throw Error(S(387));r=t.pendingProps,i=t.memoizedState,s=i.element,cd(e,t),Ks(t,r,null,n);var o=t.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){s=zn(Error(S(423)),t),t=au(e,t,r,n,s);break e}else if(r!==s){s=zn(Error(S(424)),t),t=au(e,t,r,n,s);break e}else for(Ce=bt(t.stateNode.containerInfo.firstChild),Oe=t,V=!0,qe=null,n=ld(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if($n(),r===s){t=ct(e,t,n);break e}ge(e,t,r,n)}t=t.child}return t;case 5:return dd(t),e===null&&zo(t),r=t.type,s=t.pendingProps,i=e!==null?e.memoizedProps:null,o=s.children,Io(r,s)?o=null:i!==null&&Io(r,i)&&(t.flags|=32),$d(e,t),ge(e,t,o,n),t.child;case 6:return e===null&&zo(t),null;case 13:return Dd(e,t,n);case 4:return Fa(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Un(t,null,r,n):ge(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Fe(r,s),su(e,t,r,s,n);case 7:return ge(e,t,t.pendingProps,n),t.child;case 8:return ge(e,t,t.pendingProps.children,n),t.child;case 12:return ge(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,i=t.memoizedProps,o=s.value,M(Hs,r._currentValue),r._currentValue=o,i!==null)if(Je(i.value,o)){if(i.children===s.children&&!ke.current){t=ct(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(i.tag===1){l=ot(-1,n&-n),l.tag=2;var u=i.updateQueue;if(u!==null){u=u.shared;var c=u.pending;c===null?l.next=l:(l.next=c.next,c.next=l),u.pending=l}}i.lanes|=n,l=i.alternate,l!==null&&(l.lanes|=n),Bo(i.return,n,t),a.lanes|=n;break}l=l.next}}else if(i.tag===10)o=i.type===t.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(S(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),Bo(o,n,t),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===t){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ge(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,An(t,n),s=Ue(s),r=r(s),t.flags|=1,ge(e,t,r,n),t.child;case 14:return r=t.type,s=Fe(r,t.pendingProps),s=Fe(r.type,s),iu(e,t,r,s,n);case 15:return Id(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:Fe(r,s),Os(e,t),t.tag=1,Se(r)?(e=!0,Fs(t)):e=!1,An(t,n),Ad(t,r,s),Fo(t,r,s,n),Ho(null,t,r,!0,e,n);case 19:return zd(e,t,n);case 22:return Ld(e,t,n)}throw Error(S(156,t.tag))};function th(e,t){return Oc(e,t)}function Vp(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ie(e,t,n,r){return new Vp(e,t,n,r)}function rl(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Hp(e){if(typeof e=="function")return rl(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Sa)return 11;if(e===Ea)return 14}return 2}function Rt(e,t){var n=e.alternate;return n===null?(n=Ie(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function As(e,t,n,r,s,i){var o=2;if(r=e,typeof e=="function")rl(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case gn:return Jt(n.children,s,i,t);case ka:o=8,s|=8;break;case ho:return e=Ie(12,n,t,s|2),e.elementType=ho,e.lanes=i,e;case fo:return e=Ie(13,n,t,s),e.elementType=fo,e.lanes=i,e;case po:return e=Ie(19,n,t,s),e.elementType=po,e.lanes=i,e;case dc:return mi(n,s,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case uc:o=10;break e;case cc:o=9;break e;case Sa:o=11;break e;case Ea:o=14;break e;case pt:o=16,r=null;break e}throw Error(S(130,e==null?e:typeof e,""))}return t=Ie(o,n,t,s),t.elementType=e,t.type=r,t.lanes=i,t}function Jt(e,t,n,r){return e=Ie(7,e,r,t),e.lanes=n,e}function mi(e,t,n,r){return e=Ie(22,e,r,t),e.elementType=dc,e.lanes=n,e.stateNode={isHidden:!1},e}function Zi(e,t,n){return e=Ie(6,e,null,t),e.lanes=n,e}function eo(e,t,n){return t=Ie(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function qp(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ii(0),this.expirationTimes=Ii(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ii(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function sl(e,t,n,r,s,i,o,a,l){return e=new qp(e,t,n,a,l),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ie(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ma(i),e}function Kp(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(ih)}catch(e){console.error(e)}}ih(),ic.exports=je;var Xp=ic.exports,wu=Xp;uo.createRoot=wu.createRoot,uo.hydrateRoot=wu.hydrateRoot;/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */var Xp={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"};/** + */var Zp={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.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const Zp=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),Vn=(e,t)=>{const n=z.forwardRef(({color:r="currentColor",size:s=24,strokeWidth:i=2,absoluteStrokeWidth:o,className:a="",children:l,...u},c)=>z.createElement("svg",{ref:c,...Xp,width:s,height:s,stroke:r,strokeWidth:o?Number(i)*24/Number(s):i,className:["lucide",`lucide-${Zp(e)}`,a].join(" "),...u},[...t.map(([p,h])=>z.createElement(p,h)),...Array.isArray(l)?l:[l]]));return n.displayName=`${e}`,n};/** + */const eg=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),ki=(e,t)=>{const n=z.forwardRef(({color:r="currentColor",size:s=24,strokeWidth:i=2,absoluteStrokeWidth:o,className:a="",children:l,...u},c)=>z.createElement("svg",{ref:c,...Zp,width:s,height:s,stroke:r,strokeWidth:o?Number(i)*24/Number(s):i,className:["lucide",`lucide-${eg(e)}`,a].join(" "),...u},[...t.map(([p,h])=>z.createElement(p,h)),...Array.isArray(l)?l:[l]]));return n.displayName=`${e}`,n};/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const eg=Vn("FileText",[["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"}]]);/** + */const tg=ki("FileText",[["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"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const tg=Vn("History",[["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"}]]);/** + */const _u=ki("Landmark",[["line",{x1:"3",x2:"21",y1:"22",y2:"22",key:"j8o0r"}],["line",{x1:"6",x2:"6",y1:"18",y2:"11",key:"10tf0k"}],["line",{x1:"10",x2:"10",y1:"18",y2:"11",key:"54lgf6"}],["line",{x1:"14",x2:"14",y1:"18",y2:"11",key:"380y"}],["line",{x1:"18",x2:"18",y1:"18",y2:"11",key:"1kevvc"}],["polygon",{points:"12 2 20 7 4 7",key:"jkujk7"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const ng=Vn("Landmark",[["line",{x1:"3",x2:"21",y1:"22",y2:"22",key:"j8o0r"}],["line",{x1:"6",x2:"6",y1:"18",y2:"11",key:"10tf0k"}],["line",{x1:"10",x2:"10",y1:"18",y2:"11",key:"54lgf6"}],["line",{x1:"14",x2:"14",y1:"18",y2:"11",key:"380y"}],["line",{x1:"18",x2:"18",y1:"18",y2:"11",key:"1kevvc"}],["polygon",{points:"12 2 20 7 4 7",key:"jkujk7"}]]);/** + */const ng=ki("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */const rg=Vn("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** - * @license lucide-react v0.344.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const sg=Vn("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** - * @license lucide-react v0.344.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ig=Vn("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);function og({activeView:e="mission",onChangeView:t=()=>{}}){const n=[{icon:rg,label:"Mission Control",key:"mission"},{icon:ng,label:"Fluxo de Caixa",key:"cashflow"},{icon:eg,label:"Knowledge Base",active:!1,status:"Em breve"},{icon:sg,label:"Squad Settings",active:!1,status:"Em breve"}];return v.jsxs("aside",{className:"area sidebar",children:[v.jsx("div",{className:"sidebar-brand",children:v.jsx("h3",{children:"Mission Control"})}),v.jsx("nav",{children:v.jsx("ul",{children:n.map(r=>v.jsxs("li",{className:`${r.key&&e===r.key?"active":""} ${r.status?"disabled":""}`,onClick:()=>{r.key&&t(r.key)},children:[v.jsx(r.icon,{size:18}),v.jsxs("div",{className:"menu-label-container",children:[v.jsx("span",{children:r.label}),r.status&&v.jsx("span",{className:"status-badge-inline",children:r.status})]})]},r.label))})})]})}function ag({title:e="Global Operations",status:t="System Online"}){return v.jsx("header",{className:"area header",children:v.jsxs("div",{className:"header-content",children:[v.jsx("h1",{children:e}),v.jsxs("div",{className:"system-status",children:[v.jsx("span",{className:"status-dot"})," ",t]})]})})}function lg({task:e,onClose:t}){if(!e)return null;const n=s=>{if(!s)return"-";try{return new Date(s).toLocaleString("pt-BR",{hour:"2-digit",minute:"2-digit",day:"2-digit",month:"2-digit"})}catch{return"-"}},r=(s,i)=>{if(!s||!i)return null;try{const o=new Date(i)-new Date(s);if(isNaN(o))return null;const a=Math.floor(o/6e4),l=Math.floor(o%6e4/1e3);return`${a}m ${l}s`}catch{return null}};return v.jsx("div",{className:"modal-overlay",onClick:t,children:v.jsxs("div",{className:"modal-content",onClick:s=>s.stopPropagation(),children:[v.jsx("button",{className:"close-btn",onClick:t,children:v.jsx(ig,{size:20})}),v.jsxs("div",{className:"modal-header",children:[v.jsx("span",{className:`priority-tag ${(e.priority||"medium").toLowerCase()}`,children:e.priority||"Medium"}),v.jsx("h2",{children:e.title}),v.jsxs("div",{className:"meta-info",children:[v.jsxs("span",{children:["Agente: ",v.jsxs("strong",{children:["@",e.assigned_to||"unassigned"]})]}),v.jsxs("span",{children:["Status: ",v.jsx("strong",{children:e.status})]})]})]}),v.jsxs("div",{className:"modal-body",children:[v.jsxs("section",{children:[v.jsx("h3",{children:"Descrição"}),v.jsx("p",{children:e.description||"Sem descrição."})]}),v.jsxs("section",{className:"timeline-section",children:[v.jsxs("h3",{children:[v.jsx(tg,{size:16})," Linha do Tempo"]}),v.jsxs("div",{className:"timeline",children:[v.jsxs("div",{className:"timeline-item",children:[v.jsx("span",{className:"time",children:n(e.created_at)}),v.jsxs("span",{className:"label",children:["Criado por ",e.created_by||"Sistema"]})]}),e.started_at&&v.jsxs("div",{className:"timeline-item highlight",children:[v.jsx("span",{className:"time",children:n(e.started_at)}),v.jsx("span",{className:"label",children:"Início do processamento"})]}),Array.isArray(e.status_history)&&e.status_history.map((s,i)=>{const o=i===0?e.created_at:e.status_history[i-1].at,a=r(o,s.at);return v.jsxs("div",{className:"timeline-item",children:[v.jsx("span",{className:"time",children:n(s.at)}),v.jsxs("span",{className:"label",children:["Movido para ",v.jsx("strong",{children:s.to})]}),a&&v.jsxs("span",{className:"duration",children:["Duração: ",a]})]},i)})]})]})]})]})})}function ug({task:e,onClick:t}){const n=(e.priority||"medium").toLowerCase();return v.jsxs("div",{className:"task-card",onClick:()=>t(e),children:[v.jsx("div",{className:"task-header",children:v.jsx("span",{className:`priority-tag ${n}`,children:e.priority||"Medium"})}),v.jsx("h4",{children:e.title}),v.jsx("p",{children:e.description}),v.jsx("div",{className:"task-footer",children:v.jsxs("span",{className:"assigned-to",children:["@",e.assigned_to]})})]})}function cg({tasks:e=[]}){const[t,n]=z.useState(null),r=["Inbox","Assigned","In Progress","Review","Done"],s=i=>{const a={Inbox:"pending",Assigned:"assigned","In Progress":"in_progress",Review:"review",Done:"done"}[i]||i.toLowerCase().replace(" ","_");return(e||[]).filter(l=>l.status===a)};return v.jsxs(rc.Fragment,{children:[v.jsx("div",{className:"kanban-board",children:r.map(i=>v.jsxs("div",{className:"kanban-column",children:[v.jsxs("div",{className:"column-header",children:[i," ",v.jsx("span",{className:"count",children:s(i).length})]}),v.jsx("div",{className:"column-content",children:s(i).map(o=>v.jsx(ug,{task:o,onClick:n},o.id))})]},i))}),t&&v.jsx(lg,{task:t,onClose:()=>n(null)})]})}function dg({logs:e=[]}){const t=n=>new Date(n).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return v.jsxs("section",{className:"area activity-ticker",children:[v.jsx("div",{className:"ticker-header",children:v.jsx("h4",{children:"Live Activity Feed"})}),v.jsx("div",{className:"ticker-content",children:e.length>0?e.map(n=>v.jsxs("div",{className:"activity-item",children:[v.jsx("span",{className:"time",children:t(n.created_at)}),v.jsx("span",{className:"divider",children:" - "}),v.jsxs("span",{className:"agent-name",children:["Agent ",n.agent_id]}),v.jsxs("span",{className:"action",children:[" ",n.action]}),n.details&&v.jsxs("span",{className:"details",children:[": ",n.details]})]},n.id)):v.jsx("p",{className:"empty-state",children:"No activity yet..."})})]})}function hg({agent:e}){const t=e.status==="active"||e.status==="busy"||e.status==="idle";return v.jsxs("div",{className:`agent-card ${t?"":"offline"}`,children:[v.jsxs("div",{className:"agent-portrait",children:[v.jsx("img",{src:`/${e.img}`,alt:e.name}),v.jsxs("div",{className:`status-badge ${e.status}`,children:[v.jsx("span",{className:"dot"}),e.status==="offline"?"Offline":"Ativo"]})]}),v.jsxs("div",{className:"agent-info",children:[v.jsxs("div",{className:"agent-header-row",children:[v.jsx("h3",{children:e.name}),v.jsx("span",{className:"load-badge",children:e.load||"0%"})]}),v.jsx("p",{className:"role",children:e.role}),v.jsx("div",{className:"agent-stats",children:Object.entries(e.powers).map(([n,r])=>v.jsxs("div",{className:"stat-item",children:[v.jsx("span",{className:"stat-label",children:n}),v.jsx("span",{className:"stat-value",children:r})]},n))})]})]})}function fg({agents:e=[]}){return v.jsx("footer",{className:"area agent-footer",children:e.map(t=>v.jsx(hg,{agent:t},t.name))})}function pg(e){return Number(e||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function gg({summary:e,snapshotDate:t}){return e?v.jsxs("section",{className:"cashflow-summary-grid",children:[v.jsxs("article",{className:"cashflow-card",children:[v.jsx("span",{children:"Data"}),v.jsx("strong",{children:t||"-"})]}),v.jsxs("article",{className:"cashflow-card",children:[v.jsx("span",{children:"Saldo consolidado"}),v.jsx("strong",{children:pg(e.consolidated_balance)})]}),v.jsxs("article",{className:"cashflow-card",children:[v.jsx("span",{children:"Unidades em risco"}),v.jsx("strong",{children:e.risk_units||0})]}),v.jsxs("article",{className:"cashflow-card",children:[v.jsxs("span",{children:["Desatualizadas (",e.stale_threshold_days||2,"+ dias)"]}),v.jsx("strong",{children:e.stale_units||0})]}),v.jsxs("article",{className:"cashflow-card",children:[v.jsx("span",{children:"Contas negativas"}),v.jsx("strong",{children:e.units_with_negative_accounts||0})]}),v.jsxs("article",{className:"cashflow-card",children:[v.jsx("span",{children:"Total de unidades"}),v.jsx("strong",{children:e.total_units||0})]})]}):null}function mg(e){return Number(e||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function vg({units:e=[],onSelectUnit:t,selectedUnitId:n}){return v.jsxs("section",{className:"cashflow-ranking",children:[v.jsxs("div",{className:"cashflow-ranking-header",children:[v.jsx("h3",{children:"Ranking de Caixa (Maior → Menor)"}),v.jsxs("span",{children:[e.length," unidades"]})]}),v.jsx("div",{className:"cashflow-table-wrapper",children:v.jsxs("table",{className:"cashflow-table",children:[v.jsx("thead",{children:v.jsxs("tr",{children:[v.jsx("th",{children:"#"}),v.jsx("th",{children:"Unidade"}),v.jsx("th",{children:"Saldo Total"}),v.jsx("th",{children:"Contas Negativas"}),v.jsx("th",{children:"Dias sem input"}),v.jsx("th",{children:"Status"})]})}),v.jsx("tbody",{children:e.map((r,s)=>{const i=[n===r.unit_id?"selected":"",Number(r.total_balance)<0?"risk":"",Number(r.days_since_last_input||0)>=2?"stale":""].filter(Boolean).join(" "),o=r.is_up_to_date?"Atualizado":"Desatualizado";return v.jsxs("tr",{className:i,children:[v.jsx("td",{children:s+1}),v.jsx("td",{children:v.jsx("button",{type:"button",onClick:()=>t(r),children:r.unit_name})}),v.jsx("td",{children:mg(r.total_balance)}),v.jsx("td",{children:r.negative_accounts_count||0}),v.jsx("td",{children:r.days_since_last_input||0}),v.jsx("td",{children:o})]},r.unit_id||`${r.unit_name}-${s}`)})})]})})]})}function yg({selectedDate:e,onDateChange:t,onRefresh:n}){return v.jsxs("section",{className:"cashflow-filter",children:[v.jsxs("div",{className:"cashflow-filter-left",children:[v.jsx("h3",{children:"Fluxo de Caixa por Data"}),v.jsx("p",{children:"Selecione uma data retroativa para comparar o histórico."})]}),v.jsxs("div",{className:"cashflow-filter-controls",children:[v.jsx("label",{htmlFor:"snapshot-date",children:"Data de referência"}),v.jsx("input",{id:"snapshot-date",type:"date",value:e,onChange:r=>t(r.target.value)}),v.jsx("button",{type:"button",onClick:n,children:"Atualizar"})]})]})}function _u(e){return Number(e||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function wg({unit:e}){if(!e)return v.jsxs("section",{className:"cashflow-unit-detail empty",children:[v.jsx("h3",{children:"Detalhe da Unidade"}),v.jsx("p",{children:"Selecione uma unidade no ranking para ver as contas."})]});const t=Array.isArray(e.accounts)?e.accounts:[];return v.jsxs("section",{className:"cashflow-unit-detail",children:[v.jsxs("div",{className:"cashflow-unit-header",children:[v.jsx("h3",{children:e.unit_name}),v.jsx("span",{children:_u(e.total_balance)})]}),v.jsxs("div",{className:"cashflow-unit-meta",children:[v.jsxs("span",{children:["Dias sem input: ",e.days_since_last_input||0]}),v.jsxs("span",{children:["Status: ",e.is_up_to_date?"Atualizado":"Desatualizado"]})]}),v.jsx("div",{className:"cashflow-table-wrapper",children:v.jsxs("table",{className:"cashflow-table",children:[v.jsx("thead",{children:v.jsxs("tr",{children:[v.jsx("th",{children:"Conta"}),v.jsx("th",{children:"Saldo"})]})}),v.jsx("tbody",{children:t.map(n=>{const r=Number(n.balance||0)<0;return v.jsxs("tr",{className:r?"risk":"",children:[v.jsx("td",{children:n.name}),v.jsx("td",{children:_u(n.balance)})]},n.bank_account_id||n.name)})})]})})]})}function _g(e){return Number(e||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function Sg({history:e=[]}){return v.jsxs("section",{className:"cashflow-history",children:[v.jsxs("div",{className:"cashflow-ranking-header",children:[v.jsx("h3",{children:"Historico Diario"}),v.jsxs("span",{children:[e.length," snapshots"]})]}),v.jsx("div",{className:"cashflow-table-wrapper",children:v.jsxs("table",{className:"cashflow-table",children:[v.jsx("thead",{children:v.jsxs("tr",{children:[v.jsx("th",{children:"Data"}),v.jsx("th",{children:"Saldo consolidado"}),v.jsx("th",{children:"Risco"}),v.jsx("th",{children:"Desatualizadas"}),v.jsx("th",{children:"Contas negativas"})]})}),v.jsx("tbody",{children:e.map((t,n)=>{const r=t.summary||{};return v.jsxs("tr",{children:[v.jsx("td",{children:t.snapshot_date}),v.jsx("td",{children:_g(r.consolidated_balance)}),v.jsx("td",{children:r.risk_units||0}),v.jsx("td",{children:r.stale_units||0}),v.jsx("td",{children:r.units_with_negative_accounts||0})]},`${t.snapshot_date}-${n}`)})})]})})]})}function ki(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);se?(...t)=>e(...t):(...t)=>fetch(...t);class ll extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class xg extends ll{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class Su extends ll{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class ku extends ll{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var ra;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(ra||(ra={}));class Tg{constructor(t,{headers:n={},customFetch:r,region:s=ra.Any}={}){this.url=t,this.headers=n,this.region=s,this.fetch=Eg(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t){return kg(this,arguments,void 0,function*(n,r={}){var s;let i,o;try{const{headers:a,method:l,body:u,signal:c,timeout:p}=r;let h={},{region:m}=r;m||(m=this.region);const y=new URL(`${this.url}/${n}`);m&&m!=="any"&&(h["x-region"]=m,y.searchParams.set("forceFunctionRegion",m));let w;u&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",w=u):typeof u=="string"?(h["Content-Type"]="text/plain",w=u):typeof FormData<"u"&&u instanceof FormData?w=u:(h["Content-Type"]="application/json",w=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?w=JSON.stringify(u):w=u;let S=c;p&&(o=new AbortController,i=setTimeout(()=>o.abort(),p),c?(S=o.signal,c.addEventListener("abort",()=>o.abort())):S=o.signal);const f=yield this.fetch(y.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),a),body:w,signal:S}).catch(E=>{throw new xg(E)}),d=f.headers.get("x-relay-error");if(d&&d==="true")throw new Su(f);if(!f.ok)throw new ku(f);let g=((s=f.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),_;return g==="application/json"?_=yield f.json():g==="application/octet-stream"||g==="application/pdf"?_=yield f.blob():g==="text/event-stream"?_=f:g==="multipart/form-data"?_=yield f.formData():_=yield f.text(),{data:_,error:null,response:f}}catch(a){return{data:null,error:a,response:a instanceof ku||a instanceof Su?a.context:void 0}}finally{i&&clearTimeout(i)}})}}var bg=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},Cg=class{constructor(e){var t,n,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(n=e.isMaybeSingle)!==null&&n!==void 0?n:!1,this.urlLengthLimit=(r=e.urlLengthLimit)!==null&&r!==void 0?r:8e3,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var n=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const r=this.fetch;let s=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let o=null,a=null,l=null,u=i.status,c=i.statusText;if(i.ok){var p,h;if(n.method!=="HEAD"){var m;const f=await i.text();f===""||(n.headers.get("Accept")==="text/csv"||n.headers.get("Accept")&&(!((m=n.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text"))?a=f:a=JSON.parse(f))}const w=(p=n.headers.get("Prefer"))===null||p===void 0?void 0:p.match(/count=(exact|planned|estimated)/),S=(h=i.headers.get("content-range"))===null||h===void 0?void 0:h.split("/");w&&S&&S.length>1&&(l=parseInt(S[1])),n.isMaybeSingle&&n.method==="GET"&&Array.isArray(a)&&(a.length>1?(o={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{var y;const w=await i.text();try{o=JSON.parse(w),Array.isArray(o)&&i.status===404&&(a=[],o=null,u=200,c="OK")}catch{i.status===404&&w===""?(u=204,c="No Content"):o={message:w}}if(o&&n.isMaybeSingle&&(!(o==null||(y=o.details)===null||y===void 0)&&y.includes("0 rows"))&&(o=null,u=200,c="OK"),o&&n.shouldThrowOnError)throw new bg(o)}return{error:o,data:a,count:l,status:u,statusText:c}});return this.shouldThrowOnError||(s=s.catch(i=>{var o;let a="",l="",u="";const c=i==null?void 0:i.cause;if(c){var p,h,m,y;const f=(p=c==null?void 0:c.message)!==null&&p!==void 0?p:"",d=(h=c==null?void 0:c.code)!==null&&h!==void 0?h:"";a=`${(m=i==null?void 0:i.name)!==null&&m!==void 0?m:"FetchError"}: ${i==null?void 0:i.message}`,a+=` + */const rg=ki("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);function sg({activeView:e="mission",onChangeView:t=()=>{},mode:n="full"}){const r=n==="cashflow",s=r?[{icon:_u,label:"Fluxo de Caixa",key:"cashflow"}]:[{icon:ng,label:"Mission Control",key:"mission"},{icon:_u,label:"Fluxo de Caixa",key:"cashflow"},{icon:tg,label:"Knowledge Base",active:!1,status:"Em breve"},{icon:rg,label:"Squad Settings",active:!1,status:"Em breve"}];return w.jsxs("aside",{className:"area sidebar",children:[w.jsx("div",{className:"sidebar-brand",children:w.jsx("h3",{children:r?"Albert Finance":"Mission Control"})}),w.jsx("nav",{children:w.jsx("ul",{children:s.map(i=>w.jsxs("li",{className:`${i.key&&e===i.key?"active":""} ${i.status?"disabled":""}`,onClick:()=>{i.key&&t(i.key)},children:[w.jsx(i.icon,{size:18}),w.jsxs("div",{className:"menu-label-container",children:[w.jsx("span",{children:i.label}),i.status&&w.jsx("span",{className:"status-badge-inline",children:i.status})]})]},i.label))})})]})}function ig({title:e="Global Operations",status:t="System Online"}){return w.jsx("header",{className:"area header",children:w.jsxs("div",{className:"header-content",children:[w.jsx("h1",{children:e}),w.jsxs("div",{className:"system-status",children:[w.jsx("span",{className:"status-dot"})," ",t]})]})})}function og({logs:e=[]}){const t=n=>new Date(n).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return w.jsxs("section",{className:"area activity-ticker",children:[w.jsx("div",{className:"ticker-header",children:w.jsx("h4",{children:"Live Activity Feed"})}),w.jsx("div",{className:"ticker-content",children:e.length>0?e.map(n=>w.jsxs("div",{className:"activity-item",children:[w.jsx("span",{className:"time",children:t(n.created_at)}),w.jsx("span",{className:"divider",children:" - "}),w.jsxs("span",{className:"agent-name",children:["Agent ",n.agent_id]}),w.jsxs("span",{className:"action",children:[" ",n.action]}),n.details&&w.jsxs("span",{className:"details",children:[": ",n.details]})]},n.id)):w.jsx("p",{className:"empty-state",children:"No activity yet..."})})]})}function ag({agent:e}){const t=e.status==="active"||e.status==="busy"||e.status==="idle";return w.jsxs("div",{className:`agent-card ${t?"":"offline"}`,children:[w.jsxs("div",{className:"agent-portrait",children:[w.jsx("img",{src:`/${e.img}`,alt:e.name}),w.jsxs("div",{className:`status-badge ${e.status}`,children:[w.jsx("span",{className:"dot"}),e.status==="offline"?"Offline":"Ativo"]})]}),w.jsxs("div",{className:"agent-info",children:[w.jsxs("div",{className:"agent-header-row",children:[w.jsx("h3",{children:e.name}),w.jsx("span",{className:"load-badge",children:e.load||"0%"})]}),w.jsx("p",{className:"role",children:e.role}),w.jsx("div",{className:"agent-stats",children:Object.entries(e.powers).map(([n,r])=>w.jsxs("div",{className:"stat-item",children:[w.jsx("span",{className:"stat-label",children:n}),w.jsx("span",{className:"stat-value",children:r})]},n))})]})]})}function lg({agents:e=[]}){return w.jsx("footer",{className:"area agent-footer",children:e.map(t=>w.jsx(ag,{agent:t},t.name))})}function ug(e){return Number(e||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function cg({summary:e,snapshotDate:t}){return e?w.jsxs("section",{className:"cashflow-summary-grid",children:[w.jsxs("article",{className:"cashflow-card",children:[w.jsx("span",{children:"Data"}),w.jsx("strong",{children:t||"-"})]}),w.jsxs("article",{className:"cashflow-card",children:[w.jsx("span",{children:"Saldo consolidado"}),w.jsx("strong",{children:ug(e.consolidated_balance)})]}),w.jsxs("article",{className:"cashflow-card",children:[w.jsx("span",{children:"Unidades em risco"}),w.jsx("strong",{children:e.risk_units||0})]}),w.jsxs("article",{className:"cashflow-card",children:[w.jsxs("span",{children:["Desatualizadas (",e.stale_threshold_days||2,"+ dias)"]}),w.jsx("strong",{children:e.stale_units||0})]}),w.jsxs("article",{className:"cashflow-card",children:[w.jsx("span",{children:"Contas negativas"}),w.jsx("strong",{children:e.units_with_negative_accounts||0})]}),w.jsxs("article",{className:"cashflow-card",children:[w.jsx("span",{children:"Total de unidades"}),w.jsx("strong",{children:e.total_units||0})]})]}):null}function dg(e){return Number(e||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function hg({units:e=[],onSelectUnit:t,selectedUnitId:n}){return w.jsxs("section",{className:"cashflow-ranking",children:[w.jsxs("div",{className:"cashflow-ranking-header",children:[w.jsx("h3",{children:"Ranking de Caixa (Maior → Menor)"}),w.jsxs("span",{children:[e.length," unidades"]})]}),w.jsx("div",{className:"cashflow-table-wrapper",children:w.jsxs("table",{className:"cashflow-table",children:[w.jsx("thead",{children:w.jsxs("tr",{children:[w.jsx("th",{children:"#"}),w.jsx("th",{children:"Unidade"}),w.jsx("th",{children:"Saldo Total"}),w.jsx("th",{children:"Contas Negativas"}),w.jsx("th",{children:"Dias sem input"}),w.jsx("th",{children:"Status"})]})}),w.jsx("tbody",{children:e.map((r,s)=>{const i=[n===r.unit_id?"selected":"",Number(r.total_balance)<0?"risk":"",Number(r.days_since_last_input||0)>=2?"stale":""].filter(Boolean).join(" "),o=r.is_up_to_date?"Atualizado":"Desatualizado";return w.jsxs("tr",{className:i,children:[w.jsx("td",{children:s+1}),w.jsx("td",{children:w.jsx("button",{type:"button",onClick:()=>t(r),children:r.unit_name})}),w.jsx("td",{children:dg(r.total_balance)}),w.jsx("td",{children:r.negative_accounts_count||0}),w.jsx("td",{children:r.days_since_last_input||0}),w.jsx("td",{children:o})]},r.unit_id||`${r.unit_name}-${s}`)})})]})})]})}function fg({selectedDate:e,onDateChange:t,onRefresh:n}){return w.jsxs("section",{className:"cashflow-filter",children:[w.jsxs("div",{className:"cashflow-filter-left",children:[w.jsx("h3",{children:"Fluxo de Caixa por Data"}),w.jsx("p",{children:"Selecione uma data retroativa para comparar o histórico."})]}),w.jsxs("div",{className:"cashflow-filter-controls",children:[w.jsx("label",{htmlFor:"snapshot-date",children:"Data de referência"}),w.jsx("input",{id:"snapshot-date",type:"date",value:e,onChange:r=>t(r.target.value)}),w.jsx("button",{type:"button",onClick:n,children:"Atualizar"})]})]})}function ku(e){return Number(e||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function pg({unit:e}){if(!e)return w.jsxs("section",{className:"cashflow-unit-detail empty",children:[w.jsx("h3",{children:"Detalhe da Unidade"}),w.jsx("p",{children:"Selecione uma unidade no ranking para ver as contas."})]});const t=Array.isArray(e.accounts)?e.accounts:[];return w.jsxs("section",{className:"cashflow-unit-detail",children:[w.jsxs("div",{className:"cashflow-unit-header",children:[w.jsx("h3",{children:e.unit_name}),w.jsx("span",{children:ku(e.total_balance)})]}),w.jsxs("div",{className:"cashflow-unit-meta",children:[w.jsxs("span",{children:["Dias sem input: ",e.days_since_last_input||0]}),w.jsxs("span",{children:["Status: ",e.is_up_to_date?"Atualizado":"Desatualizado"]})]}),w.jsx("div",{className:"cashflow-table-wrapper",children:w.jsxs("table",{className:"cashflow-table",children:[w.jsx("thead",{children:w.jsxs("tr",{children:[w.jsx("th",{children:"Conta"}),w.jsx("th",{children:"Saldo"})]})}),w.jsx("tbody",{children:t.map(n=>{const r=Number(n.balance||0)<0;return w.jsxs("tr",{className:r?"risk":"",children:[w.jsx("td",{children:n.name}),w.jsx("td",{children:ku(n.balance)})]},n.bank_account_id||n.name)})})]})})]})}function gg(e){return Number(e||0).toLocaleString("pt-BR",{style:"currency",currency:"BRL"})}function mg({history:e=[]}){return w.jsxs("section",{className:"cashflow-history",children:[w.jsxs("div",{className:"cashflow-ranking-header",children:[w.jsx("h3",{children:"Historico Diario"}),w.jsxs("span",{children:[e.length," snapshots"]})]}),w.jsx("div",{className:"cashflow-table-wrapper",children:w.jsxs("table",{className:"cashflow-table",children:[w.jsx("thead",{children:w.jsxs("tr",{children:[w.jsx("th",{children:"Data"}),w.jsx("th",{children:"Saldo consolidado"}),w.jsx("th",{children:"Risco"}),w.jsx("th",{children:"Desatualizadas"}),w.jsx("th",{children:"Contas negativas"})]})}),w.jsx("tbody",{children:e.map((t,n)=>{const r=t.summary||{};return w.jsxs("tr",{children:[w.jsx("td",{children:t.snapshot_date}),w.jsx("td",{children:gg(r.consolidated_balance)}),w.jsx("td",{children:r.risk_units||0}),w.jsx("td",{children:r.stale_units||0}),w.jsx("td",{children:r.units_with_negative_accounts||0})]},`${t.snapshot_date}-${n}`)})})]})})]})}function Si(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);se?(...t)=>e(...t):(...t)=>fetch(...t);class ll extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class wg extends ll{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class Su extends ll{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class Eu extends ll{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var ra;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(ra||(ra={}));class _g{constructor(t,{headers:n={},customFetch:r,region:s=ra.Any}={}){this.url=t,this.headers=n,this.region=s,this.fetch=yg(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t){return vg(this,arguments,void 0,function*(n,r={}){var s;let i,o;try{const{headers:a,method:l,body:u,signal:c,timeout:p}=r;let h={},{region:m}=r;m||(m=this.region);const v=new URL(`${this.url}/${n}`);m&&m!=="any"&&(h["x-region"]=m,v.searchParams.set("forceFunctionRegion",m));let y;u&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",y=u):typeof u=="string"?(h["Content-Type"]="text/plain",y=u):typeof FormData<"u"&&u instanceof FormData?y=u:(h["Content-Type"]="application/json",y=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?y=JSON.stringify(u):y=u;let k=c;p&&(o=new AbortController,i=setTimeout(()=>o.abort(),p),c?(k=o.signal,c.addEventListener("abort",()=>o.abort())):k=o.signal);const f=yield this.fetch(v.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),a),body:y,signal:k}).catch(E=>{throw new wg(E)}),d=f.headers.get("x-relay-error");if(d&&d==="true")throw new Su(f);if(!f.ok)throw new Eu(f);let g=((s=f.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),_;return g==="application/json"?_=yield f.json():g==="application/octet-stream"||g==="application/pdf"?_=yield f.blob():g==="text/event-stream"?_=f:g==="multipart/form-data"?_=yield f.formData():_=yield f.text(),{data:_,error:null,response:f}}catch(a){return{data:null,error:a,response:a instanceof Eu||a instanceof Su?a.context:void 0}}finally{i&&clearTimeout(i)}})}}var kg=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},Sg=class{constructor(e){var t,n,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(n=e.isMaybeSingle)!==null&&n!==void 0?n:!1,this.urlLengthLimit=(r=e.urlLengthLimit)!==null&&r!==void 0?r:8e3,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var n=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const r=this.fetch;let s=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let o=null,a=null,l=null,u=i.status,c=i.statusText;if(i.ok){var p,h;if(n.method!=="HEAD"){var m;const f=await i.text();f===""||(n.headers.get("Accept")==="text/csv"||n.headers.get("Accept")&&(!((m=n.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text"))?a=f:a=JSON.parse(f))}const y=(p=n.headers.get("Prefer"))===null||p===void 0?void 0:p.match(/count=(exact|planned|estimated)/),k=(h=i.headers.get("content-range"))===null||h===void 0?void 0:h.split("/");y&&k&&k.length>1&&(l=parseInt(k[1])),n.isMaybeSingle&&n.method==="GET"&&Array.isArray(a)&&(a.length>1?(o={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{var v;const y=await i.text();try{o=JSON.parse(y),Array.isArray(o)&&i.status===404&&(a=[],o=null,u=200,c="OK")}catch{i.status===404&&y===""?(u=204,c="No Content"):o={message:y}}if(o&&n.isMaybeSingle&&(!(o==null||(v=o.details)===null||v===void 0)&&v.includes("0 rows"))&&(o=null,u=200,c="OK"),o&&n.shouldThrowOnError)throw new kg(o)}return{error:o,data:a,count:l,status:u,statusText:c}});return this.shouldThrowOnError||(s=s.catch(i=>{var o;let a="",l="",u="";const c=i==null?void 0:i.cause;if(c){var p,h,m,v;const f=(p=c==null?void 0:c.message)!==null&&p!==void 0?p:"",d=(h=c==null?void 0:c.code)!==null&&h!==void 0?h:"";a=`${(m=i==null?void 0:i.name)!==null&&m!==void 0?m:"FetchError"}: ${i==null?void 0:i.message}`,a+=` -Caused by: ${(y=c==null?void 0:c.name)!==null&&y!==void 0?y:"Error"}: ${f}`,d&&(a+=` (${d})`),c!=null&&c.stack&&(a+=` -${c.stack}`)}else{var w;a=(w=i==null?void 0:i.stack)!==null&&w!==void 0?w:""}const S=this.url.toString().length;return(i==null?void 0:i.name)==="AbortError"||(i==null?void 0:i.code)==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",S>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${S} 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.`)):((c==null?void 0:c.name)==="HeadersOverflowError"||(c==null?void 0:c.code)==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",S>this.urlLengthLimit&&(l+=`. Your request URL is ${S} 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.`)),{error:{message:`${(o=i==null?void 0:i.name)!==null&&o!==void 0?o:"FetchError"}: ${i==null?void 0:i.message}`,details:a,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}returns(){return this}overrideTypes(){return this}},Og=class extends Cg{select(e){let t=!1;const n=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",n),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:s=r}={}){const i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){const r=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){const s=typeof r>"u"?"offset":`${r}.offset`,i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this.url.searchParams.set(i,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:r=!1,wal:s=!1,format:i="text"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,n?"settings":null,r?"buffers":null,s?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const Eu=new RegExp("[,()]");var dn=class extends Og{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const n=Array.from(new Set(t)).map(r=>typeof r=="string"&&Eu.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`in.(${n})`),this}notIn(e,t){const n=Array.from(new Set(t)).map(r=>typeof r=="string"&&Eu.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`not.in.(${n})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:n,type:r}={}){let s="";r==="plain"?s="pl":r==="phrase"?s="ph":r==="websearch"&&(s="w");const i=n===void 0?"":`(${n})`;return this.url.searchParams.append(e,`${s}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([t,n])=>{this.url.searchParams.append(t,`eq.${n}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){const r=n?`${n}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}},jg=class{constructor(e,{headers:t={},schema:n,fetch:r,urlLengthLimit:s=8e3}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r,this.urlLengthLimit=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:n=!1,count:r}=t??{},s=n?"HEAD":"GET";let i=!1;const o=(e??"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),r&&l.append("Prefer",`count=${r}`),new dn({method:s,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(e,{count:t,defaultToNull:n=!0}={}){var r;const s="POST",{url:i,headers:o}=this.cloneRequestState();if(t&&o.append("Prefer",`count=${t}`),n||o.append("Prefer","missing=default"),Array.isArray(e)){const a=e.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(a.length>0){const l=[...new Set(a)].map(u=>`"${u}"`);i.searchParams.set("columns",l.join(","))}}return new dn({method:s,url:i,headers:o,schema:this.schema,body:e,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:r,defaultToNull:s=!0}={}){var i;const o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${n?"ignore":"merge"}-duplicates`),t!==void 0&&a.searchParams.set("on_conflict",t),r&&l.append("Prefer",`count=${r}`),s||l.append("Prefer","missing=default"),Array.isArray(e)){const u=e.reduce((c,p)=>c.concat(Object.keys(p)),[]);if(u.length>0){const c=[...new Set(u)].map(p=>`"${p}"`);a.searchParams.set("columns",c.join(","))}}return new dn({method:o,url:a,headers:l,schema:this.schema,body:e,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(e,{count:t}={}){var n;const r="PATCH",{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new dn({method:r,url:s,headers:i,schema:this.schema,body:e,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:e}={}){var t;const n="DELETE",{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new dn({method:n,url:r,headers:s,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function $r(e){"@babel/helpers - typeof";return $r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$r(e)}function Rg(e,t){if($r(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if($r(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Pg(e){var t=Rg(e,"string");return $r(t)=="symbol"?t:t+""}function Ag(e,t,n){return(t=Pg(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function xu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function ps(e){for(var t=1;t0?this.fetch=(l,u)=>{const c=new AbortController,p=setTimeout(()=>c.abort(),i),h=u==null?void 0:u.signal;if(h){if(h.aborted)return clearTimeout(p),a(l,u);const m=()=>{clearTimeout(p),c.abort()};return h.addEventListener("abort",m,{once:!0}),a(l,ps(ps({},u),{},{signal:c.signal})).finally(()=>{clearTimeout(p),h.removeEventListener("abort",m)})}return a(l,ps(ps({},u),{},{signal:c.signal})).finally(()=>clearTimeout(p))}:this.fetch=a}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new jg(new URL(`${this.url}/${t}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new oh(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(t,n={},{head:r=!1,get:s=!1,count:i}={}){var o;let a;const l=new URL(`${this.url}/rpc/${t}`);let u;const c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),p=r&&Object.values(n).some(c);p?(a="POST",u=n):r||s?(a=r?"HEAD":"GET",Object.entries(n).filter(([m,y])=>y!==void 0).map(([m,y])=>[m,Array.isArray(y)?`{${y.join(",")}}`:`${y}`]).forEach(([m,y])=>{l.searchParams.append(m,y)})):(a="POST",u=n);const h=new Headers(this.headers);return p?h.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&h.set("Prefer",`count=${i}`),new dn({method:a,url:l,headers:h,schema:this.schemaName,body:u,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};class Ig{constructor(){}static detectEnvironment(){var t;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((t=navigator.userAgent)===null||t===void 0)&&t.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 n=globalThis.process;if(n){const r=n.versions;if(r&&r.node){const s=r.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: +Caused by: ${(v=c==null?void 0:c.name)!==null&&v!==void 0?v:"Error"}: ${f}`,d&&(a+=` (${d})`),c!=null&&c.stack&&(a+=` +${c.stack}`)}else{var y;a=(y=i==null?void 0:i.stack)!==null&&y!==void 0?y:""}const k=this.url.toString().length;return(i==null?void 0:i.name)==="AbortError"||(i==null?void 0:i.code)==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",k>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${k} 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.`)):((c==null?void 0:c.name)==="HeadersOverflowError"||(c==null?void 0:c.code)==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",k>this.urlLengthLimit&&(l+=`. Your request URL is ${k} 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.`)),{error:{message:`${(o=i==null?void 0:i.name)!==null&&o!==void 0?o:"FetchError"}: ${i==null?void 0:i.message}`,details:a,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}returns(){return this}overrideTypes(){return this}},Eg=class extends Sg{select(e){let t=!1;const n=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",n),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:s=r}={}){const i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){const r=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){const s=typeof r>"u"?"offset":`${r}.offset`,i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this.url.searchParams.set(i,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:r=!1,wal:s=!1,format:i="text"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,n?"settings":null,r?"buffers":null,s?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const Tu=new RegExp("[,()]");var dn=class extends Eg{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const n=Array.from(new Set(t)).map(r=>typeof r=="string"&&Tu.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`in.(${n})`),this}notIn(e,t){const n=Array.from(new Set(t)).map(r=>typeof r=="string"&&Tu.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`not.in.(${n})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:n,type:r}={}){let s="";r==="plain"?s="pl":r==="phrase"?s="ph":r==="websearch"&&(s="w");const i=n===void 0?"":`(${n})`;return this.url.searchParams.append(e,`${s}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([t,n])=>{this.url.searchParams.append(t,`eq.${n}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){const r=n?`${n}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}},Tg=class{constructor(e,{headers:t={},schema:n,fetch:r,urlLengthLimit:s=8e3}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r,this.urlLengthLimit=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:n=!1,count:r}=t??{},s=n?"HEAD":"GET";let i=!1;const o=(e??"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),r&&l.append("Prefer",`count=${r}`),new dn({method:s,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(e,{count:t,defaultToNull:n=!0}={}){var r;const s="POST",{url:i,headers:o}=this.cloneRequestState();if(t&&o.append("Prefer",`count=${t}`),n||o.append("Prefer","missing=default"),Array.isArray(e)){const a=e.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(a.length>0){const l=[...new Set(a)].map(u=>`"${u}"`);i.searchParams.set("columns",l.join(","))}}return new dn({method:s,url:i,headers:o,schema:this.schema,body:e,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:r,defaultToNull:s=!0}={}){var i;const o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${n?"ignore":"merge"}-duplicates`),t!==void 0&&a.searchParams.set("on_conflict",t),r&&l.append("Prefer",`count=${r}`),s||l.append("Prefer","missing=default"),Array.isArray(e)){const u=e.reduce((c,p)=>c.concat(Object.keys(p)),[]);if(u.length>0){const c=[...new Set(u)].map(p=>`"${p}"`);a.searchParams.set("columns",c.join(","))}}return new dn({method:o,url:a,headers:l,schema:this.schema,body:e,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(e,{count:t}={}){var n;const r="PATCH",{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new dn({method:r,url:s,headers:i,schema:this.schema,body:e,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:e}={}){var t;const n="DELETE",{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new dn({method:n,url:r,headers:s,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function Lr(e){"@babel/helpers - typeof";return Lr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Lr(e)}function bg(e,t){if(Lr(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Lr(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function xg(e){var t=bg(e,"string");return Lr(t)=="symbol"?t:t+""}function Cg(e,t,n){return(t=xg(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function bu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function fs(e){for(var t=1;t0?this.fetch=(l,u)=>{const c=new AbortController,p=setTimeout(()=>c.abort(),i),h=u==null?void 0:u.signal;if(h){if(h.aborted)return clearTimeout(p),a(l,u);const m=()=>{clearTimeout(p),c.abort()};return h.addEventListener("abort",m,{once:!0}),a(l,fs(fs({},u),{},{signal:c.signal})).finally(()=>{clearTimeout(p),h.removeEventListener("abort",m)})}return a(l,fs(fs({},u),{},{signal:c.signal})).finally(()=>clearTimeout(p))}:this.fetch=a}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Tg(new URL(`${this.url}/${t}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new oh(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(t,n={},{head:r=!1,get:s=!1,count:i}={}){var o;let a;const l=new URL(`${this.url}/rpc/${t}`);let u;const c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),p=r&&Object.values(n).some(c);p?(a="POST",u=n):r||s?(a=r?"HEAD":"GET",Object.entries(n).filter(([m,v])=>v!==void 0).map(([m,v])=>[m,Array.isArray(v)?`{${v.join(",")}}`:`${v}`]).forEach(([m,v])=>{l.searchParams.append(m,v)})):(a="POST",u=n);const h=new Headers(this.headers);return p?h.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&h.set("Prefer",`count=${i}`),new dn({method:a,url:l,headers:h,schema:this.schemaName,body:u,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};class Rg{constructor(){}static detectEnvironment(){var t;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((t=navigator.userAgent)===null||t===void 0)&&t.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 n=globalThis.process;if(n){const r=n.versions;if(r&&r.node){const s=r.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: import ws from "ws" new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const t=this.detectEnvironment();if(t.constructor)return t.constructor;let n=t.error||"WebSocket not supported in this environment.";throw t.workaround&&(n+=` -Suggested solution: ${t.workaround}`),new Error(n)}static createWebSocket(t,n){const r=this.getWebSocketConstructor();return new r(t,n)}static isWebSocketSupported(){try{const t=this.detectEnvironment();return t.type==="native"||t.type==="ws"}catch{return!1}}}const Lg="2.95.3",$g=`realtime-js/${Lg}`,Ug="1.0.0",ah="2.0.0",Tu=ah,sa=1e4,Dg=1e3,zg=100;var mt;(function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"})(mt||(mt={}));var ee;(function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"})(ee||(ee={}));var He;(function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"})(He||(He={}));var ia;(function(e){e.websocket="websocket"})(ia||(ia={}));var Ft;(function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"})(Ft||(Ft={}));class Mg{constructor(t){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=t??[]}encode(t,n){if(t.event===this.BROADCAST_EVENT&&!(t.payload instanceof ArrayBuffer)&&typeof t.payload.event=="string")return n(this._binaryEncodeUserBroadcastPush(t));let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return n(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(t){var n;return this._isArrayBuffer((n=t.payload)===null||n===void 0?void 0:n.payload)?this._encodeBinaryUserBroadcastPush(t):this._encodeJsonUserBroadcastPush(t)}_encodeBinaryUserBroadcastPush(t){var n,r;const s=(r=(n=t.payload)===null||n===void 0?void 0:n.payload)!==null&&r!==void 0?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(t,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(t){var n,r;const s=(r=(n=t.payload)===null||n===void 0?void 0:n.payload)!==null&&r!==void 0?r:{},o=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(t,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(t,n,r){var s,i;const o=t.topic,a=(s=t.ref)!==null&&s!==void 0?s:"",l=(i=t.join_ref)!==null&&i!==void 0?i:"",u=t.payload.event,c=this.allowedMetadataKeys?this._pick(t.payload,this.allowedMetadataKeys):{},p=Object.keys(c).length===0?"":JSON.stringify(c);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(p.length>255)throw new Error(`metadata length ${p.length} exceeds maximum of 255`);const h=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+u.length+p.length,m=new ArrayBuffer(this.HEADER_LENGTH+h);let y=new DataView(m),w=0;y.setUint8(w++,this.KINDS.userBroadcastPush),y.setUint8(w++,l.length),y.setUint8(w++,a.length),y.setUint8(w++,o.length),y.setUint8(w++,u.length),y.setUint8(w++,p.length),y.setUint8(w++,n),Array.from(l,f=>y.setUint8(w++,f.charCodeAt(0))),Array.from(a,f=>y.setUint8(w++,f.charCodeAt(0))),Array.from(o,f=>y.setUint8(w++,f.charCodeAt(0))),Array.from(u,f=>y.setUint8(w++,f.charCodeAt(0))),Array.from(p,f=>y.setUint8(w++,f.charCodeAt(0)));var S=new Uint8Array(m.byteLength+r.byteLength);return S.set(new Uint8Array(m),0),S.set(new Uint8Array(r),m.byteLength),S.buffer}decode(t,n){if(this._isArrayBuffer(t)){let r=this._binaryDecode(t);return n(r)}if(typeof t=="string"){const r=JSON.parse(t),[s,i,o,a,l]=r;return n({join_ref:s,ref:i,topic:o,event:a,payload:l})}return n({})}_binaryDecode(t){const n=new DataView(t),r=n.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(t,n,s)}}_decodeUserBroadcast(t,n,r){const s=n.getUint8(1),i=n.getUint8(2),o=n.getUint8(3),a=n.getUint8(4);let l=this.HEADER_LENGTH+4;const u=r.decode(t.slice(l,l+s));l=l+s;const c=r.decode(t.slice(l,l+i));l=l+i;const p=r.decode(t.slice(l,l+o));l=l+o;const h=t.slice(l,t.byteLength),m=a===this.JSON_ENCODING?JSON.parse(r.decode(h)):h,y={type:this.BROADCAST_EVENT,event:c,payload:m};return o>0&&(y.meta=JSON.parse(p)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:y}}_isArrayBuffer(t){var n;return t instanceof ArrayBuffer||((n=t==null?void 0:t.constructor)===null||n===void 0?void 0:n.name)==="ArrayBuffer"}_pick(t,n){return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(([r])=>n.includes(r)))}}class lh{constructor(t,n){this.callback=t,this.timerCalc=n,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=n}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var M;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(M||(M={}));const bu=(e,t,n={})=>{var r;const s=(r=n.skipTypes)!==null&&r!==void 0?r:[];return t?Object.keys(t).reduce((i,o)=>(i[o]=Bg(o,e,t,s),i),{}):{}},Bg=(e,t,n,r)=>{const s=t.find(a=>a.name===e),i=s==null?void 0:s.type,o=n[e];return i&&!r.includes(i)?uh(i,o):oa(o)},uh=(e,t)=>{if(e.charAt(0)==="_"){const n=e.slice(1,e.length);return Hg(t,n)}switch(e){case M.bool:return Fg(t);case M.float4:case M.float8:case M.int2:case M.int4:case M.int8:case M.numeric:case M.oid:return Wg(t);case M.json:case M.jsonb:return Vg(t);case M.timestamp:return qg(t);case M.abstime:case M.date:case M.daterange:case M.int4range:case M.int8range:case M.money:case M.reltime:case M.text:case M.time:case M.timestamptz:case M.timetz:case M.tsrange:case M.tstzrange:return oa(t);default:return oa(t)}},oa=e=>e,Fg=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},Wg=e=>{if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},Vg=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e},Hg=(e,t)=>{if(typeof e!="string")return e;const n=e.length-1,r=e[n];if(e[0]==="{"&&r==="}"){let i;const o=e.slice(1,n);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>uh(t,a))}return e},qg=e=>typeof e=="string"?e.replace(" ","T"):e,ch=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),t.pathname===""||t.pathname==="/"?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class to{constructor(t,n,r={},s=sa){this.channel=t,this.event=n,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,n){var r;return this._hasReceived(t)&&n((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:t,callback:n}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=n=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=n,this._matchReceive(n)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,n){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:n})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:t,response:n}){this.recHooks.filter(r=>r.status===t).forEach(r=>r.callback(n))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var Cu;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(Cu||(Cu={}));class vr{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(n==null?void 0:n.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},s=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=vr.syncState(this.state,s,i,o),this.pendingDiffs.forEach(l=>{this.state=vr.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},s=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=vr.syncDiff(this.state,s,i,o),a())}),this.onJoin((s,i,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:o})}),this.onLeave((s,i,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,s){const i=this.cloneDeep(t),o=this.transformState(n),a={},l={};return this.map(i,(u,c)=>{o[u]||(l[u]=c)}),this.map(o,(u,c)=>{const p=i[u];if(p){const h=c.map(S=>S.presence_ref),m=p.map(S=>S.presence_ref),y=c.filter(S=>m.indexOf(S.presence_ref)<0),w=p.filter(S=>h.indexOf(S.presence_ref)<0);y.length>0&&(a[u]=y),w.length>0&&(l[u]=w)}else a[u]=c}),this.syncDiff(i,{joins:a,leaves:l},r,s)}static syncDiff(t,n,r,s){const{joins:i,leaves:o}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(i,(a,l)=>{var u;const c=(u=t[a])!==null&&u!==void 0?u:[];if(t[a]=this.cloneDeep(l),c.length>0){const p=t[a].map(m=>m.presence_ref),h=c.filter(m=>p.indexOf(m.presence_ref)<0);t[a].unshift(...h)}r(a,c,l)}),this.map(o,(a,l)=>{let u=t[a];if(!u)return;const c=l.map(p=>p.presence_ref);u=u.filter(p=>c.indexOf(p.presence_ref)<0),t[a]=u,s(a,u,l),u.length===0&&delete t[a]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const s=t[r];return"metas"in s?n[r]=s.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):n[r]=s,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var Ou;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(Ou||(Ou={}));var yr;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"})(yr||(yr={}));var nt;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(nt||(nt={}));class bn{constructor(t,n={config:{}},r){var s,i;if(this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=ee.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},n.config),this.timeout=this.socket.timeout,this.joinPush=new to(this,He.join,this.params,this.timeout),this.rejoinTimer=new lh(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=ee.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=ee.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=ee.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=ee.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=ee.errored,this.rejoinTimer.scheduleTimeout())}),this._on(He.reply,{},(o,a)=>{this._trigger(this._replyEventName(a),o)}),this.presence=new vr(this),this.broadcastEndpointURL=ch(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(t,n=this.timeout){var r,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==ee.closed){const{config:{broadcast:o,presence:a,private:l}}=this.params,u=(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(m=>m.filter))!==null&&s!==void 0?s:[],c=!!this.bindings[yr.PRESENCE]&&this.bindings[yr.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,p={},h={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(p.access_token=this.socket.accessTokenValue),this._onError(m=>t==null?void 0:t(nt.CHANNEL_ERROR,m)),this._onClose(()=>t==null?void 0:t(nt.CLOSED)),this.updateJoinPayload(Object.assign({config:h},p)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive("ok",async({postgres_changes:m})=>{var y;if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){t==null||t(nt.SUBSCRIBED);return}else{const w=this.bindings.postgres_changes,S=(y=w==null?void 0:w.length)!==null&&y!==void 0?y:0,f=[];for(let d=0;d{this.state=ee.errored,t==null||t(nt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(nt.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(t,n={}){return await this.send({type:"presence",event:"track",payload:t},n.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,n,r){return this.state===ee.joined&&t===yr.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(t,n,r)}async httpSend(t,n,r={}){var s;if(n==null)return Promise.reject("Payload is required for httpSend()");const i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:t,payload:n,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{const u=await a.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(t,n={}){var r,s;if(!this._canPush()&&t.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:o}=t,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(r=n.timeout)!==null&&r!==void 0?r:this.timeout);return await((s=u.body)===null||s===void 0?void 0:s.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;const u=this._push(t.type,t,n.timeout||this.timeout);t.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=ee.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(He.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{r=new to(this,He.leave,{},t),r.receive("ok",()=>{n(),s("ok")}).receive("timeout",()=>{n(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{r==null||r.destroy()})}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=ee.closed,this.bindings={}}async _fetchWithTimeout(t,n,r){const s=new AbortController,i=setTimeout(()=>s.abort(),r),o=await this.socket.fetch(t,Object.assign(Object.assign({},n),{signal:s.signal}));return clearTimeout(i),o}_push(t,n,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new to(this,t,n,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(t){if(t.startTimeout(),this.pushBuffer.push(t),this.pushBuffer.length>zg){const n=this.pushBuffer.shift();n&&(n.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${n.event}`,n.payload))}}_onMessage(t,n,r){return n}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,n,r){var s,i;const o=t.toLocaleLowerCase(),{close:a,error:l,leave:u,join:c}=He;if(r&&[a,l,u,c].indexOf(o)>=0&&r!==this._joinRef())return;let h=this._onMessage(o,n,r);if(n&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(m=>{var y,w,S;return((y=m.filter)===null||y===void 0?void 0:y.event)==="*"||((S=(w=m.filter)===null||w===void 0?void 0:w.event)===null||S===void 0?void 0:S.toLocaleLowerCase())===o}).map(m=>m.callback(h,r)):(i=this.bindings[o])===null||i===void 0||i.filter(m=>{var y,w,S,f,d,g;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){const _=m.id,E=(y=m.filter)===null||y===void 0?void 0:y.event;return _&&((w=n.ids)===null||w===void 0?void 0:w.includes(_))&&(E==="*"||(E==null?void 0:E.toLocaleLowerCase())===((S=n.data)===null||S===void 0?void 0:S.type.toLocaleLowerCase()))}else{const _=(d=(f=m==null?void 0:m.filter)===null||f===void 0?void 0:f.event)===null||d===void 0?void 0:d.toLocaleLowerCase();return _==="*"||_===((g=n==null?void 0:n.event)===null||g===void 0?void 0:g.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof h=="object"&&"ids"in h){const y=h.data,{schema:w,table:S,commit_timestamp:f,type:d,errors:g}=y;h=Object.assign(Object.assign({},{schema:w,table:S,commit_timestamp:f,eventType:d,new:{},old:{},errors:g}),this._getPayloadRecords(y))}m.callback(h,r)})}_isClosed(){return this.state===ee.closed}_isJoined(){return this.state===ee.joined}_isJoining(){return this.state===ee.joining}_isLeaving(){return this.state===ee.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,n,r){const s=t.toLocaleLowerCase(),i={type:s,filter:n,callback:r};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(t,n){const r=t.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(s=>{var i;return!(((i=s.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===r&&bn.isEqual(s.filter,n))})),this}static isEqual(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in t)if(t[r]!==n[r])return!1;return!0}static isFilterValueEqual(t,n){return(t??void 0)===(n??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(He.close,{},t)}_onError(t){this._on(He.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=ee.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=bu(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=bu(t.columns,t.old_record)),n}}const no=()=>{},gs={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Kg=[1e3,2e3,5e3,1e4],Gg=1e4,Jg=` +Suggested solution: ${t.workaround}`),new Error(n)}static createWebSocket(t,n){const r=this.getWebSocketConstructor();return new r(t,n)}static isWebSocketSupported(){try{const t=this.detectEnvironment();return t.type==="native"||t.type==="ws"}catch{return!1}}}const jg="2.95.3",Ag=`realtime-js/${jg}`,Pg="1.0.0",ah="2.0.0",xu=ah,sa=1e4,Ng=1e3,Ig=100;var mt;(function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"})(mt||(mt={}));var ee;(function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"})(ee||(ee={}));var He;(function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"})(He||(He={}));var ia;(function(e){e.websocket="websocket"})(ia||(ia={}));var Ft;(function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"})(Ft||(Ft={}));class Lg{constructor(t){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=t??[]}encode(t,n){if(t.event===this.BROADCAST_EVENT&&!(t.payload instanceof ArrayBuffer)&&typeof t.payload.event=="string")return n(this._binaryEncodeUserBroadcastPush(t));let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return n(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(t){var n;return this._isArrayBuffer((n=t.payload)===null||n===void 0?void 0:n.payload)?this._encodeBinaryUserBroadcastPush(t):this._encodeJsonUserBroadcastPush(t)}_encodeBinaryUserBroadcastPush(t){var n,r;const s=(r=(n=t.payload)===null||n===void 0?void 0:n.payload)!==null&&r!==void 0?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(t,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(t){var n,r;const s=(r=(n=t.payload)===null||n===void 0?void 0:n.payload)!==null&&r!==void 0?r:{},o=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(t,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(t,n,r){var s,i;const o=t.topic,a=(s=t.ref)!==null&&s!==void 0?s:"",l=(i=t.join_ref)!==null&&i!==void 0?i:"",u=t.payload.event,c=this.allowedMetadataKeys?this._pick(t.payload,this.allowedMetadataKeys):{},p=Object.keys(c).length===0?"":JSON.stringify(c);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(p.length>255)throw new Error(`metadata length ${p.length} exceeds maximum of 255`);const h=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+u.length+p.length,m=new ArrayBuffer(this.HEADER_LENGTH+h);let v=new DataView(m),y=0;v.setUint8(y++,this.KINDS.userBroadcastPush),v.setUint8(y++,l.length),v.setUint8(y++,a.length),v.setUint8(y++,o.length),v.setUint8(y++,u.length),v.setUint8(y++,p.length),v.setUint8(y++,n),Array.from(l,f=>v.setUint8(y++,f.charCodeAt(0))),Array.from(a,f=>v.setUint8(y++,f.charCodeAt(0))),Array.from(o,f=>v.setUint8(y++,f.charCodeAt(0))),Array.from(u,f=>v.setUint8(y++,f.charCodeAt(0))),Array.from(p,f=>v.setUint8(y++,f.charCodeAt(0)));var k=new Uint8Array(m.byteLength+r.byteLength);return k.set(new Uint8Array(m),0),k.set(new Uint8Array(r),m.byteLength),k.buffer}decode(t,n){if(this._isArrayBuffer(t)){let r=this._binaryDecode(t);return n(r)}if(typeof t=="string"){const r=JSON.parse(t),[s,i,o,a,l]=r;return n({join_ref:s,ref:i,topic:o,event:a,payload:l})}return n({})}_binaryDecode(t){const n=new DataView(t),r=n.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(t,n,s)}}_decodeUserBroadcast(t,n,r){const s=n.getUint8(1),i=n.getUint8(2),o=n.getUint8(3),a=n.getUint8(4);let l=this.HEADER_LENGTH+4;const u=r.decode(t.slice(l,l+s));l=l+s;const c=r.decode(t.slice(l,l+i));l=l+i;const p=r.decode(t.slice(l,l+o));l=l+o;const h=t.slice(l,t.byteLength),m=a===this.JSON_ENCODING?JSON.parse(r.decode(h)):h,v={type:this.BROADCAST_EVENT,event:c,payload:m};return o>0&&(v.meta=JSON.parse(p)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:v}}_isArrayBuffer(t){var n;return t instanceof ArrayBuffer||((n=t==null?void 0:t.constructor)===null||n===void 0?void 0:n.name)==="ArrayBuffer"}_pick(t,n){return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(([r])=>n.includes(r)))}}class lh{constructor(t,n){this.callback=t,this.timerCalc=n,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=n}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var B;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(B||(B={}));const Cu=(e,t,n={})=>{var r;const s=(r=n.skipTypes)!==null&&r!==void 0?r:[];return t?Object.keys(t).reduce((i,o)=>(i[o]=$g(o,e,t,s),i),{}):{}},$g=(e,t,n,r)=>{const s=t.find(a=>a.name===e),i=s==null?void 0:s.type,o=n[e];return i&&!r.includes(i)?uh(i,o):oa(o)},uh=(e,t)=>{if(e.charAt(0)==="_"){const n=e.slice(1,e.length);return Bg(t,n)}switch(e){case B.bool:return Ug(t);case B.float4:case B.float8:case B.int2:case B.int4:case B.int8:case B.numeric:case B.oid:return Dg(t);case B.json:case B.jsonb:return zg(t);case B.timestamp:return Mg(t);case B.abstime:case B.date:case B.daterange:case B.int4range:case B.int8range:case B.money:case B.reltime:case B.text:case B.time:case B.timestamptz:case B.timetz:case B.tsrange:case B.tstzrange:return oa(t);default:return oa(t)}},oa=e=>e,Ug=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},Dg=e=>{if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},zg=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e},Bg=(e,t)=>{if(typeof e!="string")return e;const n=e.length-1,r=e[n];if(e[0]==="{"&&r==="}"){let i;const o=e.slice(1,n);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>uh(t,a))}return e},Mg=e=>typeof e=="string"?e.replace(" ","T"):e,ch=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),t.pathname===""||t.pathname==="/"?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class to{constructor(t,n,r={},s=sa){this.channel=t,this.event=n,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,n){var r;return this._hasReceived(t)&&n((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:t,callback:n}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=n=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=n,this._matchReceive(n)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,n){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:n})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:t,response:n}){this.recHooks.filter(r=>r.status===t).forEach(r=>r.callback(n))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var Ou;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(Ou||(Ou={}));class mr{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(n==null?void 0:n.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},s=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=mr.syncState(this.state,s,i,o),this.pendingDiffs.forEach(l=>{this.state=mr.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},s=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=mr.syncDiff(this.state,s,i,o),a())}),this.onJoin((s,i,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:o})}),this.onLeave((s,i,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,s){const i=this.cloneDeep(t),o=this.transformState(n),a={},l={};return this.map(i,(u,c)=>{o[u]||(l[u]=c)}),this.map(o,(u,c)=>{const p=i[u];if(p){const h=c.map(k=>k.presence_ref),m=p.map(k=>k.presence_ref),v=c.filter(k=>m.indexOf(k.presence_ref)<0),y=p.filter(k=>h.indexOf(k.presence_ref)<0);v.length>0&&(a[u]=v),y.length>0&&(l[u]=y)}else a[u]=c}),this.syncDiff(i,{joins:a,leaves:l},r,s)}static syncDiff(t,n,r,s){const{joins:i,leaves:o}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(i,(a,l)=>{var u;const c=(u=t[a])!==null&&u!==void 0?u:[];if(t[a]=this.cloneDeep(l),c.length>0){const p=t[a].map(m=>m.presence_ref),h=c.filter(m=>p.indexOf(m.presence_ref)<0);t[a].unshift(...h)}r(a,c,l)}),this.map(o,(a,l)=>{let u=t[a];if(!u)return;const c=l.map(p=>p.presence_ref);u=u.filter(p=>c.indexOf(p.presence_ref)<0),t[a]=u,s(a,u,l),u.length===0&&delete t[a]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const s=t[r];return"metas"in s?n[r]=s.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):n[r]=s,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var Ru;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(Ru||(Ru={}));var vr;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"})(vr||(vr={}));var nt;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(nt||(nt={}));class xn{constructor(t,n={config:{}},r){var s,i;if(this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=ee.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},n.config),this.timeout=this.socket.timeout,this.joinPush=new to(this,He.join,this.params,this.timeout),this.rejoinTimer=new lh(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=ee.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=ee.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=ee.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=ee.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=ee.errored,this.rejoinTimer.scheduleTimeout())}),this._on(He.reply,{},(o,a)=>{this._trigger(this._replyEventName(a),o)}),this.presence=new mr(this),this.broadcastEndpointURL=ch(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(t,n=this.timeout){var r,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==ee.closed){const{config:{broadcast:o,presence:a,private:l}}=this.params,u=(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(m=>m.filter))!==null&&s!==void 0?s:[],c=!!this.bindings[vr.PRESENCE]&&this.bindings[vr.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,p={},h={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(p.access_token=this.socket.accessTokenValue),this._onError(m=>t==null?void 0:t(nt.CHANNEL_ERROR,m)),this._onClose(()=>t==null?void 0:t(nt.CLOSED)),this.updateJoinPayload(Object.assign({config:h},p)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive("ok",async({postgres_changes:m})=>{var v;if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){t==null||t(nt.SUBSCRIBED);return}else{const y=this.bindings.postgres_changes,k=(v=y==null?void 0:y.length)!==null&&v!==void 0?v:0,f=[];for(let d=0;d{this.state=ee.errored,t==null||t(nt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(nt.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(t,n={}){return await this.send({type:"presence",event:"track",payload:t},n.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,n,r){return this.state===ee.joined&&t===vr.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(t,n,r)}async httpSend(t,n,r={}){var s;if(n==null)return Promise.reject("Payload is required for httpSend()");const i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:t,payload:n,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{const u=await a.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(t,n={}){var r,s;if(!this._canPush()&&t.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:o}=t,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(r=n.timeout)!==null&&r!==void 0?r:this.timeout);return await((s=u.body)===null||s===void 0?void 0:s.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;const u=this._push(t.type,t,n.timeout||this.timeout);t.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=ee.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(He.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{r=new to(this,He.leave,{},t),r.receive("ok",()=>{n(),s("ok")}).receive("timeout",()=>{n(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{r==null||r.destroy()})}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=ee.closed,this.bindings={}}async _fetchWithTimeout(t,n,r){const s=new AbortController,i=setTimeout(()=>s.abort(),r),o=await this.socket.fetch(t,Object.assign(Object.assign({},n),{signal:s.signal}));return clearTimeout(i),o}_push(t,n,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new to(this,t,n,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(t){if(t.startTimeout(),this.pushBuffer.push(t),this.pushBuffer.length>Ig){const n=this.pushBuffer.shift();n&&(n.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${n.event}`,n.payload))}}_onMessage(t,n,r){return n}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,n,r){var s,i;const o=t.toLocaleLowerCase(),{close:a,error:l,leave:u,join:c}=He;if(r&&[a,l,u,c].indexOf(o)>=0&&r!==this._joinRef())return;let h=this._onMessage(o,n,r);if(n&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(m=>{var v,y,k;return((v=m.filter)===null||v===void 0?void 0:v.event)==="*"||((k=(y=m.filter)===null||y===void 0?void 0:y.event)===null||k===void 0?void 0:k.toLocaleLowerCase())===o}).map(m=>m.callback(h,r)):(i=this.bindings[o])===null||i===void 0||i.filter(m=>{var v,y,k,f,d,g;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in m){const _=m.id,E=(v=m.filter)===null||v===void 0?void 0:v.event;return _&&((y=n.ids)===null||y===void 0?void 0:y.includes(_))&&(E==="*"||(E==null?void 0:E.toLocaleLowerCase())===((k=n.data)===null||k===void 0?void 0:k.type.toLocaleLowerCase()))}else{const _=(d=(f=m==null?void 0:m.filter)===null||f===void 0?void 0:f.event)===null||d===void 0?void 0:d.toLocaleLowerCase();return _==="*"||_===((g=n==null?void 0:n.event)===null||g===void 0?void 0:g.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===o}).map(m=>{if(typeof h=="object"&&"ids"in h){const v=h.data,{schema:y,table:k,commit_timestamp:f,type:d,errors:g}=v;h=Object.assign(Object.assign({},{schema:y,table:k,commit_timestamp:f,eventType:d,new:{},old:{},errors:g}),this._getPayloadRecords(v))}m.callback(h,r)})}_isClosed(){return this.state===ee.closed}_isJoined(){return this.state===ee.joined}_isJoining(){return this.state===ee.joining}_isLeaving(){return this.state===ee.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,n,r){const s=t.toLocaleLowerCase(),i={type:s,filter:n,callback:r};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(t,n){const r=t.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(s=>{var i;return!(((i=s.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===r&&xn.isEqual(s.filter,n))})),this}static isEqual(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in t)if(t[r]!==n[r])return!1;return!0}static isFilterValueEqual(t,n){return(t??void 0)===(n??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(He.close,{},t)}_onError(t){this._on(He.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=ee.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=Cu(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=Cu(t.columns,t.old_record)),n}}const no=()=>{},ps={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Fg=[1e3,2e3,5e3,1e4],Wg=1e4,Vg=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } - });`;class Qg{constructor(t,n){var r;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=sa,this.transport=null,this.heartbeatIntervalMs=gs.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=no,this.ref=0,this.reconnectTimer=null,this.vsn=Tu,this.logger=no,this.conn=null,this.sendBuffer=[],this.serializer=new Mg,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((r=n==null?void 0:n.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=n.params.apikey,this.endPoint=`${t}/${ia.websocket}`,this.httpEndpoint=ch(t),this._initializeOptions(n),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(n==null?void 0:n.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=Ig.createWebSocket(this.endpointURL())}catch(t){this._setConnectionState("disconnected");const n=t.message;throw n.includes("Node.js")?new Error(`${n} + });`;class Hg{constructor(t,n){var r;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=sa,this.transport=null,this.heartbeatIntervalMs=ps.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=no,this.ref=0,this.reconnectTimer=null,this.vsn=xu,this.logger=no,this.conn=null,this.sendBuffer=[],this.serializer=new Lg,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((r=n==null?void 0:n.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=n.params.apikey,this.endPoint=`${t}/${ia.websocket}`,this.httpEndpoint=ch(t),this._initializeOptions(n),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(n==null?void 0:n.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=Rg.createWebSocket(this.endpointURL())}catch(t){this._setConnectionState("disconnected");const n=t.message;throw n.includes("Node.js")?new Error(`${n} To use Realtime in Node.js, you need to provide a WebSocket implementation: @@ -102,13 +92,13 @@ Option 2: Install and provide the "ws" package: const client = new RealtimeClient(url, { ...options, transport: ws - })`):new Error(`WebSocket not available: ${n}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(t,n){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(t?this.conn.close(t,n??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(t){const n=await t.unsubscribe();return n==="ok"&&this._remove(t),this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const t=await Promise.all(this.channels.map(n=>n.unsubscribe()));return this.channels=[],this.disconnect(),t}log(t,n,r){this.logger(t,n,r)}connectionState(){switch(this.conn&&this.conn.readyState){case mt.connecting:return Ft.Connecting;case mt.open:return Ft.Open;case mt.closing:return Ft.Closing;default:return Ft.Closed}}isConnected(){return this.connectionState()===Ft.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(t,n={config:{}}){const r=`realtime:${t}`,s=this.getChannels().find(i=>i.topic===r);if(s)return s;{const i=new bn(`realtime:${t}`,n,this);return this.channels.push(i),i}}push(t){const{topic:n,event:r,payload:s,ref:i}=t,o=()=>{this.encode(t,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${n} ${r} (${i})`,s),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(t=null){this._authPromise=this._performAuth(t);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var t;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(n){this.log("error","error in heartbeat callback",n)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,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._wasManualDisconnect=!1,(t=this.conn)===null||t===void 0||t.close(Dg,"heartbeat timeout"),setTimeout(()=>{var n;this.isConnected()||(n=this.reconnectTimer)===null||n===void 0||n.scheduleTimeout()},gs.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),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._setAuthSafely("heartbeat")}onHeartbeat(t){this.heartbeatCallback=t}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let n=this.channels.find(r=>r.topic===t&&(r._isJoined()||r._isJoining()));n&&(this.log("transport",`leaving duplicate topic "${t}"`),n.unsubscribe())}_remove(t){this.channels=this.channels.filter(n=>n.topic!==t.topic)}_onConnMessage(t){this.decode(t.data,n=>{if(n.topic==="phoenix"&&n.event==="phx_reply"&&n.ref&&n.ref===this.pendingHeartbeatRef){const u=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(n.payload.status==="ok"?"ok":"error",u)}catch(c){this.log("error","error in heartbeat callback",c)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:r,event:s,payload:i,ref:o}=n,a=o?`(${o})`:"",l=i.status||"";this.log("receive",`${l} ${r} ${s} ${a}`.trim(),i),this.channels.filter(u=>u._isMember(r)).forEach(u=>u._trigger(s,i,o)),this._triggerStateCallbacks("message",n)})}_clearTimer(t){var n;t==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):t==="reconnect"&&((n=this.reconnectTimer)===null||n===void 0||n.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t),this.conn.readyState===mt.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===mt.open||this.conn.readyState===mt.connecting)try{this.conn.close()}catch(t){this.log("error","Error closing connection",t)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(t=>t.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(n=>{this.log("error","error waiting for auth on connect",n),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=n=>{this.log("worker","worker error",n.message),this._terminateWorker()},this.workerRef.onmessage=n=>{n.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)}_onConnClose(t){var n;this._setConnectionState("disconnected"),this.log("transport","close",t),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(n=this.reconnectTimer)===null||n===void 0||n.scheduleTimeout(),this._triggerStateCallbacks("close",t)}_onConnError(t){this._setConnectionState("disconnected"),this.log("transport",`${t}`),this._triggerChanError(),this._triggerStateCallbacks("error",t);try{this.heartbeatCallback("error")}catch(n){this.log("error","error in heartbeat callback",n)}}_triggerChanError(){this.channels.forEach(t=>t._trigger(He.error))}_appendParams(t,n){if(Object.keys(n).length===0)return t;const r=t.match(/\?/)?"&":"?",s=new URLSearchParams(n);return`${t}${r}${s}`}_workerObjectUrl(t){let n;if(t)n=t;else{const r=new Blob([Jg],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}_setConnectionState(t,n=!1){this._connectionState=t,t==="connecting"?this._wasManualDisconnect=!1:t==="disconnecting"&&(this._wasManualDisconnect=n)}async _performAuth(t=null){let n,r=!1;if(t)n=t,r=!0;else if(this.accessToken)try{n=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),n=this.accessTokenValue}else n=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(s=>{const i={access_token:n,version:$g};n&&s.updateJoinPayload(i),s.joinedOnce&&s._isJoined()&&s._push(He.access_token,{access_token:n})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(t="general"){this._isManualToken()||this.setAuth().catch(n=>{this.log("error",`Error setting auth in ${t}`,n)})}_triggerStateCallbacks(t,n){try{this.stateChangeCallbacks[t].forEach(r=>{try{r(n)}catch(s){this.log("error",`error in ${t} callback`,s)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}_setupReconnectionTimer(){this.reconnectTimer=new lh(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},gs.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(t){var n,r,s,i,o,a,l,u,c,p,h,m;switch(this.transport=(n=t==null?void 0:t.transport)!==null&&n!==void 0?n:null,this.timeout=(r=t==null?void 0:t.timeout)!==null&&r!==void 0?r:sa,this.heartbeatIntervalMs=(s=t==null?void 0:t.heartbeatIntervalMs)!==null&&s!==void 0?s:gs.HEARTBEAT_INTERVAL,this.worker=(i=t==null?void 0:t.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=t==null?void 0:t.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=t==null?void 0:t.heartbeatCallback)!==null&&a!==void 0?a:no,this.vsn=(l=t==null?void 0:t.vsn)!==null&&l!==void 0?l:Tu,t!=null&&t.params&&(this.params=t.params),t!=null&&t.logger&&(this.logger=t.logger),(t!=null&&t.logLevel||t!=null&&t.log_level)&&(this.logLevel=t.logLevel||t.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(u=t==null?void 0:t.reconnectAfterMs)!==null&&u!==void 0?u:y=>Kg[y-1]||Gg,this.vsn){case Ug:this.encode=(c=t==null?void 0:t.encode)!==null&&c!==void 0?c:(y,w)=>w(JSON.stringify(y)),this.decode=(p=t==null?void 0:t.decode)!==null&&p!==void 0?p:(y,w)=>w(JSON.parse(y));break;case ah:this.encode=(h=t==null?void 0:t.encode)!==null&&h!==void 0?h:this.serializer.encode.bind(this.serializer),this.decode=(m=t==null?void 0:t.decode)!==null&&m!==void 0?m:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=t==null?void 0:t.workerUrl}}}var Ur=class extends Error{constructor(e,t){var n;super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType==="CommitStateUnknownException"||[500,502,504].includes(t.status)&&((n=t.icebergType)==null?void 0:n.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Yg(e,t,n){const r=new URL(t,e);if(n)for(const[s,i]of Object.entries(n))i!==void 0&&r.searchParams.set(s,i);return r.toString()}async function Xg(e){return!e||e.type==="none"?{}:e.type==="bearer"?{Authorization:`Bearer ${e.token}`}:e.type==="header"?{[e.name]:e.value}:e.type==="custom"?await e.getHeaders():{}}function Zg(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:s,body:i,headers:o}){const a=Yg(e.baseUrl,r,s),l=await Xg(e.auth),u=await t(a,{method:n,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),c=await u.text(),p=(u.headers.get("content-type")||"").includes("application/json"),h=p&&c?JSON.parse(c):c;if(!u.ok){const m=p?h:void 0,y=m==null?void 0:m.error;throw new Ur((y==null?void 0:y.message)??`Request failed with status ${u.status}`,{status:u.status,icebergType:y==null?void 0:y.type,icebergCode:y==null?void 0:y.code,details:m})}return{status:u.status,headers:u.headers,data:h}}}}function ms(e){return e.join("")}var em=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:ms(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(r=>({namespace:r}))}async createNamespace(e,t){const n={namespace:e.namespace,properties:t==null?void 0:t.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ms(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ms(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ms(e.namespace)}`}),!0}catch(t){if(t instanceof Ur&&t.status===404)return!1;throw t}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(n){if(n instanceof Ur&&n.status===409)return;throw n}}};function sn(e){return e.join("")}var tm=class{constructor(e,t="",n){this.client=e,this.prefix=t,this.accessDelegation=n}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const n={};return this.accessDelegation&&(n["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables`,body:t,headers:n})).data.metadata}async updateTable(e,t){const n=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":n.data["metadata-location"],metadata:n.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String((t==null?void 0:t.purge)??!1)}})}async loadTable(e){const t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(n){if(n instanceof Ur&&n.status===404)return!1;throw n}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(n){if(n instanceof Ur&&n.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw n}}},nm=class{constructor(e){var r;let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const n=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=Zg({baseUrl:n,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=(r=e.accessDelegation)==null?void 0:r.join(","),this.namespaceOps=new em(this.client,t),this.tableOps=new tm(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},Ei=class extends Error{constructor(e,t="storage",n,r){super(e),this.__isStorageError=!0,this.namespace=t,this.name=t==="vectors"?"StorageVectorsError":"StorageError",this.status=n,this.statusCode=r}};function xi(e){return typeof e=="object"&&e!==null&&"__isStorageError"in e}var vs=class extends Ei{constructor(e,t,n,r="storage"){super(e,r,t,n),this.name=r==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},dh=class extends Ei{constructor(e,t,n="storage"){super(e,n),this.name=n==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};const rm=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),sm=e=>{if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},aa=e=>{if(Array.isArray(e))return e.map(n=>aa(n));if(typeof e=="function"||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([n,r])=>{const s=n.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[s]=aa(r)}),t},im=e=>!e||typeof e!="string"||e.length===0||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e);function Dr(e){"@babel/helpers - typeof";return Dr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Dr(e)}function om(e,t){if(Dr(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Dr(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function am(e){var t=om(e,"string");return Dr(t)=="symbol"?t:t+""}function lm(e,t,n){return(t=am(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ju(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function P(e){for(var t=1;t{var t;return e.msg||e.message||e.error_description||(typeof e.error=="string"?e.error:(t=e.error)===null||t===void 0?void 0:t.message)||JSON.stringify(e)},um=async(e,t,n,r)=>{if(e&&typeof e=="object"&&"status"in e&&"ok"in e&&typeof e.status=="number"&&!(n!=null&&n.noResolveJson)){const s=e,i=s.status||500;if(typeof s.json=="function")s.json().then(o=>{const a=(o==null?void 0:o.statusCode)||(o==null?void 0:o.code)||i+"";t(new vs(Ru(o),i,a,r))}).catch(()=>{if(r==="vectors"){const o=i+"";t(new vs(s.statusText||`HTTP ${i} error`,i,o,r))}else{const o=i+"";t(new vs(s.statusText||`HTTP ${i} error`,i,o,r))}});else{const o=i+"";t(new vs(s.statusText||`HTTP ${i} error`,i,o,r))}}else t(new dh(Ru(e),e,r))},cm=(e,t,n,r)=>{const s={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"||e==="HEAD"||!r?P(P({},s),n):(sm(r)?(s.headers=P({"Content-Type":"application/json"},t==null?void 0:t.headers),s.body=JSON.stringify(r)):s.body=r,t!=null&&t.duplex&&(s.duplex=t.duplex),P(P({},s),n))};async function nr(e,t,n,r,s,i,o){return new Promise((a,l)=>{e(n,cm(t,r,s,i)).then(u=>{if(!u.ok)throw u;if(r!=null&&r.noResolveJson)return u;if(o==="vectors"){const c=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!c||!c.includes("application/json"))return{}}return u.json()}).then(u=>a(u)).catch(u=>um(u,l,r,o))})}function hh(e="storage"){return{get:async(t,n,r,s)=>nr(t,"GET",n,r,s,void 0,e),post:async(t,n,r,s,i)=>nr(t,"POST",n,s,i,r,e),put:async(t,n,r,s,i)=>nr(t,"PUT",n,s,i,r,e),head:async(t,n,r,s)=>nr(t,"HEAD",n,P(P({},r),{},{noResolveJson:!0}),s,void 0,e),remove:async(t,n,r,s,i)=>nr(t,"DELETE",n,s,i,r,e)}}const dm=hh("storage"),{get:zr,post:We,put:la,head:hm,remove:ul}=dm,be=hh("vectors");var Hn=class{constructor(e,t={},n,r="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.fetch=rm(n),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(n){if(t.shouldThrowOnError)throw n;if(xi(n))return{data:null,error:n};throw n}}},fm=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(xi(t))return{data:null,error:t};throw t}}};let fh;fh=Symbol.toStringTag;var pm=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[fh]="BlobDownloadBuilder",this.promise=null}asStream(){return new fm(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(xi(t))return{data:null,error:t};throw t}}};const gm={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Pu={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var mm=class extends Hn{constructor(e,t={},n,r){super(e,t,r,"storage"),this.bucketId=n}async uploadOrUpdate(e,t,n,r){var s=this;return s.handleOperation(async()=>{let i;const o=P(P({},Pu),r);let a=P(P({},s.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",s.encodeMetadata(l)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(l))):(i=n,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=s.toBase64(s.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),r!=null&&r.headers&&(a=P(P({},a),r.headers));const u=s._removeEmptyFolders(t),c=s._getFinalPath(u),p=await(e=="PUT"?la:We)(s.fetch,`${s.url}/object/${c}`,i,P({headers:a},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{path:u,id:p.Id,fullPath:p.Key}})}async upload(e,t,n){return this.uploadOrUpdate("POST",e,t,n)}async uploadToSignedUrl(e,t,n,r){var s=this;const i=s._removeEmptyFolders(e),o=s._getFinalPath(i),a=new URL(s.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",t),s.handleOperation(async()=>{let l;const u=P({upsert:Pu.upsert},r),c=P(P({},s.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&n instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",n)):typeof FormData<"u"&&n instanceof FormData?(l=n,l.append("cacheControl",u.cacheControl)):(l=n,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType),{path:i,fullPath:(await la(s.fetch,a.toString(),l,{headers:c})).Key}})}async createSignedUploadUrl(e,t){var n=this;return n.handleOperation(async()=>{let r=n._getFinalPath(e);const s=P({},n.headers);t!=null&&t.upsert&&(s["x-upsert"]="true");const i=await We(n.fetch,`${n.url}/object/upload/sign/${r}`,{},{headers:s}),o=new URL(n.url+i.url),a=o.searchParams.get("token");if(!a)throw new Ei("No token returned by API");return{signedUrl:o.toString(),path:e,token:a}})}async update(e,t,n){return this.uploadOrUpdate("PUT",e,t,n)}async move(e,t,n){var r=this;return r.handleOperation(async()=>await We(r.fetch,`${r.url}/object/move`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:r.headers}))}async copy(e,t,n){var r=this;return r.handleOperation(async()=>({path:(await We(r.fetch,`${r.url}/object/copy`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:r.headers})).Key}))}async createSignedUrl(e,t,n){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(e),i=await We(r.fetch,`${r.url}/object/sign/${s}`,P({expiresIn:t},n!=null&&n.transform?{transform:n.transform}:{}),{headers:r.headers});const o=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{signedUrl:encodeURI(`${r.url}${i.signedURL}${o}`)}})}async createSignedUrls(e,t,n){var r=this;return r.handleOperation(async()=>{const s=await We(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:t,paths:e},{headers:r.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return s.map(o=>P(P({},o),{},{signedUrl:o.signedURL?encodeURI(`${r.url}${o.signedURL}${i}`):null}))})}download(e,t,n){const r=typeof(t==null?void 0:t.transform)<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),i=s?`?${s}`:"",o=this._getFinalPath(e),a=()=>zr(this.fetch,`${this.url}/${r}/${o}${i}`,{headers:this.headers,noResolveJson:!0},n);return new pm(a,this.shouldThrowOnError)}async info(e){var t=this;const n=t._getFinalPath(e);return t.handleOperation(async()=>aa(await zr(t.fetch,`${t.url}/object/info/${n}`,{headers:t.headers})))}async exists(e){var t=this;const n=t._getFinalPath(e);try{return await hm(t.fetch,`${t.url}/object/${n}`,{headers:t.headers}),{data:!0,error:null}}catch(r){if(t.shouldThrowOnError)throw r;if(xi(r)&&r instanceof dh){const s=r.originalError;if([400,404].includes(s==null?void 0:s.status))return{data:!1,error:r}}throw r}}getPublicUrl(e,t){const n=this._getFinalPath(e),r=[],s=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";s!==""&&r.push(s);const i=typeof(t==null?void 0:t.transform)<"u"?"render/image":"object",o=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});o!==""&&r.push(o);let a=r.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${n}${a}`)}}}async remove(e){var t=this;return t.handleOperation(async()=>await ul(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,n){var r=this;return r.handleOperation(async()=>{const s=P(P(P({},gm),t),{},{prefix:e||""});return await We(r.fetch,`${r.url}/object/list/${r.bucketId}`,s,{headers:r.headers},n)})}async listV2(e,t){var n=this;return n.handleOperation(async()=>{const r=P({},e);return await We(n.fetch,`${n.url}/object/list-v2/${n.bucketId}`,r,{headers:n.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};const vm="2.95.3",Gr={"X-Client-Info":`storage-js/${vm}`};var ym=class extends Hn{constructor(e,t={},n,r){const s=new URL(e);r!=null&&r.useNewHostname&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase."));const i=s.href.replace(/\/$/,""),o=P(P({},Gr),t);super(i,o,n,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const n=t.listBucketOptionsToQueryString(e);return await zr(t.fetch,`${t.url}/bucket${n}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await zr(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var n=this;return n.handleOperation(async()=>await We(n.fetch,`${n.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async updateBucket(e,t){var n=this;return n.handleOperation(async()=>await la(n.fetch,`${n.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await We(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await ul(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},wm=class extends Hn{constructor(e,t={},n){const r=e.replace(/\/$/,""),s=P(P({},Gr),t);super(r,s,n,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await We(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const n=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&n.set("limit",e.limit.toString()),(e==null?void 0:e.offset)!==void 0&&n.set("offset",e.offset.toString()),e!=null&&e.sortColumn&&n.set("sortColumn",e.sortColumn),e!=null&&e.sortOrder&&n.set("sortOrder",e.sortOrder),e!=null&&e.search&&n.set("search",e.search);const r=n.toString(),s=r?`${t.url}/bucket?${r}`:`${t.url}/bucket`;return await zr(t.fetch,s,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await ul(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!im(e))throw new Ei("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 n=new nm({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),r=this.shouldThrowOnError;return new Proxy(n,{get(s,i){const o=s[i];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(s,a),error:null}}catch(l){if(r)throw l;return{data:null,error:l}}}}})}},_m=class extends Hn{constructor(e,t={},n){const r=e.replace(/\/$/,""),s=P(P({},Gr),{},{"Content-Type":"application/json"},t);super(r,s,n,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await be.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var n=this;return n.handleOperation(async()=>await be.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await be.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var n=this;return n.handleOperation(async()=>await be.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers})||{})}},Sm=class extends Hn{constructor(e,t={},n){const r=e.replace(/\/$/,""),s=P(P({},Gr),{},{"Content-Type":"application/json"},t);super(r,s,n,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await be.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await be.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await be.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await be.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await be.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},km=class extends Hn{constructor(e,t={},n){const r=e.replace(/\/$/,""),s=P(P({},Gr),{},{"Content-Type":"application/json"},t);super(r,s,n,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await be.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await be.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await be.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await be.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},Em=class extends km{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new xm(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,n=this;return t().call(n,e)}async getBucket(e){var t=()=>super.getBucket,n=this;return t().call(n,e)}async listBuckets(e={}){var t=()=>super.listBuckets,n=this;return t().call(n,e)}async deleteBucket(e){var t=()=>super.deleteBucket,n=this;return t().call(n,e)}},xm=class extends _m{constructor(e,t,n,r){super(e,t,r),this.vectorBucketName=n}async createIndex(e){var t=()=>super.createIndex,n=this;return t().call(n,P(P({},e),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,n=this;return t().call(n,P(P({},e),{},{vectorBucketName:n.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,n=this;return t().call(n,n.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,n=this;return t().call(n,n.vectorBucketName,e)}index(e){return new Tm(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},Tm=class extends Sm{constructor(e,t,n,r,s){super(e,t,s),this.vectorBucketName=n,this.indexName=r}async putVectors(e){var t=()=>super.putVectors,n=this;return t().call(n,P(P({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(e){var t=()=>super.getVectors,n=this;return t().call(n,P(P({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,n=this;return t().call(n,P(P({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,n=this;return t().call(n,P(P({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,n=this;return t().call(n,P(P({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},bm=class extends ym{constructor(e,t={},n,r){super(e,t,n,r)}from(e){return new mm(this.url,this.headers,e,this.fetch)}get vectors(){return new Em(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new wm(this.url+"/iceberg",this.headers,this.fetch)}};const ph="2.95.3",hn=30*1e3,ua=3,ro=ua*hn,Cm="http://localhost:9999",Om="supabase.auth.token",jm={"X-Client-Info":`gotrue-js/${ph}`},ca="X-Supabase-Api-Version",gh={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Rm=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Pm=10*60*1e3;class Mr extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function j(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}class Am extends Mr{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function Nm(e){return j(e)&&e.name==="AuthApiError"}class Wt extends Mr{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class ht extends Mr{constructor(t,n,r,s){super(t,r,s),this.name=n,this.status=r}}class xe extends ht{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function so(e){return j(e)&&e.name==="AuthSessionMissingError"}class on extends ht{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class ys extends ht{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class ws extends ht{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function Im(e){return j(e)&&e.name==="AuthImplicitGrantRedirectError"}class Au extends ht{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Lm extends ht{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 da extends ht{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function io(e){return j(e)&&e.name==="AuthRetryableFetchError"}class Nu extends ht{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class ha extends ht{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const ri="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Iu=` -\r=`.split(""),$m=(()=>{const e=new Array(128);for(let t=0;t=6;){const r=t.queue>>t.queuedBits-6&63;n(ri[r]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const r=t.queue>>t.queuedBits-6&63;n(ri[r]),t.queuedBits-=6}}function mh(e,t,n){const r=$m[e];if(r>-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}}function $u(e){const t=[],n=o=>{t.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{zm(o,r,n)};for(let o=0;o>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function Dm(e,t){for(let n=0;n55295&&r<=56319){const s=(r-55296)*1024&65535;r=(e.charCodeAt(n+1)-56320&65535|s)+65536,n+=1}Um(r,t)}}function zm(e,t,n){if(t.utf8seq===0){if(e<=127){n(e);return}for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|e&63,t.utf8seq-=1,t.utf8seq===0&&n(t.codepoint)}}function Nn(e){const t=[],n={queue:0,queuedBits:0},r=s=>{t.push(s)};for(let s=0;st.push(n)),new Uint8Array(t)}function Kt(e){const t=[],n={queue:0,queuedBits:0},r=s=>{t.push(s)};return e.forEach(s=>Lu(s,n,r)),Lu(null,n,r),t.join("")}function Bm(e){return Math.round(Date.now()/1e3)+e}function Fm(){return Symbol("auth-callback")}const ae=()=>typeof window<"u"&&typeof document<"u",Ut={tested:!1,writable:!1},vh=()=>{if(!ae())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ut.tested)return Ut.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Ut.tested=!0,Ut.writable=!0}catch{Ut.tested=!0,Ut.writable=!1}return Ut.writable};function Wm(e){const t={},n=new URL(e);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((s,i)=>{t[i]=s})}catch{}return n.searchParams.forEach((r,s)=>{t[s]=r}),t}const yh=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),Vm=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",fn=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},Dt=async(e,t)=>{const n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},oe=async(e,t)=>{await e.removeItem(t)};class Ti{constructor(){this.promise=new Ti.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}Ti.promiseConstructor=Promise;function _s(e){const t=e.split(".");if(t.length!==3)throw new ha("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),e)})}function qm(e,t){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await e(i);if(!t(i,null,o)){r(o);return}}catch(o){if(!t(i,o)){s(o);return}}})()})}function Km(e){return("0"+e.toString(16)).substr(-2)}function Gm(){const t=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let s="";for(let i=0;i<56;i++)s+=n.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(t),Array.from(t,Km).join("")}async function Jm(e){const n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function Qm(e){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."),e;const n=await Jm(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function an(e,t,n=!1){const r=Gm();let s=r;n&&(s+="/PASSWORD_RECOVERY"),await fn(e,`${t}-code-verifier`,s);const i=await Qm(r);return[i,r===i?"plain":"s256"]}const Ym=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Xm(e){const t=e.headers.get(ca);if(!t||!t.match(Ym))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function Zm(e){if(!e)throw new Error("Missing exp claim");const t=Math.floor(Date.now()/1e3);if(e<=t)throw new Error("JWT has expired")}function ev(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const tv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ln(e){if(!tv.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function oo(){const e={};return new Proxy(e,{get:(t,n)=>{if(n==="__isUserNotAvailableProxy")return!0;if(typeof n=="symbol"){const r=n.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${n}" property of the session object is not supported. Please use getUser() instead.`)},set:(t,n)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${n}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(t,n)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${n}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function nv(e,t){return new Proxy(e,{get:(n,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){const i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(n,r,s)}return!t.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),t.value=!0),Reflect.get(n,r,s)}})}function Uu(e){return JSON.parse(JSON.stringify(e))}const Bt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),rv=[502,503,504];async function Du(e){var t;if(!Vm(e))throw new da(Bt(e),0);if(rv.includes(e.status))throw new da(Bt(e),e.status);let n;try{n=await e.json()}catch(i){throw new Wt(Bt(i),i)}let r;const s=Xm(e);if(s&&s.getTime()>=gh["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new Nu(Bt(n),e.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new xe}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Nu(Bt(n),e.status,n.weak_password.reasons);throw new Am(Bt(n),e.status||500,r)}const sv=(e,t,n,r)=>{const s={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),n))};async function R(e,t,n,r){var s;const i=Object.assign({},r==null?void 0:r.headers);i[ca]||(i[ca]=gh["2024-01-01"].name),r!=null&&r.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const o=(s=r==null?void 0:r.query)!==null&&s!==void 0?s:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await iv(e,t,n+a,{headers:i,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(l):{data:Object.assign({},l),error:null}}async function iv(e,t,n,r,s,i){const o=sv(t,r,s,i);let a;try{a=await e(n,Object.assign({},o))}catch(l){throw console.error(l),new da(Bt(l),0)}if(a.ok||await Du(a),r!=null&&r.noResolveJson)return a;try{return await a.json()}catch(l){await Du(l)}}function Be(e){var t;let n=null;lv(e)&&(n=Object.assign({},e),e.expires_at||(n.expires_at=Bm(e.expires_in)));const r=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:n,user:r},error:null}}function zu(e){const t=Be(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(t.data.weak_password=e.weak_password),t}function wt(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function ov(e){return{data:e,error:null}}function av(e){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:s,verification_type:i}=e,o=ki(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:t,email_otp:n,hashed_token:r,redirect_to:s,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Mu(e){return e}function lv(e){return e.access_token&&e.refresh_token&&e.expires_in}const ao=["global","local","others"];class uv{constructor({url:t="",headers:n={},fetch:r}){this.url=t,this.headers=n,this.fetch=yh(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(t,n=ao[0]){if(ao.indexOf(n)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ao.join(", ")}`);try{return await R(this.fetch,"POST",`${this.url}/logout?scope=${n}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(r){if(j(r))return{data:null,error:r};throw r}}async inviteUserByEmail(t,n={}){try{return await R(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:wt})}catch(r){if(j(r))return{data:{user:null},error:r};throw r}}async generateLink(t){try{const{options:n}=t,r=ki(t,["options"]),s=Object.assign(Object.assign({},r),n);return"newEmail"in r&&(s.new_email=r==null?void 0:r.newEmail,delete s.newEmail),await R(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:av,redirectTo:n==null?void 0:n.redirectTo})}catch(n){if(j(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(t){try{return await R(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:wt})}catch(n){if(j(n))return{data:{user:null},error:n};throw n}}async listUsers(t){var n,r,s,i,o,a,l;try{const u={nextPage:null,lastPage:0,total:0},c=await R(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=t==null?void 0:t.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Mu});if(c.error)throw c.error;const p=await c.json(),h=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(y=>{const w=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),S=JSON.parse(y.split(";")[1].split("=")[1]);u[`${S}Page`]=w}),u.total=parseInt(h)),{data:Object.assign(Object.assign({},p),u),error:null}}catch(u){if(j(u))return{data:{users:[]},error:u};throw u}}async getUserById(t){ln(t);try{return await R(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:wt})}catch(n){if(j(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){ln(t);try{return await R(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:wt})}catch(r){if(j(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){ln(t);try{return await R(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:wt})}catch(r){if(j(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){ln(t.userId);try{const{data:n,error:r}=await R(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:n,error:r}}catch(n){if(j(n))return{data:null,error:n};throw n}}async _deleteFactor(t){ln(t.userId),ln(t.id);try{return{data:await R(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(j(n))return{data:null,error:n};throw n}}async _listOAuthClients(t){var n,r,s,i,o,a,l;try{const u={nextPage:null,lastPage:0,total:0},c=await R(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=t==null?void 0:t.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Mu});if(c.error)throw c.error;const p=await c.json(),h=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(y=>{const w=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),S=JSON.parse(y.split(";")[1].split("=")[1]);u[`${S}Page`]=w}),u.total=parseInt(h)),{data:Object.assign(Object.assign({},p),u),error:null}}catch(u){if(j(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(t){try{return await R(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:t,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(j(n))return{data:null,error:n};throw n}}async _getOAuthClient(t){try{return await R(this.fetch,"GET",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(j(n))return{data:null,error:n};throw n}}async _updateOAuthClient(t,n){try{return await R(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${t}`,{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(j(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(t){try{return await R(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(j(n))return{data:null,error:n};throw n}}async _regenerateOAuthClientSecret(t){try{return await R(this.fetch,"POST",`${this.url}/admin/oauth/clients/${t}/regenerate_secret`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(j(n))return{data:null,error:n};throw n}}}function Bu(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}const un={debug:!!(globalThis&&vh()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class wh extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class cv extends wh{}async function dv(e,t,n){un.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),un.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async s=>{if(s){un.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await n()}finally{un.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}else{if(t===0)throw un.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new cv(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(un.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await n()}}))}function hv(){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 _h(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function fv(e){return parseInt(e,16)}function pv(e){const t=new TextEncoder().encode(e);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function gv(e){var t;const{chainId:n,domain:r,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:u,scheme:c,uri:p,version:h}=e;{if(!Number.isInteger(n))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${n}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!p)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(h!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);if(!((t=e.statement)===null||t===void 0)&&t.includes(` -`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`)}const m=_h(e.address),y=c?`${c}://${r}`:r,w=e.statement?`${e.statement} -`:"",S=`${y} wants you to sign in with your Ethereum account: + })`):new Error(`WebSocket not available: ${n}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(t,n){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(t?this.conn.close(t,n??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(t){const n=await t.unsubscribe();return n==="ok"&&this._remove(t),this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const t=await Promise.all(this.channels.map(n=>n.unsubscribe()));return this.channels=[],this.disconnect(),t}log(t,n,r){this.logger(t,n,r)}connectionState(){switch(this.conn&&this.conn.readyState){case mt.connecting:return Ft.Connecting;case mt.open:return Ft.Open;case mt.closing:return Ft.Closing;default:return Ft.Closed}}isConnected(){return this.connectionState()===Ft.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(t,n={config:{}}){const r=`realtime:${t}`,s=this.getChannels().find(i=>i.topic===r);if(s)return s;{const i=new xn(`realtime:${t}`,n,this);return this.channels.push(i),i}}push(t){const{topic:n,event:r,payload:s,ref:i}=t,o=()=>{this.encode(t,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${n} ${r} (${i})`,s),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(t=null){this._authPromise=this._performAuth(t);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var t;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(n){this.log("error","error in heartbeat callback",n)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,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._wasManualDisconnect=!1,(t=this.conn)===null||t===void 0||t.close(Ng,"heartbeat timeout"),setTimeout(()=>{var n;this.isConnected()||(n=this.reconnectTimer)===null||n===void 0||n.scheduleTimeout()},ps.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),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._setAuthSafely("heartbeat")}onHeartbeat(t){this.heartbeatCallback=t}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let n=this.channels.find(r=>r.topic===t&&(r._isJoined()||r._isJoining()));n&&(this.log("transport",`leaving duplicate topic "${t}"`),n.unsubscribe())}_remove(t){this.channels=this.channels.filter(n=>n.topic!==t.topic)}_onConnMessage(t){this.decode(t.data,n=>{if(n.topic==="phoenix"&&n.event==="phx_reply"&&n.ref&&n.ref===this.pendingHeartbeatRef){const u=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(n.payload.status==="ok"?"ok":"error",u)}catch(c){this.log("error","error in heartbeat callback",c)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:r,event:s,payload:i,ref:o}=n,a=o?`(${o})`:"",l=i.status||"";this.log("receive",`${l} ${r} ${s} ${a}`.trim(),i),this.channels.filter(u=>u._isMember(r)).forEach(u=>u._trigger(s,i,o)),this._triggerStateCallbacks("message",n)})}_clearTimer(t){var n;t==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):t==="reconnect"&&((n=this.reconnectTimer)===null||n===void 0||n.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t),this.conn.readyState===mt.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===mt.open||this.conn.readyState===mt.connecting)try{this.conn.close()}catch(t){this.log("error","Error closing connection",t)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(t=>t.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(n=>{this.log("error","error waiting for auth on connect",n),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=n=>{this.log("worker","worker error",n.message),this._terminateWorker()},this.workerRef.onmessage=n=>{n.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)}_onConnClose(t){var n;this._setConnectionState("disconnected"),this.log("transport","close",t),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(n=this.reconnectTimer)===null||n===void 0||n.scheduleTimeout(),this._triggerStateCallbacks("close",t)}_onConnError(t){this._setConnectionState("disconnected"),this.log("transport",`${t}`),this._triggerChanError(),this._triggerStateCallbacks("error",t);try{this.heartbeatCallback("error")}catch(n){this.log("error","error in heartbeat callback",n)}}_triggerChanError(){this.channels.forEach(t=>t._trigger(He.error))}_appendParams(t,n){if(Object.keys(n).length===0)return t;const r=t.match(/\?/)?"&":"?",s=new URLSearchParams(n);return`${t}${r}${s}`}_workerObjectUrl(t){let n;if(t)n=t;else{const r=new Blob([Vg],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}_setConnectionState(t,n=!1){this._connectionState=t,t==="connecting"?this._wasManualDisconnect=!1:t==="disconnecting"&&(this._wasManualDisconnect=n)}async _performAuth(t=null){let n,r=!1;if(t)n=t,r=!0;else if(this.accessToken)try{n=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),n=this.accessTokenValue}else n=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(s=>{const i={access_token:n,version:Ag};n&&s.updateJoinPayload(i),s.joinedOnce&&s._isJoined()&&s._push(He.access_token,{access_token:n})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(t="general"){this._isManualToken()||this.setAuth().catch(n=>{this.log("error",`Error setting auth in ${t}`,n)})}_triggerStateCallbacks(t,n){try{this.stateChangeCallbacks[t].forEach(r=>{try{r(n)}catch(s){this.log("error",`error in ${t} callback`,s)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}_setupReconnectionTimer(){this.reconnectTimer=new lh(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},ps.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(t){var n,r,s,i,o,a,l,u,c,p,h,m;switch(this.transport=(n=t==null?void 0:t.transport)!==null&&n!==void 0?n:null,this.timeout=(r=t==null?void 0:t.timeout)!==null&&r!==void 0?r:sa,this.heartbeatIntervalMs=(s=t==null?void 0:t.heartbeatIntervalMs)!==null&&s!==void 0?s:ps.HEARTBEAT_INTERVAL,this.worker=(i=t==null?void 0:t.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=t==null?void 0:t.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=t==null?void 0:t.heartbeatCallback)!==null&&a!==void 0?a:no,this.vsn=(l=t==null?void 0:t.vsn)!==null&&l!==void 0?l:xu,t!=null&&t.params&&(this.params=t.params),t!=null&&t.logger&&(this.logger=t.logger),(t!=null&&t.logLevel||t!=null&&t.log_level)&&(this.logLevel=t.logLevel||t.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(u=t==null?void 0:t.reconnectAfterMs)!==null&&u!==void 0?u:v=>Fg[v-1]||Wg,this.vsn){case Pg:this.encode=(c=t==null?void 0:t.encode)!==null&&c!==void 0?c:(v,y)=>y(JSON.stringify(v)),this.decode=(p=t==null?void 0:t.decode)!==null&&p!==void 0?p:(v,y)=>y(JSON.parse(v));break;case ah:this.encode=(h=t==null?void 0:t.encode)!==null&&h!==void 0?h:this.serializer.encode.bind(this.serializer),this.decode=(m=t==null?void 0:t.decode)!==null&&m!==void 0?m:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=t==null?void 0:t.workerUrl}}}var $r=class extends Error{constructor(e,t){var n;super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType==="CommitStateUnknownException"||[500,502,504].includes(t.status)&&((n=t.icebergType)==null?void 0:n.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function qg(e,t,n){const r=new URL(t,e);if(n)for(const[s,i]of Object.entries(n))i!==void 0&&r.searchParams.set(s,i);return r.toString()}async function Kg(e){return!e||e.type==="none"?{}:e.type==="bearer"?{Authorization:`Bearer ${e.token}`}:e.type==="header"?{[e.name]:e.value}:e.type==="custom"?await e.getHeaders():{}}function Gg(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:s,body:i,headers:o}){const a=qg(e.baseUrl,r,s),l=await Kg(e.auth),u=await t(a,{method:n,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),c=await u.text(),p=(u.headers.get("content-type")||"").includes("application/json"),h=p&&c?JSON.parse(c):c;if(!u.ok){const m=p?h:void 0,v=m==null?void 0:m.error;throw new $r((v==null?void 0:v.message)??`Request failed with status ${u.status}`,{status:u.status,icebergType:v==null?void 0:v.type,icebergCode:v==null?void 0:v.code,details:m})}return{status:u.status,headers:u.headers,data:h}}}}function gs(e){return e.join("")}var Jg=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:gs(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(r=>({namespace:r}))}async createNamespace(e,t){const n={namespace:e.namespace,properties:t==null?void 0:t.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${gs(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${gs(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${gs(e.namespace)}`}),!0}catch(t){if(t instanceof $r&&t.status===404)return!1;throw t}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(n){if(n instanceof $r&&n.status===409)return;throw n}}};function sn(e){return e.join("")}var Qg=class{constructor(e,t="",n){this.client=e,this.prefix=t,this.accessDelegation=n}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const n={};return this.accessDelegation&&(n["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables`,body:t,headers:n})).data.metadata}async updateTable(e,t){const n=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":n.data["metadata-location"],metadata:n.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String((t==null?void 0:t.purge)??!1)}})}async loadTable(e){const t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${sn(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(n){if(n instanceof $r&&n.status===404)return!1;throw n}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(n){if(n instanceof $r&&n.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw n}}},Yg=class{constructor(e){var r;let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const n=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=Gg({baseUrl:n,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=(r=e.accessDelegation)==null?void 0:r.join(","),this.namespaceOps=new Jg(this.client,t),this.tableOps=new Qg(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},Ei=class extends Error{constructor(e,t="storage",n,r){super(e),this.__isStorageError=!0,this.namespace=t,this.name=t==="vectors"?"StorageVectorsError":"StorageError",this.status=n,this.statusCode=r}};function Ti(e){return typeof e=="object"&&e!==null&&"__isStorageError"in e}var ms=class extends Ei{constructor(e,t,n,r="storage"){super(e,r,t,n),this.name=r==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},dh=class extends Ei{constructor(e,t,n="storage"){super(e,n),this.name=n==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};const Xg=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),Zg=e=>{if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},aa=e=>{if(Array.isArray(e))return e.map(n=>aa(n));if(typeof e=="function"||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([n,r])=>{const s=n.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[s]=aa(r)}),t},em=e=>!e||typeof e!="string"||e.length===0||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e);function Ur(e){"@babel/helpers - typeof";return Ur=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ur(e)}function tm(e,t){if(Ur(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Ur(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function nm(e){var t=tm(e,"string");return Ur(t)=="symbol"?t:t+""}function rm(e,t,n){return(t=nm(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ju(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function A(e){for(var t=1;t{var t;return e.msg||e.message||e.error_description||(typeof e.error=="string"?e.error:(t=e.error)===null||t===void 0?void 0:t.message)||JSON.stringify(e)},sm=async(e,t,n,r)=>{if(e&&typeof e=="object"&&"status"in e&&"ok"in e&&typeof e.status=="number"&&!(n!=null&&n.noResolveJson)){const s=e,i=s.status||500;if(typeof s.json=="function")s.json().then(o=>{const a=(o==null?void 0:o.statusCode)||(o==null?void 0:o.code)||i+"";t(new ms(Au(o),i,a,r))}).catch(()=>{if(r==="vectors"){const o=i+"";t(new ms(s.statusText||`HTTP ${i} error`,i,o,r))}else{const o=i+"";t(new ms(s.statusText||`HTTP ${i} error`,i,o,r))}});else{const o=i+"";t(new ms(s.statusText||`HTTP ${i} error`,i,o,r))}}else t(new dh(Au(e),e,r))},im=(e,t,n,r)=>{const s={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"||e==="HEAD"||!r?A(A({},s),n):(Zg(r)?(s.headers=A({"Content-Type":"application/json"},t==null?void 0:t.headers),s.body=JSON.stringify(r)):s.body=r,t!=null&&t.duplex&&(s.duplex=t.duplex),A(A({},s),n))};async function tr(e,t,n,r,s,i,o){return new Promise((a,l)=>{e(n,im(t,r,s,i)).then(u=>{if(!u.ok)throw u;if(r!=null&&r.noResolveJson)return u;if(o==="vectors"){const c=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!c||!c.includes("application/json"))return{}}return u.json()}).then(u=>a(u)).catch(u=>sm(u,l,r,o))})}function hh(e="storage"){return{get:async(t,n,r,s)=>tr(t,"GET",n,r,s,void 0,e),post:async(t,n,r,s,i)=>tr(t,"POST",n,s,i,r,e),put:async(t,n,r,s,i)=>tr(t,"PUT",n,s,i,r,e),head:async(t,n,r,s)=>tr(t,"HEAD",n,A(A({},r),{},{noResolveJson:!0}),s,void 0,e),remove:async(t,n,r,s,i)=>tr(t,"DELETE",n,s,i,r,e)}}const om=hh("storage"),{get:Dr,post:We,put:la,head:am,remove:ul}=om,xe=hh("vectors");var Vn=class{constructor(e,t={},n,r="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.fetch=Xg(n),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(n){if(t.shouldThrowOnError)throw n;if(Ti(n))return{data:null,error:n};throw n}}},lm=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ti(t))return{data:null,error:t};throw t}}};let fh;fh=Symbol.toStringTag;var um=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[fh]="BlobDownloadBuilder",this.promise=null}asStream(){return new lm(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Ti(t))return{data:null,error:t};throw t}}};const cm={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Pu={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var dm=class extends Vn{constructor(e,t={},n,r){super(e,t,r,"storage"),this.bucketId=n}async uploadOrUpdate(e,t,n,r){var s=this;return s.handleOperation(async()=>{let i;const o=A(A({},Pu),r);let a=A(A({},s.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",s.encodeMetadata(l)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(l))):(i=n,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=s.toBase64(s.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),r!=null&&r.headers&&(a=A(A({},a),r.headers));const u=s._removeEmptyFolders(t),c=s._getFinalPath(u),p=await(e=="PUT"?la:We)(s.fetch,`${s.url}/object/${c}`,i,A({headers:a},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{path:u,id:p.Id,fullPath:p.Key}})}async upload(e,t,n){return this.uploadOrUpdate("POST",e,t,n)}async uploadToSignedUrl(e,t,n,r){var s=this;const i=s._removeEmptyFolders(e),o=s._getFinalPath(i),a=new URL(s.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",t),s.handleOperation(async()=>{let l;const u=A({upsert:Pu.upsert},r),c=A(A({},s.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&n instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",n)):typeof FormData<"u"&&n instanceof FormData?(l=n,l.append("cacheControl",u.cacheControl)):(l=n,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType),{path:i,fullPath:(await la(s.fetch,a.toString(),l,{headers:c})).Key}})}async createSignedUploadUrl(e,t){var n=this;return n.handleOperation(async()=>{let r=n._getFinalPath(e);const s=A({},n.headers);t!=null&&t.upsert&&(s["x-upsert"]="true");const i=await We(n.fetch,`${n.url}/object/upload/sign/${r}`,{},{headers:s}),o=new URL(n.url+i.url),a=o.searchParams.get("token");if(!a)throw new Ei("No token returned by API");return{signedUrl:o.toString(),path:e,token:a}})}async update(e,t,n){return this.uploadOrUpdate("PUT",e,t,n)}async move(e,t,n){var r=this;return r.handleOperation(async()=>await We(r.fetch,`${r.url}/object/move`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:r.headers}))}async copy(e,t,n){var r=this;return r.handleOperation(async()=>({path:(await We(r.fetch,`${r.url}/object/copy`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:r.headers})).Key}))}async createSignedUrl(e,t,n){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(e),i=await We(r.fetch,`${r.url}/object/sign/${s}`,A({expiresIn:t},n!=null&&n.transform?{transform:n.transform}:{}),{headers:r.headers});const o=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{signedUrl:encodeURI(`${r.url}${i.signedURL}${o}`)}})}async createSignedUrls(e,t,n){var r=this;return r.handleOperation(async()=>{const s=await We(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:t,paths:e},{headers:r.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return s.map(o=>A(A({},o),{},{signedUrl:o.signedURL?encodeURI(`${r.url}${o.signedURL}${i}`):null}))})}download(e,t,n){const r=typeof(t==null?void 0:t.transform)<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),i=s?`?${s}`:"",o=this._getFinalPath(e),a=()=>Dr(this.fetch,`${this.url}/${r}/${o}${i}`,{headers:this.headers,noResolveJson:!0},n);return new um(a,this.shouldThrowOnError)}async info(e){var t=this;const n=t._getFinalPath(e);return t.handleOperation(async()=>aa(await Dr(t.fetch,`${t.url}/object/info/${n}`,{headers:t.headers})))}async exists(e){var t=this;const n=t._getFinalPath(e);try{return await am(t.fetch,`${t.url}/object/${n}`,{headers:t.headers}),{data:!0,error:null}}catch(r){if(t.shouldThrowOnError)throw r;if(Ti(r)&&r instanceof dh){const s=r.originalError;if([400,404].includes(s==null?void 0:s.status))return{data:!1,error:r}}throw r}}getPublicUrl(e,t){const n=this._getFinalPath(e),r=[],s=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";s!==""&&r.push(s);const i=typeof(t==null?void 0:t.transform)<"u"?"render/image":"object",o=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});o!==""&&r.push(o);let a=r.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${n}${a}`)}}}async remove(e){var t=this;return t.handleOperation(async()=>await ul(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,n){var r=this;return r.handleOperation(async()=>{const s=A(A(A({},cm),t),{},{prefix:e||""});return await We(r.fetch,`${r.url}/object/list/${r.bucketId}`,s,{headers:r.headers},n)})}async listV2(e,t){var n=this;return n.handleOperation(async()=>{const r=A({},e);return await We(n.fetch,`${n.url}/object/list-v2/${n.bucketId}`,r,{headers:n.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};const hm="2.95.3",Kr={"X-Client-Info":`storage-js/${hm}`};var fm=class extends Vn{constructor(e,t={},n,r){const s=new URL(e);r!=null&&r.useNewHostname&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase."));const i=s.href.replace(/\/$/,""),o=A(A({},Kr),t);super(i,o,n,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const n=t.listBucketOptionsToQueryString(e);return await Dr(t.fetch,`${t.url}/bucket${n}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await Dr(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var n=this;return n.handleOperation(async()=>await We(n.fetch,`${n.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async updateBucket(e,t){var n=this;return n.handleOperation(async()=>await la(n.fetch,`${n.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await We(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await ul(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},pm=class extends Vn{constructor(e,t={},n){const r=e.replace(/\/$/,""),s=A(A({},Kr),t);super(r,s,n,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await We(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const n=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&n.set("limit",e.limit.toString()),(e==null?void 0:e.offset)!==void 0&&n.set("offset",e.offset.toString()),e!=null&&e.sortColumn&&n.set("sortColumn",e.sortColumn),e!=null&&e.sortOrder&&n.set("sortOrder",e.sortOrder),e!=null&&e.search&&n.set("search",e.search);const r=n.toString(),s=r?`${t.url}/bucket?${r}`:`${t.url}/bucket`;return await Dr(t.fetch,s,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await ul(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!em(e))throw new Ei("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 n=new Yg({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),r=this.shouldThrowOnError;return new Proxy(n,{get(s,i){const o=s[i];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(s,a),error:null}}catch(l){if(r)throw l;return{data:null,error:l}}}}})}},gm=class extends Vn{constructor(e,t={},n){const r=e.replace(/\/$/,""),s=A(A({},Kr),{},{"Content-Type":"application/json"},t);super(r,s,n,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await xe.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var n=this;return n.handleOperation(async()=>await xe.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await xe.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var n=this;return n.handleOperation(async()=>await xe.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers})||{})}},mm=class extends Vn{constructor(e,t={},n){const r=e.replace(/\/$/,""),s=A(A({},Kr),{},{"Content-Type":"application/json"},t);super(r,s,n,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await xe.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await xe.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await xe.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await xe.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await xe.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},vm=class extends Vn{constructor(e,t={},n){const r=e.replace(/\/$/,""),s=A(A({},Kr),{},{"Content-Type":"application/json"},t);super(r,s,n,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await xe.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await xe.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await xe.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await xe.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},ym=class extends vm{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new wm(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,n=this;return t().call(n,e)}async getBucket(e){var t=()=>super.getBucket,n=this;return t().call(n,e)}async listBuckets(e={}){var t=()=>super.listBuckets,n=this;return t().call(n,e)}async deleteBucket(e){var t=()=>super.deleteBucket,n=this;return t().call(n,e)}},wm=class extends gm{constructor(e,t,n,r){super(e,t,r),this.vectorBucketName=n}async createIndex(e){var t=()=>super.createIndex,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,n=this;return t().call(n,n.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,n=this;return t().call(n,n.vectorBucketName,e)}index(e){return new _m(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},_m=class extends mm{constructor(e,t,n,r,s){super(e,t,s),this.vectorBucketName=n,this.indexName=r}async putVectors(e){var t=()=>super.putVectors,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(e){var t=()=>super.getVectors,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,n=this;return t().call(n,A(A({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},km=class extends fm{constructor(e,t={},n,r){super(e,t,n,r)}from(e){return new dm(this.url,this.headers,e,this.fetch)}get vectors(){return new ym(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new pm(this.url+"/iceberg",this.headers,this.fetch)}};const ph="2.95.3",hn=30*1e3,ua=3,ro=ua*hn,Sm="http://localhost:9999",Em="supabase.auth.token",Tm={"X-Client-Info":`gotrue-js/${ph}`},ca="X-Supabase-Api-Version",gh={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},bm=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,xm=10*60*1e3;class zr extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function R(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}class Cm extends zr{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function Om(e){return R(e)&&e.name==="AuthApiError"}class Wt extends zr{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class ht extends zr{constructor(t,n,r,s){super(t,r,s),this.name=n,this.status=r}}class Te extends ht{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function so(e){return R(e)&&e.name==="AuthSessionMissingError"}class on extends ht{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class vs extends ht{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class ys extends ht{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function Rm(e){return R(e)&&e.name==="AuthImplicitGrantRedirectError"}class Nu extends ht{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class jm extends ht{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 da extends ht{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function io(e){return R(e)&&e.name==="AuthRetryableFetchError"}class Iu extends ht{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class ha extends ht{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const ni="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Lu=` +\r=`.split(""),Am=(()=>{const e=new Array(128);for(let t=0;t=6;){const r=t.queue>>t.queuedBits-6&63;n(ni[r]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const r=t.queue>>t.queuedBits-6&63;n(ni[r]),t.queuedBits-=6}}function mh(e,t,n){const r=Am[e];if(r>-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}}function Uu(e){const t=[],n=o=>{t.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{Im(o,r,n)};for(let o=0;o>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function Nm(e,t){for(let n=0;n55295&&r<=56319){const s=(r-55296)*1024&65535;r=(e.charCodeAt(n+1)-56320&65535|s)+65536,n+=1}Pm(r,t)}}function Im(e,t,n){if(t.utf8seq===0){if(e<=127){n(e);return}for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|e&63,t.utf8seq-=1,t.utf8seq===0&&n(t.codepoint)}}function Nn(e){const t=[],n={queue:0,queuedBits:0},r=s=>{t.push(s)};for(let s=0;st.push(n)),new Uint8Array(t)}function Kt(e){const t=[],n={queue:0,queuedBits:0},r=s=>{t.push(s)};return e.forEach(s=>$u(s,n,r)),$u(null,n,r),t.join("")}function $m(e){return Math.round(Date.now()/1e3)+e}function Um(){return Symbol("auth-callback")}const ae=()=>typeof window<"u"&&typeof document<"u",Ut={tested:!1,writable:!1},vh=()=>{if(!ae())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ut.tested)return Ut.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Ut.tested=!0,Ut.writable=!0}catch{Ut.tested=!0,Ut.writable=!1}return Ut.writable};function Dm(e){const t={},n=new URL(e);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((s,i)=>{t[i]=s})}catch{}return n.searchParams.forEach((r,s)=>{t[s]=r}),t}const yh=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),zm=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",fn=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},Dt=async(e,t)=>{const n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},oe=async(e,t)=>{await e.removeItem(t)};class bi{constructor(){this.promise=new bi.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}bi.promiseConstructor=Promise;function ws(e){const t=e.split(".");if(t.length!==3)throw new ha("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),e)})}function Mm(e,t){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await e(i);if(!t(i,null,o)){r(o);return}}catch(o){if(!t(i,o)){s(o);return}}})()})}function Fm(e){return("0"+e.toString(16)).substr(-2)}function Wm(){const t=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let s="";for(let i=0;i<56;i++)s+=n.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(t),Array.from(t,Fm).join("")}async function Vm(e){const n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function Hm(e){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."),e;const n=await Vm(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function an(e,t,n=!1){const r=Wm();let s=r;n&&(s+="/PASSWORD_RECOVERY"),await fn(e,`${t}-code-verifier`,s);const i=await Hm(r);return[i,r===i?"plain":"s256"]}const qm=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Km(e){const t=e.headers.get(ca);if(!t||!t.match(qm))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function Gm(e){if(!e)throw new Error("Missing exp claim");const t=Math.floor(Date.now()/1e3);if(e<=t)throw new Error("JWT has expired")}function Jm(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const Qm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ln(e){if(!Qm.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function oo(){const e={};return new Proxy(e,{get:(t,n)=>{if(n==="__isUserNotAvailableProxy")return!0;if(typeof n=="symbol"){const r=n.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${n}" property of the session object is not supported. Please use getUser() instead.`)},set:(t,n)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${n}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(t,n)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${n}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Ym(e,t){return new Proxy(e,{get:(n,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){const i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(n,r,s)}return!t.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),t.value=!0),Reflect.get(n,r,s)}})}function Du(e){return JSON.parse(JSON.stringify(e))}const Mt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Xm=[502,503,504];async function zu(e){var t;if(!zm(e))throw new da(Mt(e),0);if(Xm.includes(e.status))throw new da(Mt(e),e.status);let n;try{n=await e.json()}catch(i){throw new Wt(Mt(i),i)}let r;const s=Km(e);if(s&&s.getTime()>=gh["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new Iu(Mt(n),e.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new Te}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Iu(Mt(n),e.status,n.weak_password.reasons);throw new Cm(Mt(n),e.status||500,r)}const Zm=(e,t,n,r)=>{const s={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),n))};async function j(e,t,n,r){var s;const i=Object.assign({},r==null?void 0:r.headers);i[ca]||(i[ca]=gh["2024-01-01"].name),r!=null&&r.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const o=(s=r==null?void 0:r.query)!==null&&s!==void 0?s:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await ev(e,t,n+a,{headers:i,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(l):{data:Object.assign({},l),error:null}}async function ev(e,t,n,r,s,i){const o=Zm(t,r,s,i);let a;try{a=await e(n,Object.assign({},o))}catch(l){throw console.error(l),new da(Mt(l),0)}if(a.ok||await zu(a),r!=null&&r.noResolveJson)return a;try{return await a.json()}catch(l){await zu(l)}}function Me(e){var t;let n=null;rv(e)&&(n=Object.assign({},e),e.expires_at||(n.expires_at=$m(e.expires_in)));const r=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:n,user:r},error:null}}function Bu(e){const t=Me(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(t.data.weak_password=e.weak_password),t}function wt(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function tv(e){return{data:e,error:null}}function nv(e){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:s,verification_type:i}=e,o=Si(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:t,email_otp:n,hashed_token:r,redirect_to:s,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Mu(e){return e}function rv(e){return e.access_token&&e.refresh_token&&e.expires_in}const ao=["global","local","others"];class sv{constructor({url:t="",headers:n={},fetch:r}){this.url=t,this.headers=n,this.fetch=yh(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(t,n=ao[0]){if(ao.indexOf(n)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ao.join(", ")}`);try{return await j(this.fetch,"POST",`${this.url}/logout?scope=${n}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(r){if(R(r))return{data:null,error:r};throw r}}async inviteUserByEmail(t,n={}){try{return await j(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:wt})}catch(r){if(R(r))return{data:{user:null},error:r};throw r}}async generateLink(t){try{const{options:n}=t,r=Si(t,["options"]),s=Object.assign(Object.assign({},r),n);return"newEmail"in r&&(s.new_email=r==null?void 0:r.newEmail,delete s.newEmail),await j(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:nv,redirectTo:n==null?void 0:n.redirectTo})}catch(n){if(R(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(t){try{return await j(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:wt})}catch(n){if(R(n))return{data:{user:null},error:n};throw n}}async listUsers(t){var n,r,s,i,o,a,l;try{const u={nextPage:null,lastPage:0,total:0},c=await j(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=t==null?void 0:t.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Mu});if(c.error)throw c.error;const p=await c.json(),h=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(v=>{const y=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),k=JSON.parse(v.split(";")[1].split("=")[1]);u[`${k}Page`]=y}),u.total=parseInt(h)),{data:Object.assign(Object.assign({},p),u),error:null}}catch(u){if(R(u))return{data:{users:[]},error:u};throw u}}async getUserById(t){ln(t);try{return await j(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:wt})}catch(n){if(R(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){ln(t);try{return await j(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:wt})}catch(r){if(R(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){ln(t);try{return await j(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:wt})}catch(r){if(R(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){ln(t.userId);try{const{data:n,error:r}=await j(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:n,error:r}}catch(n){if(R(n))return{data:null,error:n};throw n}}async _deleteFactor(t){ln(t.userId),ln(t.id);try{return{data:await j(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(R(n))return{data:null,error:n};throw n}}async _listOAuthClients(t){var n,r,s,i,o,a,l;try{const u={nextPage:null,lastPage:0,total:0},c=await j(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(i=(s=t==null?void 0:t.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Mu});if(c.error)throw c.error;const p=await c.json(),h=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(v=>{const y=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),k=JSON.parse(v.split(";")[1].split("=")[1]);u[`${k}Page`]=y}),u.total=parseInt(h)),{data:Object.assign(Object.assign({},p),u),error:null}}catch(u){if(R(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(t){try{return await j(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:t,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(R(n))return{data:null,error:n};throw n}}async _getOAuthClient(t){try{return await j(this.fetch,"GET",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(R(n))return{data:null,error:n};throw n}}async _updateOAuthClient(t,n){try{return await j(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${t}`,{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(R(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(t){try{return await j(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(R(n))return{data:null,error:n};throw n}}async _regenerateOAuthClientSecret(t){try{return await j(this.fetch,"POST",`${this.url}/admin/oauth/clients/${t}/regenerate_secret`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(R(n))return{data:null,error:n};throw n}}}function Fu(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}const un={debug:!!(globalThis&&vh()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class wh extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class iv extends wh{}async function ov(e,t,n){un.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),un.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async s=>{if(s){un.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await n()}finally{un.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}else{if(t===0)throw un.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new iv(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(un.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await n()}}))}function av(){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 _h(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function lv(e){return parseInt(e,16)}function uv(e){const t=new TextEncoder().encode(e);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function cv(e){var t;const{chainId:n,domain:r,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:u,scheme:c,uri:p,version:h}=e;{if(!Number.isInteger(n))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${n}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!p)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(h!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);if(!((t=e.statement)===null||t===void 0)&&t.includes(` +`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`)}const m=_h(e.address),v=c?`${c}://${r}`:r,y=e.statement?`${e.statement} +`:"",k=`${v} wants you to sign in with your Ethereum account: ${m} -${w}`;let f=`URI: ${p} +${y}`;let f=`URI: ${p} Version: ${h} Chain ID: ${n}${o?` Nonce: ${o}`:""} @@ -117,6 +107,6 @@ Expiration Time: ${s.toISOString()}`),a&&(f+=` Not Before: ${a.toISOString()}`),l&&(f+=` Request ID: ${l}`),u){let d=` Resources:`;for(const g of u){if(!g||typeof g!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${g}`);d+=` -- ${g}`}f+=d}return`${S} -${f}`}class X extends Error{constructor({message:t,code:n,cause:r,name:s}){var i;super(t,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=n}}class si extends X{constructor(t,n){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n,message:t}),this.name="WebAuthnUnknownError",this.originalError=n}}function mv({error:e,options:t}){var n,r,s;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new X({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.requireResidentKey)===!0)return new X({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new X({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new X({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if(e.name==="InvalidStateError")return new X({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new X({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new X({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new X({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){const o=window.location.hostname;if(Sh(o)){if(i.rp.id!==o)return new X({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new X({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new X({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new X({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new X({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function vv({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new X({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if(e.name==="NotAllowedError")return new X({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){const r=window.location.hostname;if(Sh(r)){if(n.rpId!==r)return new X({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new X({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new X({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new X({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}class yv{createNewAbortSignal(){if(this.controller){const n=new Error("Cancelling existing WebAuthn API call for new one");n.name="AbortError",this.controller.abort(n)}const t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){const t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}}const wv=new yv;function _v(e){if(!e)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:n,excludeCredentials:r}=e,s=ki(e,["challenge","user","excludeCredentials"]),i=Nn(t).buffer,o=Object.assign(Object.assign({},n),{id:Nn(n.id).buffer}),a=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){a.excludeCredentials=new Array(r.length);for(let l=0;l0){i.allowCredentials=new Array(n.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),n=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(const s of e)if(s)for(const i in s){const o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(n(o))r[i]=o;else if(t(o)){const a=r[i];t(a)?r[i]=ii(a,o):r[i]=ii(o)}else r[i]=o}return r}function Ov(e,t){return ii(bv,e,t||{})}function jv(e,t){return ii(Cv,e,t||{})}class Rv{constructor(t){this.client=t,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(t){return this.client.mfa.enroll(Object.assign(Object.assign({},t),{factorType:"webauthn"}))}async _challenge({factorId:t,webauthn:n,friendlyName:r,signal:s},i){var o;try{const{data:a,error:l}=await this.client.mfa.challenge({factorId:t,webauthn:n});if(!a)return{data:null,error:l};const u=s??wv.createNewAbortSignal();if(a.webauthn.type==="create"){const{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){const p=r;if(p)c.name=`${c.id}:${p}`;else{const m=(await this.client.getUser()).data.user,y=((o=m==null?void 0:m.user_metadata)===null||o===void 0?void 0:o.name)||(m==null?void 0:m.email)||(m==null?void 0:m.id)||"User";c.name=`${c.id}:${y}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{const c=Ov(a.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:p,error:h}=await xv({publicKey:c,signal:u});return p?{data:{factorId:t,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:p}},error:null}:{data:null,error:h}}case"request":{const c=jv(a.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:p,error:h}=await Tv(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));return p?{data:{factorId:t,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:p}},error:null}:{data:null,error:h}}}}catch(a){return j(a)?{data:null,error:a}:{data:null,error:new Wt("Unexpected error in challenge",a)}}}async _verify({challengeId:t,factorId:n,webauthn:r}){return this.client.mfa.verify({factorId:n,challengeId:t,webauthn:r})}async _authenticate({factorId:t,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!n)return{data:null,error:new Mr("rpId is required for WebAuthn authentication")};try{if(!Fu())return{data:null,error:new Wt("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this.challenge({factorId:t,webauthn:{rpId:n,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:a};const{webauthn:l}=o;return this._verify({factorId:t,challengeId:o.challengeId,webauthn:{type:l.type,rpId:n,rpOrigins:r,credential_response:l.credential_response}})}catch(o){return j(o)?{data:null,error:o}:{data:null,error:new Wt("Unexpected error in authenticate",o)}}}async _register({friendlyName:t,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!n)return{data:null,error:new Mr("rpId is required for WebAuthn registration")};try{if(!Fu())return{data:null,error:new Wt("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this._enroll({friendlyName:t});if(!o)return await this.client.mfa.listFactors().then(c=>{var p;return(p=c.data)===null||p===void 0?void 0:p.all.find(h=>h.factor_type==="webauthn"&&h.friendly_name===t&&h.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c==null?void 0:c.id}):void 0),{data:null,error:a};const{data:l,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:n,rpOrigins:r},signal:s},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:n,rpOrigins:r,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(o){return j(o)?{data:null,error:o}:{data:null,error:new Wt("Unexpected error in register",o)}}}}hv();const Pv={url:Cm,storageKey:Om,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:jm,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function Wu(e,t,n){return await n()}const cn={};class Br{get jwks(){var t,n;return(n=(t=cn[this.storageKey])===null||t===void 0?void 0:t.jwks)!==null&&n!==void 0?n:{keys:[]}}set jwks(t){cn[this.storageKey]=Object.assign(Object.assign({},cn[this.storageKey]),{jwks:t})}get jwks_cached_at(){var t,n;return(n=(t=cn[this.storageKey])===null||t===void 0?void 0:t.cachedAt)!==null&&n!==void 0?n:Number.MIN_SAFE_INTEGER}set jwks_cached_at(t){cn[this.storageKey]=Object.assign(Object.assign({},cn[this.storageKey]),{cachedAt:t})}constructor(t){var n,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},Pv),t);if(this.storageKey=i.storageKey,this.instanceID=(n=Br.nextInstanceID[this.storageKey])!==null&&n!==void 0?n:0,Br.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&ae()){const o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new uv({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=yh(i.fetch),this.lock=i.lock||Wu,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&ae()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=dv:this.lock=Wu,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 Rv(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.persistSession?(i.storage?this.storage=i.storage:vh()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Bu(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Bu(this.memoryStorage)),ae()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(t){if(this.throwOnError&&t&&t.error)throw t.error;return t}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ph}) ${new Date().toISOString()}`}_debug(...t){return this.logDebugMessages&&this.logger(this._logPrefix(),...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var t;try{let n={},r="none";if(ae()&&(n=Wm(window.location.href),this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce")),ae()&&this.detectSessionInUrl&&r!=="none"){const{data:s,error:i}=await this._getSessionFromURL(n,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Im(i)){const l=(t=i.details)===null||t===void 0?void 0:t.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:o,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(n){return j(n)?this._returnResult({error:n}):this._returnResult({error:new Wt("Unexpected error during initialization",n)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,s;try{const i=await R(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=t==null?void 0:t.options)===null||s===void 0?void 0:s.captchaToken}},xform:Be}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});const l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(j(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(t){var n,r,s;try{let i;if("email"in t){const{email:c,password:p,options:h}=t;let m=null,y=null;this.flowType==="pkce"&&([m,y]=await an(this.storage,this.storageKey)),i=await R(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h==null?void 0:h.emailRedirectTo,body:{email:c,password:p,data:(n=h==null?void 0:h.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken},code_challenge:m,code_challenge_method:y},xform:Be})}else if("phone"in t){const{phone:c,password:p,options:h}=t;i=await R(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:p,data:(r=h==null?void 0:h.data)!==null&&r!==void 0?r:{},channel:(s=h==null?void 0:h.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:Be})}else throw new ys("You must provide either an email or phone number and a password");const{data:o,error:a}=i;if(a||!o)return await oe(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});const l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(await oe(this.storage,`${this.storageKey}-code-verifier`),j(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(t){try{let n;if("email"in t){const{email:i,password:o,options:a}=t;n=await R(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:zu})}else if("phone"in t){const{phone:i,password:o,options:a}=t;n=await R(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:zu})}else throw new ys("You must provide either an email or phone number and a password");const{data:r,error:s}=n;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){const i=new on;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(n){if(j(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOAuth(t){var n,r,s,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=t.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(t))}async signInWithWeb3(t){const{chain:n}=t;switch(n){case"ethereum":return await this.signInWithEthereum(t);case"solana":return await this.signInWithSolana(t);default:throw new Error(`@supabase/auth-js: Unsupported chain "${n}"`)}}async signInWithEthereum(t){var n,r,s,i,o,a,l,u,c,p,h;let m,y;if("message"in t)m=t.message,y=t.signature;else{const{chain:w,wallet:S,statement:f,options:d}=t;let g;if(ae())if(typeof S=="object")g=S;else{const U=window;if("ethereum"in U&&typeof U.ethereum=="object"&&"request"in U.ethereum&&typeof U.ethereum.request=="function")g=U.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 S!="object"||!(d!=null&&d.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");g=S}const _=new URL((n=d==null?void 0:d.url)!==null&&n!==void 0?n:window.location.href),E=await g.request({method:"eth_requestAccounts"}).then(U=>U).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!E||E.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const x=_h(E[0]);let T=(r=d==null?void 0:d.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!T){const U=await g.request({method:"eth_chainId"});T=fv(U)}const O={domain:_.host,address:x,statement:f,uri:_.href,version:"1",chainId:T,nonce:(s=d==null?void 0:d.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=d==null?void 0:d.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=d==null?void 0:d.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=d==null?void 0:d.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=d==null?void 0:d.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=d==null?void 0:d.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=gv(O),y=await g.request({method:"personal_sign",params:[pv(m),x]})}try{const{data:w,error:S}=await R(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:y},!((p=t.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(h=t.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:Be});if(S)throw S;if(!w||!w.session||!w.user){const f=new on;return this._returnResult({data:{user:null,session:null},error:f})}return w.session&&(await this._saveSession(w.session),await this._notifyAllSubscribers("SIGNED_IN",w.session)),this._returnResult({data:Object.assign({},w),error:S})}catch(w){if(j(w))return this._returnResult({data:{user:null,session:null},error:w});throw w}}async signInWithSolana(t){var n,r,s,i,o,a,l,u,c,p,h,m;let y,w;if("message"in t)y=t.message,w=t.signature;else{const{chain:S,wallet:f,statement:d,options:g}=t;let _;if(ae())if(typeof f=="object")_=f;else{const x=window;if("solana"in x&&typeof x.solana=="object"&&("signIn"in x.solana&&typeof x.solana.signIn=="function"||"signMessage"in x.solana&&typeof x.solana.signMessage=="function"))_=x.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 f!="object"||!(g!=null&&g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=f}const E=new URL((n=g==null?void 0:g.url)!==null&&n!==void 0?n:window.location.href);if("signIn"in _&&_.signIn){const x=await _.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},g==null?void 0:g.signInWithSolana),{version:"1",domain:E.host,uri:E.href}),d?{statement:d}:null));let T;if(Array.isArray(x)&&x[0]&&typeof x[0]=="object")T=x[0];else if(x&&typeof x=="object"&&"signedMessage"in x&&"signature"in x)T=x;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in T&&"signature"in T&&(typeof T.signedMessage=="string"||T.signedMessage instanceof Uint8Array)&&T.signature instanceof Uint8Array)y=typeof T.signedMessage=="string"?T.signedMessage:new TextDecoder().decode(T.signedMessage),w=T.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in _)||typeof _.signMessage!="function"||!("publicKey"in _)||typeof _!="object"||!_.publicKey||!("toBase58"in _.publicKey)||typeof _.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${E.host} wants you to sign in with your Solana account:`,_.publicKey.toBase58(),...d?["",d,""]:[""],"Version: 1",`URI: ${E.href}`,`Issued At: ${(s=(r=g==null?void 0:g.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=g==null?void 0:g.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${g.signInWithSolana.notBefore}`]:[],...!((o=g==null?void 0:g.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${g.signInWithSolana.expirationTime}`]:[],...!((a=g==null?void 0:g.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${g.signInWithSolana.chainId}`]:[],...!((l=g==null?void 0:g.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${g.signInWithSolana.nonce}`]:[],...!((u=g==null?void 0:g.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${g.signInWithSolana.requestId}`]:[],...!((p=(c=g==null?void 0:g.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||p===void 0)&&p.length?["Resources",...g.signInWithSolana.resources.map(T=>`- ${T}`)]:[]].join(` -`);const x=await _.signMessage(new TextEncoder().encode(y),"utf8");if(!x||!(x instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");w=x}}try{const{data:S,error:f}=await R(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:Kt(w)},!((h=t.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(m=t.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Be});if(f)throw f;if(!S||!S.session||!S.user){const d=new on;return this._returnResult({data:{user:null,session:null},error:d})}return S.session&&(await this._saveSession(S.session),await this._notifyAllSubscribers("SIGNED_IN",S.session)),this._returnResult({data:Object.assign({},S),error:f})}catch(S){if(j(S))return this._returnResult({data:{user:null,session:null},error:S});throw S}}async _exchangeCodeForSession(t){const n=await Dt(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(n??"").split("/");try{if(!r&&this.flowType==="pkce")throw new Lm;const{data:i,error:o}=await R(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:Be});if(await oe(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){const a=new on;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s??null}),error:o})}catch(i){if(await oe(this.storage,`${this.storageKey}-code-verifier`),j(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(t){try{const{options:n,provider:r,token:s,access_token:i,nonce:o}=t,a=await R(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:Be}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){const c=new on;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(n){if(j(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOtp(t){var n,r,s,i,o;try{if("email"in t){const{email:a,options:l}=t;let u=null,c=null;this.flowType==="pkce"&&([u,c]=await an(this.storage,this.storageKey));const{error:p}=await R(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(n=l==null?void 0:l.data)!==null&&n!==void 0?n:{},create_user:(r=l==null?void 0:l.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:p})}if("phone"in t){const{phone:a,options:l}=t,{data:u,error:c}=await R(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l==null?void 0:l.data)!==null&&s!==void 0?s:{},create_user:(i=l==null?void 0:l.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(o=l==null?void 0:l.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:c})}throw new ys("You must provide either an email or phone number.")}catch(a){if(await oe(this.storage,`${this.storageKey}-code-verifier`),j(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(t){var n,r;try{let s,i;"options"in t&&(s=(n=t.options)===null||n===void 0?void 0:n.redirectTo,i=(r=t.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:a}=await R(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Be});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,u=o.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(j(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(t){var n,r,s,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await an(this.storage,this.storageKey));const u=await R(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(r=(n=t.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r:void 0}),!((s=t==null?void 0:t.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:ov});return!((i=u.data)===null||i===void 0)&&i.url&&ae()&&!(!((o=t.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(await oe(this.storage,`${this.storageKey}-code-verifier`),j(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;if(r)throw r;if(!n)throw new xe;const{error:s}=await R(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(t){if(j(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async resend(t){try{const n=`${this.url}/resend`;if("email"in t){const{email:r,type:s,options:i}=t,{error:o}=await R(this.fetch,"POST",n,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in t){const{phone:r,type:s,options:i}=t,{data:o,error:a}=await R(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:a})}throw new ys("You must provide either an email or phone number and a type")}catch(n){if(j(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async n=>n))}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await t(n)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null;const n=await Dt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const r=t.expires_at?t.expires_at*1e3-Date.now()await this._getUser());return n.data.user&&(this.suppressGetSessionWarning=!0),n}async _getUser(t){try{return t?await R(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:wt}):await this._useSession(async n=>{var r,s,i;const{data:o,error:a}=n;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new xe}:await R(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:wt})})}catch(n){if(j(n))return so(n)&&(await this._removeSession(),await oe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:n});throw n}}async updateUser(t,n={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(t,n))}async _updateUser(t,n={}){try{return await this._useSession(async r=>{const{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new xe;const o=s.session;let a=null,l=null;this.flowType==="pkce"&&t.email!=null&&([a,l]=await an(this.storage,this.storageKey));const{data:u,error:c}=await R(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:wt});if(c)throw c;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(r){if(await oe(this.storage,`${this.storageKey}-code-verifier`),j(r))return this._returnResult({data:{user:null},error:r});throw r}}async setSession(t){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new xe;const n=Date.now()/1e3;let r=n,s=!0,i=null;const{payload:o}=_s(t.access_token);if(o.exp&&(r=o.exp,s=r<=n),s){const{data:a,error:l}=await this._callRefreshToken(t.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};i=a}else{const{data:a,error:l}=await this._getUser(t.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:t.access_token,refresh_token:t.refresh_token,user:a.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(n){if(j(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async n=>{var r;if(!t){const{data:o,error:a}=n;if(a)throw a;t=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(t!=null&&t.refresh_token))throw new xe;const{data:s,error:i}=await this._callRefreshToken(t.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(n){if(j(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async _getSessionFromURL(t,n){try{if(!ae())throw new ws("No browser detected.");if(t.error||t.error_description||t.error_code)throw new ws(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(n){case"implicit":if(this.flowType==="pkce")throw new Au("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ws("Not a valid implicit grant flow url.");break;default:}if(n==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new Au("No code detected.");const{data:d,error:g}=await this._exchangeCodeForSession(t.code);if(g)throw g;const _=new URL(window.location.href);return _.searchParams.delete("code"),window.history.replaceState(window.history.state,"",_.toString()),{data:{session:d.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:s,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:u}=t;if(!i||!a||!o||!u)throw new ws("No session defined in URL");const c=Math.round(Date.now()/1e3),p=parseInt(a);let h=c+p;l&&(h=parseInt(l));const m=h-c;m*1e3<=hn&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${p}s`);const y=h-p;c-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,h,c):c-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,h,c);const{data:w,error:S}=await this._getUser(i);if(S)throw S;const f={provider_token:r,provider_refresh_token:s,access_token:i,expires_in:p,expires_at:h,refresh_token:o,token_type:u,user:w.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:f,redirectType:t.type},error:null})}catch(r){if(j(r))return this._returnResult({data:{session:null,redirectType:null},error:r});throw r}}_isImplicitGrantCallback(t){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),t):!!(t.access_token||t.error_description)}async _isPKCECallback(t){const n=await Dt(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&n)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async n=>{var r;const{data:s,error:i}=n;if(i&&!so(i))return this._returnResult({error:i});const o=(r=s.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:a}=await this.admin.signOut(o,t);if(a&&!(Nm(a)&&(a.status===404||a.status===401||a.status===403)||so(a)))return this._returnResult({error:a})}return t!=="others"&&(await this._removeSession(),await oe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(t){const n=Fm(),r={id:n,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,r),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async n=>{var r,s;try{const{data:{session:i},error:o}=n;if(o)throw o;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(t))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),console.error(i)}})}async resetPasswordForEmail(t,n={}){let r=null,s=null;this.flowType==="pkce"&&([r,s]=await an(this.storage,this.storageKey,!0));try{return await R(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(i){if(await oe(this.storage,`${this.storageKey}-code-verifier`),j(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var t;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null})}catch(n){if(j(n))return this._returnResult({data:null,error:n});throw n}}async linkIdentity(t){return"token"in t?this.linkIdentityIdToken(t):this.linkIdentityOAuth(t)}async linkIdentityOAuth(t){var n;try{const{data:r,error:s}=await this._useSession(async i=>{var o,a,l,u,c;const{data:p,error:h}=i;if(h)throw h;const m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(o=t.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=t.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=t.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await R(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=p.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(s)throw s;return ae()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),this._returnResult({data:{provider:t.provider,url:r==null?void 0:r.url},error:null})}catch(r){if(j(r))return this._returnResult({data:{provider:t.provider,url:null},error:r});throw r}}async linkIdentityIdToken(t){return await this._useSession(async n=>{var r;try{const{error:s,data:{session:i}}=n;if(s)throw s;const{options:o,provider:a,token:l,access_token:u,nonce:c}=t,p=await R(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i==null?void 0:i.access_token)!==null&&r!==void 0?r:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Be}),{data:h,error:m}=p;return m?this._returnResult({data:{user:null,session:null},error:m}):!h||!h.session||!h.user?this._returnResult({data:{user:null,session:null},error:new on}):(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:m}))}catch(s){if(await oe(this.storage,`${this.storageKey}-code-verifier`),j(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(t){try{return await this._useSession(async n=>{var r,s;const{data:i,error:o}=n;if(o)throw o;return await R(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(n){if(j(n))return this._returnResult({data:null,error:n});throw n}}async _refreshAccessToken(t){const n=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(n,"begin");try{const r=Date.now();return await qm(async s=>(s>0&&await Hm(200*Math.pow(2,s-1)),this._debug(n,"refreshing attempt",s),await R(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:Be})),(s,i)=>{const o=200*Math.pow(2,s);return i&&io(i)&&Date.now()+o-r{try{await a.callback(t,n)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;athis._autoRefreshTokenTick(),hn);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t);const n=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=n,n&&typeof n=="object"&&typeof n.unref=="function"?n.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(n)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t);const n=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,n&&clearTimeout(n)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const s=Math.floor((r.expires_at*1e3-t)/hn);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${hn}ms, refresh threshold is ${ua} ticks`),s<=ua&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof wh)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!ae()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(t){this._debug("#visibilityChangedCallback","error",t)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const n=`#_onVisibilityChanged(${t})`;this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(n,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,n,r){const s=[`provider=${encodeURIComponent(n)}`];if(r!=null&&r.redirectTo&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[i,o]=await an(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(r!=null&&r.queryParams){const i=new URLSearchParams(r.queryParams);s.push(i.toString())}return r!=null&&r.skipBrowserRedirect&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${t}?${s.join("&")}`}async _unenroll(t){try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;return i?this._returnResult({data:null,error:i}):await R(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(j(n))return this._returnResult({data:null,error:n});throw n}}async _enroll(t){try{return await this._useSession(async n=>{var r,s;const{data:i,error:o}=n;if(o)return this._returnResult({data:null,error:o});const a=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:t.factorType==="totp"?{issuer:t.issuer}:{}),{data:l,error:u}=await R(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(t.factorType==="totp"&&l.type==="totp"&&(!((s=l==null?void 0:l.totp)===null||s===void 0)&&s.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(n){if(j(n))return this._returnResult({data:null,error:n});throw n}}async _verify(t){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({challenge_id:t.challengeId},"webauthn"in t?{webauthn:Object.assign(Object.assign({},t.webauthn),{credential_response:t.webauthn.type==="create"?kv(t.webauthn.credential_response):Ev(t.webauthn.credential_response)})}:{code:t.code}),{data:a,error:l}=await R(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:o,headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(n){if(j(n))return this._returnResult({data:null,error:n});throw n}})}async _challenge(t){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;if(i)return this._returnResult({data:null,error:i});const o=await R(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:t,headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});if(o.error)return o;const{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:_v(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Sv(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(n){if(j(n))return this._returnResult({data:null,error:n});throw n}})}async _challengeAndVerify(t){const{data:n,error:r}=await this._challenge({factorId:t.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){var t;const{data:{user:n},error:r}=await this.getUser();if(r)return{data:null,error:r};const s={all:[],phone:[],totp:[],webauthn:[]};for(const i of(t=n==null?void 0:n.factors)!==null&&t!==void 0?t:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(t){var n,r,s,i;if(t)try{const{payload:m}=_s(t);let y=null;m.aal&&(y=m.aal);let w=y;const{data:{user:S},error:f}=await this.getUser(t);if(f)return this._returnResult({data:null,error:f});((r=(n=S==null?void 0:S.factors)===null||n===void 0?void 0:n.filter(_=>_.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(w="aal2");const g=m.amr||[];return{data:{currentLevel:y,nextLevel:w,currentAuthenticationMethods:g},error:null}}catch(m){if(j(m))return this._returnResult({data:null,error:m});throw m}const{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=_s(o.access_token);let u=null;l.aal&&(u=l.aal);let c=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(m=>m.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(c="aal2");const h=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:h},error:null}}async _getAuthorizationDetails(t){try{return await this._useSession(async n=>{const{data:{session:r},error:s}=n;return s?this._returnResult({data:null,error:s}):r?await R(this.fetch,"GET",`${this.url}/oauth/authorizations/${t}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new xe})})}catch(n){if(j(n))return this._returnResult({data:null,error:n});throw n}}async _approveAuthorization(t,n){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new xe});const o=await R(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&ae()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(j(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(t,n){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new xe});const o=await R(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&ae()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(j(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?await R(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new xe})})}catch(t){if(j(t))return this._returnResult({data:null,error:t});throw t}}async _revokeOAuthGrant(t){try{return await this._useSession(async n=>{const{data:{session:r},error:s}=n;return s?this._returnResult({data:null,error:s}):r?(await R(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:t.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new xe})})}catch(n){if(j(n))return this._returnResult({data:null,error:n});throw n}}async fetchJwk(t,n={keys:[]}){let r=n.keys.find(a=>a.kid===t);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(a=>a.kid===t),r&&this.jwks_cached_at+Pm>s)return r;const{data:i,error:o}=await R(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(a=>a.kid===t),!r)?null:r}async getClaims(t,n={}){try{let r=t;if(!r){const{data:m,error:y}=await this.getSession();if(y||!m.session)return this._returnResult({data:null,error:y});r=m.session.access_token}const{header:s,payload:i,signature:o,raw:{header:a,payload:l}}=_s(r);n!=null&&n.allowExpired||Zm(i.exp);const u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,n!=null&&n.keys?{keys:n.keys}:n==null?void 0:n.jwks);if(!u){const{error:m}=await this.getUser(r);if(m)throw m;return{data:{claims:i,header:s,signature:o},error:null}}const c=ev(s.alg),p=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,p,o,Mm(`${a}.${l}`)))throw new ha("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(j(r))return this._returnResult({data:null,error:r});throw r}}}Br.nextInstanceID={};const Av=Br,Nv="2.95.3";let ar="";typeof Deno<"u"?ar="deno":typeof document<"u"?ar="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ar="react-native":ar="node";const Iv={"X-Client-Info":`supabase-js-${ar}/${Nv}`},Lv={headers:Iv},$v={schema:"public"},Uv={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Dv={};function Fr(e){"@babel/helpers - typeof";return Fr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fr(e)}function zv(e,t){if(Fr(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Fr(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Mv(e){var t=zv(e,"string");return Fr(t)=="symbol"?t:t+""}function Bv(e,t,n){return(t=Mv(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Vu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function G(e){for(var t=1;te?(...t)=>e(...t):(...t)=>fetch(...t),Wv=()=>Headers,Vv=(e,t,n)=>{const r=Fv(n),s=Wv();return async(i,o)=>{var a;const l=(a=await t())!==null&&a!==void 0?a:e;let u=new s(o==null?void 0:o.headers);return u.has("apikey")||u.set("apikey",e),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),r(i,G(G({},o),{},{headers:u}))}};function Hv(e){return e.endsWith("/")?e:e+"/"}function qv(e,t){var n,r;const{db:s,auth:i,realtime:o,global:a}=e,{db:l,auth:u,realtime:c,global:p}=t,h={db:G(G({},l),s),auth:G(G({},u),i),realtime:G(G({},c),o),storage:{},global:G(G(G({},p),a),{},{headers:G(G({},(n=p==null?void 0:p.headers)!==null&&n!==void 0?n:{}),(r=a==null?void 0:a.headers)!==null&&r!==void 0?r:{})}),accessToken:async()=>""};return e.accessToken?h.accessToken=e.accessToken:delete h.accessToken,h}function Kv(e){const t=e==null?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Hv(t))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Gv=class extends Av{constructor(e){super(e)}},Jv=class{constructor(e,t,n){var r,s;this.supabaseUrl=e,this.supabaseKey=t;const i=Kv(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const o=`sb-${i.hostname.split(".")[0]}-auth-token`,a={db:$v,realtime:Dv,auth:G(G({},Uv),{},{storageKey:o}),global:Lv},l=qv(n??{},a);if(this.storageKey=(r=l.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(s=l.global.headers)!==null&&s!==void 0?s:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=Vv(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(G({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(c=>this.realtime.setAuth(c)).catch(c=>console.warn("Failed to set initial Realtime auth token:",c)),this.rest=new Ng(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new bm(this.storageUrl.href,this.headers,this.fetch,n==null?void 0:n.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new Tg(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e=this,t,n;if(e.accessToken)return await e.accessToken();const{data:r}=await e.auth.getSession();return(t=(n=r.session)===null||n===void 0?void 0:n.access_token)!==null&&t!==void 0?t:e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:s,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:u},c,p){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Gv({url:this.authUrl.href,headers:G(G({},h),c),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:s,flowType:o,lock:a,debug:l,throwOnError:u,fetch:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new Qg(this.realtimeUrl.href,G(G({},e),{},{params:G(G({},{apikey:this.supabaseKey}),e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",t==null?void 0:t.access_token)})}_handleTokenChanged(e,t,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const Qv=(e,t,n)=>new Jv(e,t,n);function Yv(){if(typeof window<"u")return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(t==null)return!1;const n=t.match(/^v(\d+)\./);return n?parseInt(n[1],10)<=18:!1}Yv()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const kh="https://tnurlgbvfsxwqgwxamni.supabase.co",Xv="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InRudXJsZ2J2ZnN4d3Fnd3hhbW5pIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDQ5MTQ1OTksImV4cCI6MjA2MDQ5MDU5OX0.9__EQiZDJ954SmeeJIDTQjOYDjiiRcppai1e8UpuOl4";console.log("Initializing Supabase client with URL:",kh);const $e=Qv(kh,Xv,{db:{schema:"public"}});console.log("Supabase client initialized for schema: openclaw");function Zv(){const[e,t]=z.useState([]),[n,r]=z.useState(!0);return z.useEffect(()=>{(async()=>{console.log("Fetching tasks...");const{data:o,error:a}=await $e.from("agent_tasks").select("*").order("updated_at",{ascending:!1});a&&console.error("Error fetching tasks:",a),o&&(console.log("Tasks fetched:",o.length),t(o)),r(!1)})();const i=$e.channel("tasks-changes").on("postgres_changes",{event:"*",schema:"public",table:"agent_tasks"},o=>{o.eventType==="INSERT"?t(a=>[o.new,...a]):o.eventType==="UPDATE"?t(a=>a.map(l=>l.id===o.new.id?o.new:l)):o.eventType==="DELETE"&&t(a=>a.filter(l=>l.id===o.old.id))}).subscribe();return()=>{$e.removeChannel(i)}},[]),{tasks:e,loading:n}}function ey(e=20){const[t,n]=z.useState([]),[r,s]=z.useState(!0);return z.useEffect(()=>{(async()=>{console.log("Fetching logs...");const{data:a,error:l}=await $e.from("agent_logs").select("*").order("created_at",{ascending:!1}).limit(e);l&&console.error("Error fetching logs:",l),a&&(console.log("Logs fetched:",a.length),n(a)),s(!1)})();const o=$e.channel("logs-changes").on("postgres_changes",{event:"INSERT",schema:"public",table:"agent_logs"},a=>{n(l=>[a.new,...l.slice(0,e-1)])}).subscribe();return()=>{$e.removeChannel(o)}},[e]),{logs:t,loading:r}}const ty=[{name:"Jasmine",id:"Jasmine",role:"Atendimento ao Cliente",desc:"Especialista em recepção e suporte via Telegram/WhatsApp.",powers:{Simpatia:"10/10",Resolução:"8/10"},img:"jasmine_3d.png"},{name:"Shuri",id:"Shuri",role:"Arquitetura e Dev",desc:"Gênio técnica focada em infraestrutura e lógica central.",powers:{Inteligência:"10/10",Lógica:"9/10"},img:"shuri_3d.png"},{name:"Atlas",id:"Atlas",role:"Estrategista de Dados",desc:"Análise detalhada de mercado e inteligência competitiva.",powers:{Análise:"10/10",Estratégia:"9/10"},img:"atlas_3d.png"},{name:"Orion",id:"Orion",role:"Monitor de Marketing",desc:"Vigilância constante de tendências e campanhas.",powers:{Ads:"9/10",Criatividade:"8/10"},img:"orion_3d.png"},{name:"Quill",id:"Quill",role:"Monitor de Competidores",desc:"Especialista em monitoramento de concorrência e social.",powers:{Espionagem:"9/10",Copy:"9/10"},img:"quill_3d.png"}];function ny(){const[e,t]=z.useState(ty.map(n=>({...n,status:"offline",load:"0%"})));return z.useEffect(()=>{(async()=>{console.log("Fetching presence...");const{data:s,error:i}=await $e.from("agent_presence").select("*");i&&console.error("Error fetching presence:",i),s&&(console.log("Presence fetched:",s.length),t(o=>o.map(a=>{const l=s.find(u=>u.agent_id===a.id);return l?{...a,status:l.status,load:"Em operação"}:a})))})();const r=$e.channel("presence-changes").on("postgres_changes",{event:"*",schema:"public",table:"agent_presence"},s=>{t(i=>i.map(o=>{var a,l;return o.id===((a=s.new)==null?void 0:a.agent_id)||o.id===((l=s.old)==null?void 0:l.agent_id)?{...o,...s.new}:o}))}).subscribe();return()=>{$e.removeChannel(r)}},[]),{agents:e}}const lo="8da141f8-25d5-44d3-8652-fe0052dde949",Hu=2;function fa(e){return typeof e=="number"?e:typeof e=="string"&&Number(e.replace(",","."))||0}function ry(e){const t=Array.isArray(e)?e[0]:e;if(!t)return{payload:[],summary:null,snapshot_date:null};if(Array.isArray(t))return{payload:t,summary:null,snapshot_date:null};const n=Array.isArray(t.payload)?t.payload:Array.isArray(e)?e:[],r=t.summary||null,s=t.snapshot_date||null;return{payload:n,summary:r,snapshot_date:s}}function qu(e){const t=e.length;let n=0,r=0,s=0,i=0;const o=e.map(a=>{const l=Array.isArray(a.accounts)?a.accounts:[],u=fa(a.total_balance),c=Number(a.days_since_last_input||0),p=l.filter(h=>fa(h.balance)<0);return c>=Hu&&(s+=1),p.length>0&&(i+=1),u<0&&(r+=1),n+=u,{...a,total_balance:u,days_since_last_input:c,negative_accounts_count:p.length,negative_accounts:p}});return o.sort((a,l)=>l.total_balance-a.total_balance),{units:o,summary:{total_units:t,consolidated_balance:n,risk_units:r,stale_units:s,units_with_negative_accounts:i,stale_threshold_days:Hu}}}function sy(){const[e,t]=z.useState(new Date().toISOString().slice(0,10)),[n,r]=z.useState(!0),[s,i]=z.useState(null),[o,a]=z.useState({units:[],summary:null,snapshot_date:null}),[l,u]=z.useState([]),c=z.useCallback(async m=>{r(!0),i(null);const y={p_organization_id:lo,p_snapshot_date:m},{data:w,error:S}=await $e.rpc("fn_cashflow_snapshot_get",y);if(S){const _=await $e.rpc("get_units_financial_summary",{p_organization_id:lo});if(_.error){i(`Erro RPC snapshot: ${S.message}. Fallback também falhou: ${_.error.message}`),a({units:[],summary:null,snapshot_date:m}),r(!1);return}const{units:E,summary:x}=qu(Array.isArray(_.data)?_.data:[]);a({units:E,summary:x,snapshot_date:m}),r(!1);return}const f=ry(w);if(f.summary){const _=Array.isArray(f.payload)?f.payload.map(E=>({...E,total_balance:fa(E.total_balance),days_since_last_input:Number(E.days_since_last_input||0),accounts:Array.isArray(E.accounts)?E.accounts:[]})):[];_.sort((E,x)=>x.total_balance-E.total_balance),a({units:_,summary:f.summary,snapshot_date:f.snapshot_date||m}),r(!1);return}const{units:d,summary:g}=qu(f.payload||[]);a({units:d,summary:g,snapshot_date:f.snapshot_date||m}),r(!1)},[]),p=z.useCallback(async m=>{const y=new Date(m||new Date().toISOString().slice(0,10)),w=y.toISOString().slice(0,10),S=new Date(y.getTime()-1e3*60*60*24*90).toISOString().slice(0,10),{data:f,error:d}=await $e.rpc("fn_cashflow_snapshot_range",{p_organization_id:lo,p_from:S,p_to:w});if(d){u([]);return}u(Array.isArray(f)?f:[])},[]);z.useEffect(()=>{c(e),p(e)},[e,c,p]);const h=z.useMemo(()=>o.units.slice(0,5),[o.units]);return{loading:n,error:s,selectedDate:e,setSelectedDate:t,snapshot:o,history:l,topFive:h,refresh:()=>c(e)}}function iy(){const[e,t]=z.useState("mission"),[n,r]=z.useState(null),{tasks:s,loading:i}=Zv(),{logs:o,loading:a}=ey(),{agents:l}=ny(),{loading:u,error:c,selectedDate:p,setSelectedDate:h,snapshot:m,history:y,topFive:w,refresh:S}=sy(),f=z.useMemo(()=>e==="cashflow"?"Albert Finance - Fluxo de Caixa":"Global Operations",[e]),d=e==="cashflow"?"Finance Monitor Online":"System Online";return z.useEffect(()=>{if(!m.units.length){r(null);return}const g=n?m.units.some(_=>_.unit_id===n.unit_id):!1;if(!g&&!n){r(m.units[0]);return}!g&&n&&r(m.units[0])},[m.units,n]),v.jsxs("div",{className:"dashboard-container",children:[v.jsx(og,{activeView:e,onChangeView:t}),v.jsx(ag,{title:f,status:d}),v.jsx("main",{className:"area main-content",children:e==="mission"?i?v.jsx("div",{className:"loading-state",children:"Conectando ao terminal de missões..."}):v.jsx(cg,{tasks:s}):v.jsxs("section",{className:"cashflow-layout",children:[v.jsx(yg,{selectedDate:p,onDateChange:h,onRefresh:S}),c&&v.jsx("div",{className:"cashflow-error",children:c}),u?v.jsx("div",{className:"loading-state",children:"Carregando fluxo de caixa..."}):v.jsxs(v.Fragment,{children:[v.jsx(gg,{summary:m.summary,snapshotDate:m.snapshot_date||p}),v.jsx(vg,{units:m.units,onSelectUnit:r,selectedUnitId:n==null?void 0:n.unit_id}),v.jsx(wg,{unit:n||w[0]}),v.jsx(Sg,{history:y})]})]})}),v.jsx(dg,{logs:o,loading:a}),v.jsx(fg,{agents:l})]})}uo.createRoot(document.getElementById("root")).render(v.jsx(rc.StrictMode,{children:v.jsx(iy,{})})); +- ${g}`}f+=d}return`${k} +${f}`}class X extends Error{constructor({message:t,code:n,cause:r,name:s}){var i;super(t,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=n}}class ri extends X{constructor(t,n){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n,message:t}),this.name="WebAuthnUnknownError",this.originalError=n}}function dv({error:e,options:t}){var n,r,s;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new X({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.requireResidentKey)===!0)return new X({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new X({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new X({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if(e.name==="InvalidStateError")return new X({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new X({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new X({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new X({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){const o=window.location.hostname;if(kh(o)){if(i.rp.id!==o)return new X({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new X({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new X({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new X({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new X({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function hv({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new X({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if(e.name==="NotAllowedError")return new X({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){const r=window.location.hostname;if(kh(r)){if(n.rpId!==r)return new X({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new X({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new X({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new X({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}class fv{createNewAbortSignal(){if(this.controller){const n=new Error("Cancelling existing WebAuthn API call for new one");n.name="AbortError",this.controller.abort(n)}const t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){const t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}}const pv=new fv;function gv(e){if(!e)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:n,excludeCredentials:r}=e,s=Si(e,["challenge","user","excludeCredentials"]),i=Nn(t).buffer,o=Object.assign(Object.assign({},n),{id:Nn(n.id).buffer}),a=Object.assign(Object.assign({},s),{challenge:i,user:o});if(r&&r.length>0){a.excludeCredentials=new Array(r.length);for(let l=0;l0){i.allowCredentials=new Array(n.length);for(let o=0;os!==null&&typeof s=="object"&&!Array.isArray(s),n=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(const s of e)if(s)for(const i in s){const o=s[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(n(o))r[i]=o;else if(t(o)){const a=r[i];t(a)?r[i]=si(a,o):r[i]=si(o)}else r[i]=o}return r}function Ev(e,t){return si(kv,e,t||{})}function Tv(e,t){return si(Sv,e,t||{})}class bv{constructor(t){this.client=t,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(t){return this.client.mfa.enroll(Object.assign(Object.assign({},t),{factorType:"webauthn"}))}async _challenge({factorId:t,webauthn:n,friendlyName:r,signal:s},i){var o;try{const{data:a,error:l}=await this.client.mfa.challenge({factorId:t,webauthn:n});if(!a)return{data:null,error:l};const u=s??pv.createNewAbortSignal();if(a.webauthn.type==="create"){const{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){const p=r;if(p)c.name=`${c.id}:${p}`;else{const m=(await this.client.getUser()).data.user,v=((o=m==null?void 0:m.user_metadata)===null||o===void 0?void 0:o.name)||(m==null?void 0:m.email)||(m==null?void 0:m.id)||"User";c.name=`${c.id}:${v}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{const c=Ev(a.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:p,error:h}=await wv({publicKey:c,signal:u});return p?{data:{factorId:t,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:p}},error:null}:{data:null,error:h}}case"request":{const c=Tv(a.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:p,error:h}=await _v(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));return p?{data:{factorId:t,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:p}},error:null}:{data:null,error:h}}}}catch(a){return R(a)?{data:null,error:a}:{data:null,error:new Wt("Unexpected error in challenge",a)}}}async _verify({challengeId:t,factorId:n,webauthn:r}){return this.client.mfa.verify({factorId:n,challengeId:t,webauthn:r})}async _authenticate({factorId:t,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!n)return{data:null,error:new zr("rpId is required for WebAuthn authentication")};try{if(!Wu())return{data:null,error:new Wt("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this.challenge({factorId:t,webauthn:{rpId:n,rpOrigins:r},signal:s},{request:i});if(!o)return{data:null,error:a};const{webauthn:l}=o;return this._verify({factorId:t,challengeId:o.challengeId,webauthn:{type:l.type,rpId:n,rpOrigins:r,credential_response:l.credential_response}})}catch(o){return R(o)?{data:null,error:o}:{data:null,error:new Wt("Unexpected error in authenticate",o)}}}async _register({friendlyName:t,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!n)return{data:null,error:new zr("rpId is required for WebAuthn registration")};try{if(!Wu())return{data:null,error:new Wt("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this._enroll({friendlyName:t});if(!o)return await this.client.mfa.listFactors().then(c=>{var p;return(p=c.data)===null||p===void 0?void 0:p.all.find(h=>h.factor_type==="webauthn"&&h.friendly_name===t&&h.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c==null?void 0:c.id}):void 0),{data:null,error:a};const{data:l,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:n,rpOrigins:r},signal:s},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:n,rpOrigins:r,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(o){return R(o)?{data:null,error:o}:{data:null,error:new Wt("Unexpected error in register",o)}}}}av();const xv={url:Sm,storageKey:Em,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Tm,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function Vu(e,t,n){return await n()}const cn={};class Br{get jwks(){var t,n;return(n=(t=cn[this.storageKey])===null||t===void 0?void 0:t.jwks)!==null&&n!==void 0?n:{keys:[]}}set jwks(t){cn[this.storageKey]=Object.assign(Object.assign({},cn[this.storageKey]),{jwks:t})}get jwks_cached_at(){var t,n;return(n=(t=cn[this.storageKey])===null||t===void 0?void 0:t.cachedAt)!==null&&n!==void 0?n:Number.MIN_SAFE_INTEGER}set jwks_cached_at(t){cn[this.storageKey]=Object.assign(Object.assign({},cn[this.storageKey]),{cachedAt:t})}constructor(t){var n,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},xv),t);if(this.storageKey=i.storageKey,this.instanceID=(n=Br.nextInstanceID[this.storageKey])!==null&&n!==void 0?n:0,Br.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&ae()){const o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new sv({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=yh(i.fetch),this.lock=i.lock||Vu,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&ae()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=ov:this.lock=Vu,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 bv(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.persistSession?(i.storage?this.storage=i.storage:vh()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Fu(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Fu(this.memoryStorage)),ae()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(t){if(this.throwOnError&&t&&t.error)throw t.error;return t}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ph}) ${new Date().toISOString()}`}_debug(...t){return this.logDebugMessages&&this.logger(this._logPrefix(),...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var t;try{let n={},r="none";if(ae()&&(n=Dm(window.location.href),this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce")),ae()&&this.detectSessionInUrl&&r!=="none"){const{data:s,error:i}=await this._getSessionFromURL(n,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Rm(i)){const l=(t=i.details)===null||t===void 0?void 0:t.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:o,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(n){return R(n)?this._returnResult({error:n}):this._returnResult({error:new Wt("Unexpected error during initialization",n)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,s;try{const i=await j(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=t==null?void 0:t.options)===null||s===void 0?void 0:s.captchaToken}},xform:Me}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});const l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(R(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(t){var n,r,s;try{let i;if("email"in t){const{email:c,password:p,options:h}=t;let m=null,v=null;this.flowType==="pkce"&&([m,v]=await an(this.storage,this.storageKey)),i=await j(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h==null?void 0:h.emailRedirectTo,body:{email:c,password:p,data:(n=h==null?void 0:h.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken},code_challenge:m,code_challenge_method:v},xform:Me})}else if("phone"in t){const{phone:c,password:p,options:h}=t;i=await j(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:p,data:(r=h==null?void 0:h.data)!==null&&r!==void 0?r:{},channel:(s=h==null?void 0:h.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:Me})}else throw new vs("You must provide either an email or phone number and a password");const{data:o,error:a}=i;if(a||!o)return await oe(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});const l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(t){try{let n;if("email"in t){const{email:i,password:o,options:a}=t;n=await j(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Bu})}else if("phone"in t){const{phone:i,password:o,options:a}=t;n=await j(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Bu})}else throw new vs("You must provide either an email or phone number and a password");const{data:r,error:s}=n;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){const i=new on;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(n){if(R(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOAuth(t){var n,r,s,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=t.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(t))}async signInWithWeb3(t){const{chain:n}=t;switch(n){case"ethereum":return await this.signInWithEthereum(t);case"solana":return await this.signInWithSolana(t);default:throw new Error(`@supabase/auth-js: Unsupported chain "${n}"`)}}async signInWithEthereum(t){var n,r,s,i,o,a,l,u,c,p,h;let m,v;if("message"in t)m=t.message,v=t.signature;else{const{chain:y,wallet:k,statement:f,options:d}=t;let g;if(ae())if(typeof k=="object")g=k;else{const U=window;if("ethereum"in U&&typeof U.ethereum=="object"&&"request"in U.ethereum&&typeof U.ethereum.request=="function")g=U.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"||!(d!=null&&d.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");g=k}const _=new URL((n=d==null?void 0:d.url)!==null&&n!==void 0?n:window.location.href),E=await g.request({method:"eth_requestAccounts"}).then(U=>U).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!E||E.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const T=_h(E[0]);let b=(r=d==null?void 0:d.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!b){const U=await g.request({method:"eth_chainId"});b=lv(U)}const O={domain:_.host,address:T,statement:f,uri:_.href,version:"1",chainId:b,nonce:(s=d==null?void 0:d.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=d==null?void 0:d.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=d==null?void 0:d.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=d==null?void 0:d.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=d==null?void 0:d.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=d==null?void 0:d.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=cv(O),v=await g.request({method:"personal_sign",params:[uv(m),T]})}try{const{data:y,error:k}=await j(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:v},!((p=t.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(h=t.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:Me});if(k)throw k;if(!y||!y.session||!y.user){const f=new on;return this._returnResult({data:{user:null,session:null},error:f})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:k})}catch(y){if(R(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async signInWithSolana(t){var n,r,s,i,o,a,l,u,c,p,h,m;let v,y;if("message"in t)v=t.message,y=t.signature;else{const{chain:k,wallet:f,statement:d,options:g}=t;let _;if(ae())if(typeof f=="object")_=f;else{const T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))_=T.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 f!="object"||!(g!=null&&g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=f}const E=new URL((n=g==null?void 0:g.url)!==null&&n!==void 0?n:window.location.href);if("signIn"in _&&_.signIn){const T=await _.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},g==null?void 0:g.signInWithSolana),{version:"1",domain:E.host,uri:E.href}),d?{statement:d}:null));let b;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")b=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)b=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in b&&"signature"in b&&(typeof b.signedMessage=="string"||b.signedMessage instanceof Uint8Array)&&b.signature instanceof Uint8Array)v=typeof b.signedMessage=="string"?b.signedMessage:new TextDecoder().decode(b.signedMessage),y=b.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in _)||typeof _.signMessage!="function"||!("publicKey"in _)||typeof _!="object"||!_.publicKey||!("toBase58"in _.publicKey)||typeof _.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");v=[`${E.host} wants you to sign in with your Solana account:`,_.publicKey.toBase58(),...d?["",d,""]:[""],"Version: 1",`URI: ${E.href}`,`Issued At: ${(s=(r=g==null?void 0:g.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=g==null?void 0:g.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${g.signInWithSolana.notBefore}`]:[],...!((o=g==null?void 0:g.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${g.signInWithSolana.expirationTime}`]:[],...!((a=g==null?void 0:g.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${g.signInWithSolana.chainId}`]:[],...!((l=g==null?void 0:g.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${g.signInWithSolana.nonce}`]:[],...!((u=g==null?void 0:g.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${g.signInWithSolana.requestId}`]:[],...!((p=(c=g==null?void 0:g.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||p===void 0)&&p.length?["Resources",...g.signInWithSolana.resources.map(b=>`- ${b}`)]:[]].join(` +`);const T=await _.signMessage(new TextEncoder().encode(v),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");y=T}}try{const{data:k,error:f}=await j(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:v,signature:Kt(y)},!((h=t.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(m=t.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Me});if(f)throw f;if(!k||!k.session||!k.user){const d=new on;return this._returnResult({data:{user:null,session:null},error:d})}return k.session&&(await this._saveSession(k.session),await this._notifyAllSubscribers("SIGNED_IN",k.session)),this._returnResult({data:Object.assign({},k),error:f})}catch(k){if(R(k))return this._returnResult({data:{user:null,session:null},error:k});throw k}}async _exchangeCodeForSession(t){const n=await Dt(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(n??"").split("/");try{if(!r&&this.flowType==="pkce")throw new jm;const{data:i,error:o}=await j(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:Me});if(await oe(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){const a=new on;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s??null}),error:o})}catch(i){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(t){try{const{options:n,provider:r,token:s,access_token:i,nonce:o}=t,a=await j(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:Me}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){const c=new on;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(n){if(R(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOtp(t){var n,r,s,i,o;try{if("email"in t){const{email:a,options:l}=t;let u=null,c=null;this.flowType==="pkce"&&([u,c]=await an(this.storage,this.storageKey));const{error:p}=await j(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(n=l==null?void 0:l.data)!==null&&n!==void 0?n:{},create_user:(r=l==null?void 0:l.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:p})}if("phone"in t){const{phone:a,options:l}=t,{data:u,error:c}=await j(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l==null?void 0:l.data)!==null&&s!==void 0?s:{},create_user:(i=l==null?void 0:l.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(o=l==null?void 0:l.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u==null?void 0:u.message_id},error:c})}throw new vs("You must provide either an email or phone number.")}catch(a){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(t){var n,r;try{let s,i;"options"in t&&(s=(n=t.options)===null||n===void 0?void 0:n.redirectTo,i=(r=t.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:a}=await j(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Me});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,u=o.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(R(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(t){var n,r,s,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await an(this.storage,this.storageKey));const u=await j(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(r=(n=t.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r:void 0}),!((s=t==null?void 0:t.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:tv});return!((i=u.data)===null||i===void 0)&&i.url&&ae()&&!(!((o=t.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;if(r)throw r;if(!n)throw new Te;const{error:s}=await j(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(t){if(R(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async resend(t){try{const n=`${this.url}/resend`;if("email"in t){const{email:r,type:s,options:i}=t,{error:o}=await j(this.fetch,"POST",n,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in t){const{phone:r,type:s,options:i}=t,{data:o,error:a}=await j(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:a})}throw new vs("You must provide either an email or phone number and a type")}catch(n){if(R(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async n=>n))}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await t(n)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null;const n=await Dt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const r=t.expires_at?t.expires_at*1e3-Date.now()await this._getUser());return n.data.user&&(this.suppressGetSessionWarning=!0),n}async _getUser(t){try{return t?await j(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:wt}):await this._useSession(async n=>{var r,s,i;const{data:o,error:a}=n;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Te}:await j(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:wt})})}catch(n){if(R(n))return so(n)&&(await this._removeSession(),await oe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:n});throw n}}async updateUser(t,n={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(t,n))}async _updateUser(t,n={}){try{return await this._useSession(async r=>{const{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new Te;const o=s.session;let a=null,l=null;this.flowType==="pkce"&&t.email!=null&&([a,l]=await an(this.storage,this.storageKey));const{data:u,error:c}=await j(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:wt});if(c)throw c;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(r){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(r))return this._returnResult({data:{user:null},error:r});throw r}}async setSession(t){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new Te;const n=Date.now()/1e3;let r=n,s=!0,i=null;const{payload:o}=ws(t.access_token);if(o.exp&&(r=o.exp,s=r<=n),s){const{data:a,error:l}=await this._callRefreshToken(t.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};i=a}else{const{data:a,error:l}=await this._getUser(t.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:t.access_token,refresh_token:t.refresh_token,user:a.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(n){if(R(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async n=>{var r;if(!t){const{data:o,error:a}=n;if(a)throw a;t=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(t!=null&&t.refresh_token))throw new Te;const{data:s,error:i}=await this._callRefreshToken(t.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(n){if(R(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async _getSessionFromURL(t,n){try{if(!ae())throw new ys("No browser detected.");if(t.error||t.error_description||t.error_code)throw new ys(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(n){case"implicit":if(this.flowType==="pkce")throw new Nu("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ys("Not a valid implicit grant flow url.");break;default:}if(n==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new Nu("No code detected.");const{data:d,error:g}=await this._exchangeCodeForSession(t.code);if(g)throw g;const _=new URL(window.location.href);return _.searchParams.delete("code"),window.history.replaceState(window.history.state,"",_.toString()),{data:{session:d.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:s,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:u}=t;if(!i||!a||!o||!u)throw new ys("No session defined in URL");const c=Math.round(Date.now()/1e3),p=parseInt(a);let h=c+p;l&&(h=parseInt(l));const m=h-c;m*1e3<=hn&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${p}s`);const v=h-p;c-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,h,c):c-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",v,h,c);const{data:y,error:k}=await this._getUser(i);if(k)throw k;const f={provider_token:r,provider_refresh_token:s,access_token:i,expires_in:p,expires_at:h,refresh_token:o,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:f,redirectType:t.type},error:null})}catch(r){if(R(r))return this._returnResult({data:{session:null,redirectType:null},error:r});throw r}}_isImplicitGrantCallback(t){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),t):!!(t.access_token||t.error_description)}async _isPKCECallback(t){const n=await Dt(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&n)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async n=>{var r;const{data:s,error:i}=n;if(i&&!so(i))return this._returnResult({error:i});const o=(r=s.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:a}=await this.admin.signOut(o,t);if(a&&!(Om(a)&&(a.status===404||a.status===401||a.status===403)||so(a)))return this._returnResult({error:a})}return t!=="others"&&(await this._removeSession(),await oe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(t){const n=Um(),r={id:n,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,r),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async n=>{var r,s;try{const{data:{session:i},error:o}=n;if(o)throw o;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(t))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),console.error(i)}})}async resetPasswordForEmail(t,n={}){let r=null,s=null;this.flowType==="pkce"&&([r,s]=await an(this.storage,this.storageKey,!0));try{return await j(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(i){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var t;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}}async linkIdentity(t){return"token"in t?this.linkIdentityIdToken(t):this.linkIdentityOAuth(t)}async linkIdentityOAuth(t){var n;try{const{data:r,error:s}=await this._useSession(async i=>{var o,a,l,u,c;const{data:p,error:h}=i;if(h)throw h;const m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(o=t.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=t.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=t.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await j(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=p.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(s)throw s;return ae()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),this._returnResult({data:{provider:t.provider,url:r==null?void 0:r.url},error:null})}catch(r){if(R(r))return this._returnResult({data:{provider:t.provider,url:null},error:r});throw r}}async linkIdentityIdToken(t){return await this._useSession(async n=>{var r;try{const{error:s,data:{session:i}}=n;if(s)throw s;const{options:o,provider:a,token:l,access_token:u,nonce:c}=t,p=await j(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i==null?void 0:i.access_token)!==null&&r!==void 0?r:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Me}),{data:h,error:m}=p;return m?this._returnResult({data:{user:null,session:null},error:m}):!h||!h.session||!h.user?this._returnResult({data:{user:null,session:null},error:new on}):(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:m}))}catch(s){if(await oe(this.storage,`${this.storageKey}-code-verifier`),R(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(t){try{return await this._useSession(async n=>{var r,s;const{data:i,error:o}=n;if(o)throw o;return await j(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}}async _refreshAccessToken(t){const n=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(n,"begin");try{const r=Date.now();return await Mm(async s=>(s>0&&await Bm(200*Math.pow(2,s-1)),this._debug(n,"refreshing attempt",s),await j(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:Me})),(s,i)=>{const o=200*Math.pow(2,s);return i&&io(i)&&Date.now()+o-r{try{await a.callback(t,n)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;athis._autoRefreshTokenTick(),hn);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t);const n=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=n,n&&typeof n=="object"&&typeof n.unref=="function"?n.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(n)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t);const n=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,n&&clearTimeout(n)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const s=Math.floor((r.expires_at*1e3-t)/hn);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${hn}ms, refresh threshold is ${ua} ticks`),s<=ua&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof wh)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!ae()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(t){this._debug("#visibilityChangedCallback","error",t)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const n=`#_onVisibilityChanged(${t})`;this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(n,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,n,r){const s=[`provider=${encodeURIComponent(n)}`];if(r!=null&&r.redirectTo&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[i,o]=await an(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(r!=null&&r.queryParams){const i=new URLSearchParams(r.queryParams);s.push(i.toString())}return r!=null&&r.skipBrowserRedirect&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${t}?${s.join("&")}`}async _unenroll(t){try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;return i?this._returnResult({data:null,error:i}):await j(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}}async _enroll(t){try{return await this._useSession(async n=>{var r,s;const{data:i,error:o}=n;if(o)return this._returnResult({data:null,error:o});const a=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:t.factorType==="totp"?{issuer:t.issuer}:{}),{data:l,error:u}=await j(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(t.factorType==="totp"&&l.type==="totp"&&(!((s=l==null?void 0:l.totp)===null||s===void 0)&&s.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}}async _verify(t){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({challenge_id:t.challengeId},"webauthn"in t?{webauthn:Object.assign(Object.assign({},t.webauthn),{credential_response:t.webauthn.type==="create"?vv(t.webauthn.credential_response):yv(t.webauthn.credential_response)})}:{code:t.code}),{data:a,error:l}=await j(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:o,headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}})}async _challenge(t){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;if(i)return this._returnResult({data:null,error:i});const o=await j(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:t,headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});if(o.error)return o;const{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:gv(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:mv(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}})}async _challengeAndVerify(t){const{data:n,error:r}=await this._challenge({factorId:t.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){var t;const{data:{user:n},error:r}=await this.getUser();if(r)return{data:null,error:r};const s={all:[],phone:[],totp:[],webauthn:[]};for(const i of(t=n==null?void 0:n.factors)!==null&&t!==void 0?t:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(t){var n,r,s,i;if(t)try{const{payload:m}=ws(t);let v=null;m.aal&&(v=m.aal);let y=v;const{data:{user:k},error:f}=await this.getUser(t);if(f)return this._returnResult({data:null,error:f});((r=(n=k==null?void 0:k.factors)===null||n===void 0?void 0:n.filter(_=>_.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(y="aal2");const g=m.amr||[];return{data:{currentLevel:v,nextLevel:y,currentAuthenticationMethods:g},error:null}}catch(m){if(R(m))return this._returnResult({data:null,error:m});throw m}const{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=ws(o.access_token);let u=null;l.aal&&(u=l.aal);let c=u;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(m=>m.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(c="aal2");const h=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:h},error:null}}async _getAuthorizationDetails(t){try{return await this._useSession(async n=>{const{data:{session:r},error:s}=n;return s?this._returnResult({data:null,error:s}):r?await j(this.fetch,"GET",`${this.url}/oauth/authorizations/${t}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Te})})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}}async _approveAuthorization(t,n){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Te});const o=await j(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&ae()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(R(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(t,n){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Te});const o=await j(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&ae()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(R(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?await j(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Te})})}catch(t){if(R(t))return this._returnResult({data:null,error:t});throw t}}async _revokeOAuthGrant(t){try{return await this._useSession(async n=>{const{data:{session:r},error:s}=n;return s?this._returnResult({data:null,error:s}):r?(await j(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:t.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Te})})}catch(n){if(R(n))return this._returnResult({data:null,error:n});throw n}}async fetchJwk(t,n={keys:[]}){let r=n.keys.find(a=>a.kid===t);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(a=>a.kid===t),r&&this.jwks_cached_at+xm>s)return r;const{data:i,error:o}=await j(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(a=>a.kid===t),!r)?null:r}async getClaims(t,n={}){try{let r=t;if(!r){const{data:m,error:v}=await this.getSession();if(v||!m.session)return this._returnResult({data:null,error:v});r=m.session.access_token}const{header:s,payload:i,signature:o,raw:{header:a,payload:l}}=ws(r);n!=null&&n.allowExpired||Gm(i.exp);const u=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,n!=null&&n.keys?{keys:n.keys}:n==null?void 0:n.jwks);if(!u){const{error:m}=await this.getUser(r);if(m)throw m;return{data:{claims:i,header:s,signature:o},error:null}}const c=Jm(s.alg),p=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,p,o,Lm(`${a}.${l}`)))throw new ha("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(R(r))return this._returnResult({data:null,error:r});throw r}}}Br.nextInstanceID={};const Cv=Br,Ov="2.95.3";let or="";typeof Deno<"u"?or="deno":typeof document<"u"?or="web":typeof navigator<"u"&&navigator.product==="ReactNative"?or="react-native":or="node";const Rv={"X-Client-Info":`supabase-js-${or}/${Ov}`},jv={headers:Rv},Av={schema:"public"},Pv={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Nv={};function Mr(e){"@babel/helpers - typeof";return Mr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Mr(e)}function Iv(e,t){if(Mr(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Mr(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Lv(e){var t=Iv(e,"string");return Mr(t)=="symbol"?t:t+""}function $v(e,t,n){return(t=Lv(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Hu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function G(e){for(var t=1;te?(...t)=>e(...t):(...t)=>fetch(...t),Dv=()=>Headers,zv=(e,t,n)=>{const r=Uv(n),s=Dv();return async(i,o)=>{var a;const l=(a=await t())!==null&&a!==void 0?a:e;let u=new s(o==null?void 0:o.headers);return u.has("apikey")||u.set("apikey",e),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),r(i,G(G({},o),{},{headers:u}))}};function Bv(e){return e.endsWith("/")?e:e+"/"}function Mv(e,t){var n,r;const{db:s,auth:i,realtime:o,global:a}=e,{db:l,auth:u,realtime:c,global:p}=t,h={db:G(G({},l),s),auth:G(G({},u),i),realtime:G(G({},c),o),storage:{},global:G(G(G({},p),a),{},{headers:G(G({},(n=p==null?void 0:p.headers)!==null&&n!==void 0?n:{}),(r=a==null?void 0:a.headers)!==null&&r!==void 0?r:{})}),accessToken:async()=>""};return e.accessToken?h.accessToken=e.accessToken:delete h.accessToken,h}function Fv(e){const t=e==null?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Bv(t))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Wv=class extends Cv{constructor(e){super(e)}},Vv=class{constructor(e,t,n){var r,s;this.supabaseUrl=e,this.supabaseKey=t;const i=Fv(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const o=`sb-${i.hostname.split(".")[0]}-auth-token`,a={db:Av,realtime:Nv,auth:G(G({},Pv),{},{storageKey:o}),global:jv},l=Mv(n??{},a);if(this.storageKey=(r=l.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(s=l.global.headers)!==null&&s!==void 0?s:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=zv(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(G({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(c=>this.realtime.setAuth(c)).catch(c=>console.warn("Failed to set initial Realtime auth token:",c)),this.rest=new Og(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new km(this.storageUrl.href,this.headers,this.fetch,n==null?void 0:n.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new _g(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e=this,t,n;if(e.accessToken)return await e.accessToken();const{data:r}=await e.auth.getSession();return(t=(n=r.session)===null||n===void 0?void 0:n.access_token)!==null&&t!==void 0?t:e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:s,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:u},c,p){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Wv({url:this.authUrl.href,headers:G(G({},h),c),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:s,flowType:o,lock:a,debug:l,throwOnError:u,fetch:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new Hg(this.realtimeUrl.href,G(G({},e),{},{params:G(G({},{apikey:this.supabaseKey}),e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",t==null?void 0:t.access_token)})}_handleTokenChanged(e,t,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const Hv=(e,t,n)=>new Vv(e,t,n);function qv(){if(typeof window<"u")return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(t==null)return!1;const n=t.match(/^v(\d+)\./);return n?parseInt(n[1],10)<=18:!1}qv()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const Sh="https://tnurlgbvfsxwqgwxamni.supabase.co",Kv="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InRudXJsZ2J2ZnN4d3Fnd3hhbW5pIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDQ5MTQ1OTksImV4cCI6MjA2MDQ5MDU5OX0.9__EQiZDJ954SmeeJIDTQjOYDjiiRcppai1e8UpuOl4";console.log("Initializing Supabase client with URL:",Sh);const $e=Hv(Sh,Kv,{db:{schema:"public"}});console.log("Supabase client initialized for schema: openclaw");function Gv(){const[e,t]=z.useState([]),[n,r]=z.useState(!0);return z.useEffect(()=>{(async()=>{console.log("Fetching tasks...");const{data:o,error:a}=await $e.from("agent_tasks").select("*").order("updated_at",{ascending:!1});a&&console.error("Error fetching tasks:",a),o&&(console.log("Tasks fetched:",o.length),t(o)),r(!1)})();const i=$e.channel("tasks-changes").on("postgres_changes",{event:"*",schema:"public",table:"agent_tasks"},o=>{o.eventType==="INSERT"?t(a=>[o.new,...a]):o.eventType==="UPDATE"?t(a=>a.map(l=>l.id===o.new.id?o.new:l)):o.eventType==="DELETE"&&t(a=>a.filter(l=>l.id===o.old.id))}).subscribe();return()=>{$e.removeChannel(i)}},[]),{tasks:e,loading:n}}function Jv(e=20){const[t,n]=z.useState([]),[r,s]=z.useState(!0);return z.useEffect(()=>{(async()=>{console.log("Fetching logs...");const{data:a,error:l}=await $e.from("agent_logs").select("*").order("created_at",{ascending:!1}).limit(e);l&&console.error("Error fetching logs:",l),a&&(console.log("Logs fetched:",a.length),n(a)),s(!1)})();const o=$e.channel("logs-changes").on("postgres_changes",{event:"INSERT",schema:"public",table:"agent_logs"},a=>{n(l=>[a.new,...l.slice(0,e-1)])}).subscribe();return()=>{$e.removeChannel(o)}},[e]),{logs:t,loading:r}}const Qv=[{name:"Jasmine",id:"Jasmine",role:"Atendimento ao Cliente",desc:"Especialista em recepção e suporte via Telegram/WhatsApp.",powers:{Simpatia:"10/10",Resolução:"8/10"},img:"jasmine_3d.png"},{name:"Shuri",id:"Shuri",role:"Arquitetura e Dev",desc:"Gênio técnica focada em infraestrutura e lógica central.",powers:{Inteligência:"10/10",Lógica:"9/10"},img:"shuri_3d.png"},{name:"Atlas",id:"Atlas",role:"Estrategista de Dados",desc:"Análise detalhada de mercado e inteligência competitiva.",powers:{Análise:"10/10",Estratégia:"9/10"},img:"atlas_3d.png"},{name:"Orion",id:"Orion",role:"Monitor de Marketing",desc:"Vigilância constante de tendências e campanhas.",powers:{Ads:"9/10",Criatividade:"8/10"},img:"orion_3d.png"},{name:"Quill",id:"Quill",role:"Monitor de Competidores",desc:"Especialista em monitoramento de concorrência e social.",powers:{Espionagem:"9/10",Copy:"9/10"},img:"quill_3d.png"}];function Yv(){const[e,t]=z.useState(Qv.map(n=>({...n,status:"offline",load:"0%"})));return z.useEffect(()=>{(async()=>{console.log("Fetching presence...");const{data:s,error:i}=await $e.from("agent_presence").select("*");i&&console.error("Error fetching presence:",i),s&&(console.log("Presence fetched:",s.length),t(o=>o.map(a=>{const l=s.find(u=>u.agent_id===a.id);return l?{...a,status:l.status,load:"Em operação"}:a})))})();const r=$e.channel("presence-changes").on("postgres_changes",{event:"*",schema:"public",table:"agent_presence"},s=>{t(i=>i.map(o=>{var a,l;return o.id===((a=s.new)==null?void 0:a.agent_id)||o.id===((l=s.old)==null?void 0:l.agent_id)?{...o,...s.new}:o}))}).subscribe();return()=>{$e.removeChannel(r)}},[]),{agents:e}}const lo="8da141f8-25d5-44d3-8652-fe0052dde949",qu=2;function fa(e){return typeof e=="number"?e:typeof e=="string"&&Number(e.replace(",","."))||0}function Xv(e){const t=Array.isArray(e)?e[0]:e;if(!t)return{payload:[],summary:null,snapshot_date:null};if(Array.isArray(t))return{payload:t,summary:null,snapshot_date:null};const n=Array.isArray(t.payload)?t.payload:Array.isArray(e)?e:[],r=t.summary||null,s=t.snapshot_date||null;return{payload:n,summary:r,snapshot_date:s}}function Ku(e){const t=e.length;let n=0,r=0,s=0,i=0;const o=e.map(a=>{const l=Array.isArray(a.accounts)?a.accounts:[],u=fa(a.total_balance),c=Number(a.days_since_last_input||0),p=l.filter(h=>fa(h.balance)<0);return c>=qu&&(s+=1),p.length>0&&(i+=1),u<0&&(r+=1),n+=u,{...a,total_balance:u,days_since_last_input:c,negative_accounts_count:p.length,negative_accounts:p}});return o.sort((a,l)=>l.total_balance-a.total_balance),{units:o,summary:{total_units:t,consolidated_balance:n,risk_units:r,stale_units:s,units_with_negative_accounts:i,stale_threshold_days:qu}}}function Zv(){const[e,t]=z.useState(new Date().toISOString().slice(0,10)),[n,r]=z.useState(!0),[s,i]=z.useState(null),[o,a]=z.useState({units:[],summary:null,snapshot_date:null}),[l,u]=z.useState([]),c=z.useCallback(async m=>{r(!0),i(null);const v={p_organization_id:lo,p_snapshot_date:m},{data:y,error:k}=await $e.rpc("fn_cashflow_snapshot_get",v);if(k){const _=await $e.rpc("get_units_financial_summary",{p_organization_id:lo});if(_.error){i(`Erro RPC snapshot: ${k.message}. Fallback também falhou: ${_.error.message}`),a({units:[],summary:null,snapshot_date:m}),r(!1);return}const{units:E,summary:T}=Ku(Array.isArray(_.data)?_.data:[]);a({units:E,summary:T,snapshot_date:m}),r(!1);return}const f=Xv(y);if(f.summary){const _=Array.isArray(f.payload)?f.payload.map(E=>({...E,total_balance:fa(E.total_balance),days_since_last_input:Number(E.days_since_last_input||0),accounts:Array.isArray(E.accounts)?E.accounts:[]})):[];_.sort((E,T)=>T.total_balance-E.total_balance),a({units:_,summary:f.summary,snapshot_date:f.snapshot_date||m}),r(!1);return}const{units:d,summary:g}=Ku(f.payload||[]);a({units:d,summary:g,snapshot_date:f.snapshot_date||m}),r(!1)},[]),p=z.useCallback(async m=>{const v=new Date(m||new Date().toISOString().slice(0,10)),y=v.toISOString().slice(0,10),k=new Date(v.getTime()-1e3*60*60*24*90).toISOString().slice(0,10),{data:f,error:d}=await $e.rpc("fn_cashflow_snapshot_range",{p_organization_id:lo,p_from:k,p_to:y});if(d){u([]);return}u(Array.isArray(f)?f:[])},[]);z.useEffect(()=>{c(e),p(e)},[e,c,p]);const h=z.useMemo(()=>o.units.slice(0,5),[o.units]);return{loading:n,error:s,selectedDate:e,setSelectedDate:t,snapshot:o,history:l,topFive:h,refresh:()=>c(e)}}const ey="cashflow";function ty(){const[e,t]=z.useState("cashflow"),[n,r]=z.useState(null);Gv();const{logs:s,loading:i}=Jv(),{agents:o}=Yv(),{loading:a,error:l,selectedDate:u,setSelectedDate:c,snapshot:p,history:h,topFive:m,refresh:v}=Zv(),y=z.useMemo(()=>"Albert Finance - Fluxo de Caixa",[e]),k="Finance Monitor Online";return z.useEffect(()=>{if(!p.units.length){r(null);return}const f=n?p.units.some(d=>d.unit_id===n.unit_id):!1;if(!f&&!n){r(p.units[0]);return}!f&&n&&r(p.units[0])},[p.units,n]),w.jsxs("div",{className:"dashboard-container",children:[w.jsx(sg,{activeView:e,onChangeView:t,mode:ey}),w.jsx(ig,{title:y,status:k}),w.jsx("main",{className:"area main-content",children:w.jsxs("section",{className:"cashflow-layout",children:[w.jsx(fg,{selectedDate:u,onDateChange:c,onRefresh:v}),l&&w.jsx("div",{className:"cashflow-error",children:l}),a?w.jsx("div",{className:"loading-state",children:"Carregando fluxo de caixa..."}):w.jsxs(w.Fragment,{children:[w.jsx(cg,{summary:p.summary,snapshotDate:p.snapshot_date||u}),w.jsx(hg,{units:p.units,onSelectUnit:r,selectedUnitId:n==null?void 0:n.unit_id}),w.jsx(pg,{unit:n||m[0]}),w.jsx(mg,{history:h})]})]})}),w.jsx(og,{logs:s,loading:i}),w.jsx(lg,{agents:o})]})}uo.createRoot(document.getElementById("root")).render(w.jsx(Bh.StrictMode,{children:w.jsx(ty,{})})); diff --git a/index.html b/index.html index e319ef3..8490eb7 100644 --- a/index.html +++ b/index.html @@ -8,7 +8,7 @@ - +