(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.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)}})();var ze=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function rf(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:function(){return t[r]}})}),n}var fc={exports:{}},wi={},pc={exports:{}},U={};/** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Xr=Symbol.for("react.element"),sf=Symbol.for("react.portal"),of=Symbol.for("react.fragment"),af=Symbol.for("react.strict_mode"),lf=Symbol.for("react.profiler"),uf=Symbol.for("react.provider"),cf=Symbol.for("react.context"),df=Symbol.for("react.forward_ref"),hf=Symbol.for("react.suspense"),ff=Symbol.for("react.memo"),pf=Symbol.for("react.lazy"),Al=Symbol.iterator;function mf(t){return t===null||typeof t!="object"?null:(t=Al&&t[Al]||t["@@iterator"],typeof t=="function"?t:null)}var mc={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},vc=Object.assign,gc={};function er(t,e,n){this.props=t,this.context=e,this.refs=gc,this.updater=n||mc}er.prototype.isReactComponent={};er.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=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,t,e,"setState")};er.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function yc(){}yc.prototype=er.prototype;function Ta(t,e,n){this.props=t,this.context=e,this.refs=gc,this.updater=n||mc}var Pa=Ta.prototype=new yc;Pa.constructor=Ta;vc(Pa,er.prototype);Pa.isPureReactComponent=!0;var Rl=Array.isArray,wc=Object.prototype.hasOwnProperty,Oa={current:null},xc={key:!0,ref:!0,__self:!0,__source:!0};function _c(t,e,n){var r,s={},i=null,o=null;if(e!=null)for(r in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(i=""+e.key),e)wc.call(e,r)&&!xc.hasOwnProperty(r)&&(s[r]=e[r]);var a=arguments.length-2;if(a===1)s.children=n;else if(1>>1,te=b[K];if(0>>1;Ks(ir,A))ets(gn,ir)?(b[K]=gn,b[et]=A,K=et):(b[K]=ir,b[at]=A,K=at);else if(ets(gn,A))b[K]=gn,b[et]=A,K=et;else break e}}return O}function s(b,O){var A=b.sortIndex-O.sortIndex;return A!==0?A:b.id-O.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;t.unstable_now=function(){return i.now()}}else{var o=Date,a=o.now();t.unstable_now=function(){return o.now()-a}}var l=[],c=[],d=1,h=null,f=3,g=!1,y=!1,x=!1,E=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,p=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function m(b){for(var O=n(c);O!==null;){if(O.callback===null)r(c);else if(O.startTime<=b)r(c),O.sortIndex=O.expirationTime,e(l,O);else break;O=n(c)}}function w(b){if(x=!1,m(b),!y)if(n(l)!==null)y=!0,mn(S);else{var O=n(c);O!==null&&Vt(w,O.startTime-b)}}function S(b,O){y=!1,x&&(x=!1,v(C),C=-1),g=!0;var A=f;try{for(m(O),h=n(l);h!==null&&(!(h.expirationTime>O)||b&&!ge());){var K=h.callback;if(typeof K=="function"){h.callback=null,f=h.priorityLevel;var te=K(h.expirationTime<=O);O=t.unstable_now(),typeof te=="function"?h.callback=te:h===n(l)&&r(l),m(O)}else r(l);h=n(l)}if(h!==null)var vn=!0;else{var at=n(c);at!==null&&Vt(w,at.startTime-O),vn=!1}return vn}finally{h=null,f=A,g=!1}}var k=!1,j=null,C=-1,B=5,$=-1;function ge(){return!(t.unstable_now()-$b||125K?(b.sortIndex=A,e(c,b),n(l)===null&&b===n(c)&&(x?(v(C),C=-1):x=!0,Vt(w,A-K))):(b.sortIndex=te,e(l,b),y||g||(y=!0,mn(S))),b},t.unstable_shouldYield=ge,t.unstable_wrapCallback=function(b){var O=f;return function(){var A=f;f=O;try{return b.apply(this,arguments)}finally{f=A}}}})(bc);Ec.exports=bc;var bf=Ec.exports;/** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Nf=T,Re=bf;function _(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Eo=Object.prototype.hasOwnProperty,Cf=/^[: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]*$/,Ll={},Il={};function Tf(t){return Eo.call(Il,t)?!0:Eo.call(Ll,t)?!1:Cf.test(t)?Il[t]=!0:(Ll[t]=!0,!1)}function Pf(t,e,n,r){if(n!==null&&n.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(t=t.toLowerCase().slice(0,5),t!=="data-"&&t!=="aria-");default:return!1}}function Of(t,e,n,r){if(e===null||typeof e>"u"||Pf(t,e,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function ke(t,e,n,r,s,i,o){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=t,this.type=e,this.sanitizeURL=i,this.removeEmptyString=o}var de={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){de[t]=new ke(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];de[e]=new ke(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){de[t]=new ke(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){de[t]=new ke(t,2,!1,t,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(t){de[t]=new ke(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){de[t]=new ke(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){de[t]=new ke(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){de[t]=new ke(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){de[t]=new ke(t,5,!1,t.toLowerCase(),null,!1,!1)});var Ra=/[\-:]([a-z])/g;function $a(t){return t[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(t){var e=t.replace(Ra,$a);de[e]=new ke(e,1,!1,t,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(t){var e=t.replace(Ra,$a);de[e]=new ke(e,1,!1,t,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(t){var e=t.replace(Ra,$a);de[e]=new ke(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){de[t]=new ke(t,1,!1,t.toLowerCase(),null,!1,!1)});de.xlinkHref=new ke("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){de[t]=new ke(t,1,!1,t.toLowerCase(),null,!0,!0)});function La(t,e,n,r){var s=de.hasOwnProperty(e)?de[e]:null;(s!==null?s.type!==0:r||!(2a||s[o]!==i[a]){var l=` `+s[o].replace(" at new "," at ");return t.displayName&&l.includes("")&&(l=l.replace("",t.displayName)),l}while(1<=o&&0<=a);break}}}finally{Wi=!1,Error.prepareStackTrace=n}return(t=t?t.displayName||t.name:"")?vr(t):""}function Af(t){switch(t.tag){case 5:return vr(t.type);case 16:return vr("Lazy");case 13:return vr("Suspense");case 19:return vr("SuspenseList");case 0:case 2:case 15:return t=Hi(t.type,!1),t;case 11:return t=Hi(t.type.render,!1),t;case 1:return t=Hi(t.type,!0),t;default:return""}}function To(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case Nn:return"Fragment";case bn:return"Portal";case bo:return"Profiler";case Ia:return"StrictMode";case No:return"Suspense";case Co:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case Tc:return(t.displayName||"Context")+".Consumer";case Cc:return(t._context.displayName||"Context")+".Provider";case Ua:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case Da:return e=t.displayName||null,e!==null?e:To(t.type)||"Memo";case jt:e=t._payload,t=t._init;try{return To(t(e))}catch{}}return null}function Rf(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return To(e);case 8:return e===Ia?"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 e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function Mt(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function Oc(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function $f(t){var e=Oc(t)?"checked":"value",n=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),r=""+t[e];if(!t.hasOwnProperty(e)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,i=n.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return s.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(t,e,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function fs(t){t._valueTracker||(t._valueTracker=$f(t))}function Ac(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var n=e.getValue(),r="";return t&&(r=Oc(t)?t.checked?"true":"false":t.value),t=r,t!==n?(e.setValue(t),!0):!1}function Hs(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function Po(t,e){var n=e.checked;return Y({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??t._wrapperState.initialChecked})}function Dl(t,e){var n=e.defaultValue==null?"":e.defaultValue,r=e.checked!=null?e.checked:e.defaultChecked;n=Mt(e.value!=null?e.value:n),t._wrapperState={initialChecked:r,initialValue:n,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function Rc(t,e){e=e.checked,e!=null&&La(t,"checked",e,!1)}function Oo(t,e){Rc(t,e);var n=Mt(e.value),r=e.type;if(n!=null)r==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+n):t.value!==""+n&&(t.value=""+n);else if(r==="submit"||r==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?Ao(t,e.type,n):e.hasOwnProperty("defaultValue")&&Ao(t,e.type,Mt(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function Ml(t,e,n){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var r=e.type;if(!(r!=="submit"&&r!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,n||e===t.value||(t.value=e),t.defaultValue=e}n=t.name,n!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,n!==""&&(t.name=n)}function Ao(t,e,n){(e!=="number"||Hs(t.ownerDocument)!==t)&&(n==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+n&&(t.defaultValue=""+n))}var gr=Array.isArray;function Mn(t,e,n,r){if(t=t.options,e){e={};for(var s=0;s"+e.valueOf().toString()+"",e=ps.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function $r(t,e){if(e){var n=t.firstChild;if(n&&n===t.lastChild&&n.nodeType===3){n.nodeValue=e;return}}t.textContent=e}var _r={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},Lf=["Webkit","ms","Moz","O"];Object.keys(_r).forEach(function(t){Lf.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),_r[e]=_r[t]})});function Uc(t,e,n){return e==null||typeof e=="boolean"||e===""?"":n||typeof e!="number"||e===0||_r.hasOwnProperty(t)&&_r[t]?(""+e).trim():e+"px"}function Dc(t,e){t=t.style;for(var n in e)if(e.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=Uc(n,e[n],r);n==="float"&&(n="cssFloat"),r?t.setProperty(n,s):t[n]=s}}var If=Y({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 Lo(t,e){if(e){if(If[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(_(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(_(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(_(61))}if(e.style!=null&&typeof e.style!="object")throw Error(_(62))}}function Io(t,e){if(t.indexOf("-")===-1)return typeof e.is=="string";switch(t){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 Uo=null;function Ma(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var Do=null,zn=null,Fn=null;function Bl(t){if(t=ts(t)){if(typeof Do!="function")throw Error(_(280));var e=t.stateNode;e&&(e=ji(e),Do(t.stateNode,t.type,e))}}function Mc(t){zn?Fn?Fn.push(t):Fn=[t]:zn=t}function zc(){if(zn){var t=zn,e=Fn;if(Fn=zn=null,Bl(t),e)for(t=0;t>>=0,t===0?32:31-(Kf(t)/Gf|0)|0}var ms=64,vs=4194304;function yr(t){switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64: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 t&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return t&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return t}}function Gs(t,e){var n=t.pendingLanes;if(n===0)return 0;var r=0,s=t.suspendedLanes,i=t.pingedLanes,o=n&268435455;if(o!==0){var a=o&~s;a!==0?r=yr(a):(i&=o,i!==0&&(r=yr(i)))}else o=n&~s,o!==0?r=yr(o):i!==0&&(r=yr(i));if(r===0)return 0;if(e!==0&&e!==r&&!(e&s)&&(s=r&-r,i=e&-e,s>=i||s===16&&(i&4194240)!==0))return e;if(r&4&&(r|=n&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=r;0n;n++)e.push(t);return e}function Zr(t,e,n){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-Je(e),t[e]=n}function Xf(t,e){var n=t.pendingLanes&~e;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.expiredLanes&=e,t.mutableReadLanes&=e,t.entangledLanes&=e,e=t.entanglements;var r=t.eventTimes;for(t=t.expirationTimes;0=Sr),Yl=" ",Xl=!1;function od(t,e){switch(t){case"keyup":return bp.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ad(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Cn=!1;function Cp(t,e){switch(t){case"compositionend":return ad(e);case"keypress":return e.which!==32?null:(Xl=!0,Yl);case"textInput":return t=e.data,t===Yl&&Xl?null:t;default:return null}}function Tp(t,e){if(Cn)return t==="compositionend"||!Ka&&od(t,e)?(t=sd(),Ls=Ha=Tt=null,Cn=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:n,offset:e-t};t=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=nu(n)}}function dd(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?dd(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function hd(){for(var t=window,e=Hs();e instanceof t.HTMLIFrameElement;){try{var n=typeof e.contentWindow.location.href=="string"}catch{n=!1}if(n)t=e.contentWindow;else break;e=Hs(t.document)}return e}function Ga(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}function Dp(t){var e=hd(),n=t.focusedElem,r=t.selectionRange;if(e!==n&&n&&n.ownerDocument&&dd(n.ownerDocument.documentElement,n)){if(r!==null&&Ga(n)){if(e=r.start,t=r.end,t===void 0&&(t=e),"selectionStart"in n)n.selectionStart=e,n.selectionEnd=Math.min(t,n.value.length);else if(t=(e=n.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var s=n.textContent.length,i=Math.min(r.start,s);r=r.end===void 0?i:Math.min(r.end,s),!t.extend&&i>r&&(s=r,r=i,i=s),s=ru(n,i);var o=ru(n,r);s&&o&&(t.rangeCount!==1||t.anchorNode!==s.node||t.anchorOffset!==s.offset||t.focusNode!==o.node||t.focusOffset!==o.offset)&&(e=e.createRange(),e.setStart(s.node,s.offset),t.removeAllRanges(),i>r?(t.addRange(e),t.extend(o.node,o.offset)):(e.setEnd(o.node,o.offset),t.addRange(e)))}}for(e=[],t=n;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Tn=null,Ho=null,Er=null,Vo=!1;function su(t,e,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Vo||Tn==null||Tn!==Hs(r)||(r=Tn,"selectionStart"in r&&Ga(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}),Er&&zr(Er,r)||(Er=r,r=Ys(Ho,"onSelect"),0An||(t.current=Yo[An],Yo[An]=null,An--)}function F(t,e){An++,Yo[An]=t.current,t.current=e}var zt={},ve=Bt(zt),Ne=Bt(!1),sn=zt;function Kn(t,e){var n=t.type.contextTypes;if(!n)return zt;var r=t.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===e)return r.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in n)s[i]=e[i];return r&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=s),s}function Ce(t){return t=t.childContextTypes,t!=null}function Zs(){V(Ne),V(ve)}function du(t,e,n){if(ve.current!==zt)throw Error(_(168));F(ve,e),F(Ne,n)}function _d(t,e,n){var r=t.stateNode;if(e=e.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in e))throw Error(_(108,Rf(t)||"Unknown",s));return Y({},n,r)}function ei(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||zt,sn=ve.current,F(ve,t),F(Ne,Ne.current),!0}function hu(t,e,n){var r=t.stateNode;if(!r)throw Error(_(169));n?(t=_d(t,e,sn),r.__reactInternalMemoizedMergedChildContext=t,V(Ne),V(ve),F(ve,t)):V(Ne),F(Ne,n)}var dt=null,Ei=!1,so=!1;function kd(t){dt===null?dt=[t]:dt.push(t)}function Jp(t){Ei=!0,kd(t)}function Wt(){if(!so&&dt!==null){so=!0;var t=0,e=M;try{var n=dt;for(M=1;t>=o,s-=o,ht=1<<32-Je(e)+s|n<C?(B=j,j=null):B=j.sibling;var $=f(v,j,m[C],w);if($===null){j===null&&(j=B);break}t&&j&&$.alternate===null&&e(v,j),p=i($,p,C),k===null?S=$:k.sibling=$,k=$,j=B}if(C===m.length)return n(v,j),q&&Gt(v,C),S;if(j===null){for(;CC?(B=j,j=null):B=j.sibling;var ge=f(v,j,$.value,w);if(ge===null){j===null&&(j=B);break}t&&j&&ge.alternate===null&&e(v,j),p=i(ge,p,C),k===null?S=ge:k.sibling=ge,k=ge,j=B}if($.done)return n(v,j),q&&Gt(v,C),S;if(j===null){for(;!$.done;C++,$=m.next())$=h(v,$.value,w),$!==null&&(p=i($,p,C),k===null?S=$:k.sibling=$,k=$);return q&&Gt(v,C),S}for(j=r(v,j);!$.done;C++,$=m.next())$=g(j,v,C,$.value,w),$!==null&&(t&&$.alternate!==null&&j.delete($.key===null?C:$.key),p=i($,p,C),k===null?S=$:k.sibling=$,k=$);return t&&j.forEach(function(Ze){return e(v,Ze)}),q&&Gt(v,C),S}function E(v,p,m,w){if(typeof m=="object"&&m!==null&&m.type===Nn&&m.key===null&&(m=m.props.children),typeof m=="object"&&m!==null){switch(m.$$typeof){case hs:e:{for(var S=m.key,k=p;k!==null;){if(k.key===S){if(S=m.type,S===Nn){if(k.tag===7){n(v,k.sibling),p=s(k,m.props.children),p.return=v,v=p;break e}}else if(k.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===jt&&mu(S)===k.type){n(v,k.sibling),p=s(k,m.props),p.ref=dr(v,k,m),p.return=v,v=p;break e}n(v,k);break}else e(v,k);k=k.sibling}m.type===Nn?(p=nn(m.props.children,v.mode,w,m.key),p.return=v,v=p):(w=Ws(m.type,m.key,m.props,null,v.mode,w),w.ref=dr(v,p,m),w.return=v,v=w)}return o(v);case bn:e:{for(k=m.key;p!==null;){if(p.key===k)if(p.tag===4&&p.stateNode.containerInfo===m.containerInfo&&p.stateNode.implementation===m.implementation){n(v,p.sibling),p=s(p,m.children||[]),p.return=v,v=p;break e}else{n(v,p);break}else e(v,p);p=p.sibling}p=fo(m,v.mode,w),p.return=v,v=p}return o(v);case jt:return k=m._init,E(v,p,k(m._payload),w)}if(gr(m))return y(v,p,m,w);if(or(m))return x(v,p,m,w);Ss(v,m)}return typeof m=="string"&&m!==""||typeof m=="number"?(m=""+m,p!==null&&p.tag===6?(n(v,p.sibling),p=s(p,m),p.return=v,v=p):(n(v,p),p=ho(m,v.mode,w),p.return=v,v=p),o(v)):n(v,p)}return E}var Qn=bd(!0),Nd=bd(!1),ri=Bt(null),si=null,Ln=null,Xa=null;function Za(){Xa=Ln=si=null}function el(t){var e=ri.current;V(ri),t._currentValue=e}function ea(t,e,n){for(;t!==null;){var r=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,r!==null&&(r.childLanes|=e)):r!==null&&(r.childLanes&e)!==e&&(r.childLanes|=e),t===n)break;t=t.return}}function Wn(t,e){si=t,Xa=Ln=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(Ee=!0),t.firstContext=null)}function Fe(t){var e=t._currentValue;if(Xa!==t)if(t={context:t,memoizedValue:e,next:null},Ln===null){if(si===null)throw Error(_(308));Ln=t,si.dependencies={lanes:0,firstContext:t}}else Ln=Ln.next=t;return e}var Zt=null;function tl(t){Zt===null?Zt=[t]:Zt.push(t)}function Cd(t,e,n,r){var s=e.interleaved;return s===null?(n.next=n,tl(e)):(n.next=s.next,s.next=n),e.interleaved=n,gt(t,r)}function gt(t,e){t.lanes|=e;var n=t.alternate;for(n!==null&&(n.lanes|=e),n=t,t=t.return;t!==null;)t.childLanes|=e,n=t.alternate,n!==null&&(n.childLanes|=e),n=t,t=t.return;return n.tag===3?n.stateNode:null}var Et=!1;function nl(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Td(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,effects:t.effects})}function pt(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function Lt(t,e,n){var r=t.updateQueue;if(r===null)return null;if(r=r.shared,D&2){var s=r.pending;return s===null?e.next=e:(e.next=s.next,s.next=e),r.pending=e,gt(t,n)}return s=r.interleaved,s===null?(e.next=e,tl(r)):(e.next=s.next,s.next=e),r.interleaved=e,gt(t,n)}function Us(t,e,n){if(e=e.updateQueue,e!==null&&(e=e.shared,(n&4194240)!==0)){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,Fa(t,n)}}function vu(t,e){var n=t.updateQueue,r=t.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=e:i=i.next=e}else s=i=e;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:r.shared,effects:r.effects},t.updateQueue=n;return}t=n.lastBaseUpdate,t===null?n.firstBaseUpdate=e:t.next=e,n.lastBaseUpdate=e}function ii(t,e,n,r){var s=t.updateQueue;Et=!1;var i=s.firstBaseUpdate,o=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var l=a,c=l.next;l.next=null,o===null?i=c:o.next=c,o=l;var d=t.alternate;d!==null&&(d=d.updateQueue,a=d.lastBaseUpdate,a!==o&&(a===null?d.firstBaseUpdate=c:a.next=c,d.lastBaseUpdate=l))}if(i!==null){var h=s.baseState;o=0,d=c=l=null,a=i;do{var f=a.lane,g=a.eventTime;if((r&f)===f){d!==null&&(d=d.next={eventTime:g,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var y=t,x=a;switch(f=e,g=n,x.tag){case 1:if(y=x.payload,typeof y=="function"){h=y.call(g,h,f);break e}h=y;break e;case 3:y.flags=y.flags&-65537|128;case 0:if(y=x.payload,f=typeof y=="function"?y.call(g,h,f):y,f==null)break e;h=Y({},h,f);break e;case 2:Et=!0}}a.callback!==null&&a.lane!==0&&(t.flags|=64,f=s.effects,f===null?s.effects=[a]:f.push(a))}else g={eventTime:g,lane:f,tag:a.tag,payload:a.payload,callback:a.callback,next:null},d===null?(c=d=g,l=h):d=d.next=g,o|=f;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;f=a,a=f.next,f.next=null,s.lastBaseUpdate=f,s.shared.pending=null}}while(!0);if(d===null&&(l=h),s.baseState=l,s.firstBaseUpdate=c,s.lastBaseUpdate=d,e=s.shared.interleaved,e!==null){s=e;do o|=s.lane,s=s.next;while(s!==e)}else i===null&&(s.shared.lanes=0);ln|=o,t.lanes=o,t.memoizedState=h}}function gu(t,e,n){if(t=e.effects,e.effects=null,t!==null)for(e=0;en?n:4,t(!0);var r=oo.transition;oo.transition={};try{t(!1),e()}finally{M=n,oo.transition=r}}function qd(){return Be().memoizedState}function em(t,e,n){var r=Ut(t);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Kd(t))Gd(e,n);else if(n=Cd(t,e,n,r),n!==null){var s=xe();Ye(n,t,r,s),Qd(n,e,r)}}function tm(t,e,n){var r=Ut(t),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Kd(t))Gd(e,s);else{var i=t.alternate;if(t.lanes===0&&(i===null||i.lanes===0)&&(i=e.lastRenderedReducer,i!==null))try{var o=e.lastRenderedState,a=i(o,n);if(s.hasEagerState=!0,s.eagerState=a,Xe(a,o)){var l=e.interleaved;l===null?(s.next=s,tl(e)):(s.next=l.next,l.next=s),e.interleaved=s;return}}catch{}finally{}n=Cd(t,e,s,r),n!==null&&(s=xe(),Ye(n,t,r,s),Qd(n,e,r))}}function Kd(t){var e=t.alternate;return t===J||e!==null&&e===J}function Gd(t,e){br=ai=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function Qd(t,e,n){if(n&4194240){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,Fa(t,n)}}var li={readContext:Fe,useCallback:he,useContext:he,useEffect:he,useImperativeHandle:he,useInsertionEffect:he,useLayoutEffect:he,useMemo:he,useReducer:he,useRef:he,useState:he,useDebugValue:he,useDeferredValue:he,useTransition:he,useMutableSource:he,useSyncExternalStore:he,useId:he,unstable_isNewReconciler:!1},nm={readContext:Fe,useCallback:function(t,e){return nt().memoizedState=[t,e===void 0?null:e],t},useContext:Fe,useEffect:wu,useImperativeHandle:function(t,e,n){return n=n!=null?n.concat([t]):null,Ms(4194308,4,Fd.bind(null,e,t),n)},useLayoutEffect:function(t,e){return Ms(4194308,4,t,e)},useInsertionEffect:function(t,e){return Ms(4,2,t,e)},useMemo:function(t,e){var n=nt();return e=e===void 0?null:e,t=t(),n.memoizedState=[t,e],t},useReducer:function(t,e,n){var r=nt();return e=n!==void 0?n(e):e,r.memoizedState=r.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},r.queue=t,t=t.dispatch=em.bind(null,J,t),[r.memoizedState,t]},useRef:function(t){var e=nt();return t={current:t},e.memoizedState=t},useState:yu,useDebugValue:cl,useDeferredValue:function(t){return nt().memoizedState=t},useTransition:function(){var t=yu(!1),e=t[0];return t=Zp.bind(null,t[1]),nt().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,n){var r=J,s=nt();if(q){if(n===void 0)throw Error(_(407));n=n()}else{if(n=e(),le===null)throw Error(_(349));an&30||Rd(r,e,n)}s.memoizedState=n;var i={value:n,getSnapshot:e};return s.queue=i,wu(Ld.bind(null,r,i,t),[t]),r.flags|=2048,Gr(9,$d.bind(null,r,i,n,e),void 0,null),n},useId:function(){var t=nt(),e=le.identifierPrefix;if(q){var n=ft,r=ht;n=(r&~(1<<32-Je(r)-1)).toString(32)+n,e=":"+e+"R"+n,n=qr++,0<\/script>",t=t.removeChild(t.firstChild)):typeof r.is=="string"?t=o.createElement(n,{is:r.is}):(t=o.createElement(n),n==="select"&&(o=t,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):t=o.createElementNS(t,n),t[st]=e,t[Wr]=r,ih(t,e,!1,!1),e.stateNode=t;e:{switch(o=Io(n,r),n){case"dialog":W("cancel",t),W("close",t),s=r;break;case"iframe":case"object":case"embed":W("load",t),s=r;break;case"video":case"audio":for(s=0;sXn&&(e.flags|=128,r=!0,hr(i,!1),e.lanes=4194304)}else{if(!r)if(t=oi(o),t!==null){if(e.flags|=128,r=!0,n=t.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),hr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!q)return fe(e),null}else 2*ee()-i.renderingStartTime>Xn&&n!==1073741824&&(e.flags|=128,r=!0,hr(i,!1),e.lanes=4194304);i.isBackwards?(o.sibling=e.child,e.child=o):(n=i.last,n!==null?n.sibling=o:e.child=o,i.last=o)}return i.tail!==null?(e=i.tail,i.rendering=e,i.tail=e.sibling,i.renderingStartTime=ee(),e.sibling=null,n=G.current,F(G,r?n&1|2:n&1),e):(fe(e),null);case 22:case 23:return vl(),r=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==r&&(e.flags|=8192),r&&e.mode&1?Pe&1073741824&&(fe(e),e.subtreeFlags&6&&(e.flags|=8192)):fe(e),null;case 24:return null;case 25:return null}throw Error(_(156,e.tag))}function cm(t,e){switch(Ja(e),e.tag){case 1:return Ce(e.type)&&Zs(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return Jn(),V(Ne),V(ve),il(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return sl(e),null;case 13:if(V(G),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(_(340));Gn()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return V(G),null;case 4:return Jn(),null;case 10:return el(e.type._context),null;case 22:case 23:return vl(),null;case 24:return null;default:return null}}var Es=!1,me=!1,dm=typeof WeakSet=="function"?WeakSet:Set,N=null;function In(t,e){var n=t.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){X(t,e,r)}else n.current=null}function ua(t,e,n){try{n()}catch(r){X(t,e,r)}}var Pu=!1;function hm(t,e){if(qo=Qs,t=hd(),Ga(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else e:{n=(n=t.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,c=0,d=0,h=t,f=null;t:for(;;){for(var g;h!==n||s!==0&&h.nodeType!==3||(a=o+s),h!==i||r!==0&&h.nodeType!==3||(l=o+r),h.nodeType===3&&(o+=h.nodeValue.length),(g=h.firstChild)!==null;)f=h,h=g;for(;;){if(h===t)break t;if(f===n&&++c===s&&(a=o),f===i&&++d===r&&(l=o),(g=h.nextSibling)!==null)break;h=f,f=h.parentNode}h=g}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(Ko={focusedElem:t,selectionRange:n},Qs=!1,N=e;N!==null;)if(e=N,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,N=t;else for(;N!==null;){e=N;try{var y=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(y!==null){var x=y.memoizedProps,E=y.memoizedState,v=e.stateNode,p=v.getSnapshotBeforeUpdate(e.elementType===e.type?x:qe(e.type,x),E);v.__reactInternalSnapshotBeforeUpdate=p}break;case 3:var m=e.stateNode.containerInfo;m.nodeType===1?m.textContent="":m.nodeType===9&&m.documentElement&&m.removeChild(m.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(_(163))}}catch(w){X(e,e.return,w)}if(t=e.sibling,t!==null){t.return=e.return,N=t;break}N=e.return}return y=Pu,Pu=!1,y}function Nr(t,e,n){var r=e.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&t)===t){var i=s.destroy;s.destroy=void 0,i!==void 0&&ua(e,n,i)}s=s.next}while(s!==r)}}function Ci(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var n=e=e.next;do{if((n.tag&t)===t){var r=n.create;n.destroy=r()}n=n.next}while(n!==e)}}function ca(t){var e=t.ref;if(e!==null){var n=t.stateNode;switch(t.tag){case 5:t=n;break;default:t=n}typeof e=="function"?e(t):e.current=t}}function lh(t){var e=t.alternate;e!==null&&(t.alternate=null,lh(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[st],delete e[Wr],delete e[Jo],delete e[Gp],delete e[Qp])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function uh(t){return t.tag===5||t.tag===3||t.tag===4}function Ou(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||uh(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function da(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.nodeType===8?n.parentNode.insertBefore(t,e):n.insertBefore(t,e):(n.nodeType===8?(e=n.parentNode,e.insertBefore(t,n)):(e=n,e.appendChild(t)),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=Xs));else if(r!==4&&(t=t.child,t!==null))for(da(t,e,n),t=t.sibling;t!==null;)da(t,e,n),t=t.sibling}function ha(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(r!==4&&(t=t.child,t!==null))for(ha(t,e,n),t=t.sibling;t!==null;)ha(t,e,n),t=t.sibling}var ue=null,Ke=!1;function _t(t,e,n){for(n=n.child;n!==null;)ch(t,e,n),n=n.sibling}function ch(t,e,n){if(it&&typeof it.onCommitFiberUnmount=="function")try{it.onCommitFiberUnmount(xi,n)}catch{}switch(n.tag){case 5:me||In(n,e);case 6:var r=ue,s=Ke;ue=null,_t(t,e,n),ue=r,Ke=s,ue!==null&&(Ke?(t=ue,n=n.stateNode,t.nodeType===8?t.parentNode.removeChild(n):t.removeChild(n)):ue.removeChild(n.stateNode));break;case 18:ue!==null&&(Ke?(t=ue,n=n.stateNode,t.nodeType===8?ro(t.parentNode,n):t.nodeType===1&&ro(t,n),Dr(t)):ro(ue,n.stateNode));break;case 4:r=ue,s=Ke,ue=n.stateNode.containerInfo,Ke=!0,_t(t,e,n),ue=r,Ke=s;break;case 0:case 11:case 14:case 15:if(!me&&(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)&&ua(n,e,o),s=s.next}while(s!==r)}_t(t,e,n);break;case 1:if(!me&&(In(n,e),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){X(n,e,a)}_t(t,e,n);break;case 21:_t(t,e,n);break;case 22:n.mode&1?(me=(r=me)||n.memoizedState!==null,_t(t,e,n),me=r):_t(t,e,n);break;default:_t(t,e,n)}}function Au(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var n=t.stateNode;n===null&&(n=t.stateNode=new dm),e.forEach(function(r){var s=_m.bind(null,t,r);n.has(r)||(n.add(r),r.then(s,s))})}}function He(t,e){var n=e.deletions;if(n!==null)for(var r=0;rs&&(s=o),r&=~i}if(r=s,r=ee()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*pm(r/1960))-r,10t?16:t,Pt===null)var r=!1;else{if(t=Pt,Pt=null,di=0,D&6)throw Error(_(331));var s=D;for(D|=4,N=t.current;N!==null;){var i=N,o=i.child;if(N.flags&16){var a=i.deletions;if(a!==null){for(var l=0;lee()-pl?tn(t,0):fl|=n),Te(t,e)}function yh(t,e){e===0&&(t.mode&1?(e=vs,vs<<=1,!(vs&130023424)&&(vs=4194304)):e=1);var n=xe();t=gt(t,e),t!==null&&(Zr(t,e,n),Te(t,n))}function xm(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),yh(t,n)}function _m(t,e){var n=0;switch(t.tag){case 13:var r=t.stateNode,s=t.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=t.stateNode;break;default:throw Error(_(314))}r!==null&&r.delete(e),yh(t,n)}var wh;wh=function(t,e,n){if(t!==null)if(t.memoizedProps!==e.pendingProps||Ne.current)Ee=!0;else{if(!(t.lanes&n)&&!(e.flags&128))return Ee=!1,lm(t,e,n);Ee=!!(t.flags&131072)}else Ee=!1,q&&e.flags&1048576&&Sd(e,ni,e.index);switch(e.lanes=0,e.tag){case 2:var r=e.type;zs(t,e),t=e.pendingProps;var s=Kn(e,ve.current);Wn(e,n),s=al(null,e,r,t,s,n);var i=ll();return e.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,Ce(r)?(i=!0,ei(e)):i=!1,e.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,nl(e),s.updater=Ni,e.stateNode=s,s._reactInternals=e,na(e,r,t,n),e=ia(null,e,r,!0,i,n)):(e.tag=0,q&&i&&Qa(e),we(null,e,s,n),e=e.child),e;case 16:r=e.elementType;e:{switch(zs(t,e),t=e.pendingProps,s=r._init,r=s(r._payload),e.type=r,s=e.tag=Sm(r),t=qe(r,t),s){case 0:e=sa(null,e,r,t,n);break e;case 1:e=Nu(null,e,r,t,n);break e;case 11:e=Eu(null,e,r,t,n);break e;case 14:e=bu(null,e,r,qe(r.type,t),n);break e}throw Error(_(306,r,""))}return e;case 0:return r=e.type,s=e.pendingProps,s=e.elementType===r?s:qe(r,s),sa(t,e,r,s,n);case 1:return r=e.type,s=e.pendingProps,s=e.elementType===r?s:qe(r,s),Nu(t,e,r,s,n);case 3:e:{if(nh(e),t===null)throw Error(_(387));r=e.pendingProps,i=e.memoizedState,s=i.element,Td(t,e),ii(e,r,null,n);var o=e.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},e.updateQueue.baseState=i,e.memoizedState=i,e.flags&256){s=Yn(Error(_(423)),e),e=Cu(t,e,r,n,s);break e}else if(r!==s){s=Yn(Error(_(424)),e),e=Cu(t,e,r,n,s);break e}else for(Oe=$t(e.stateNode.containerInfo.firstChild),Ae=e,q=!0,Qe=null,n=Nd(e,null,r,n),e.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Gn(),r===s){e=yt(t,e,n);break e}we(t,e,r,n)}e=e.child}return e;case 5:return Pd(e),t===null&&Zo(e),r=e.type,s=e.pendingProps,i=t!==null?t.memoizedProps:null,o=s.children,Go(r,s)?o=null:i!==null&&Go(r,i)&&(e.flags|=32),th(t,e),we(t,e,o,n),e.child;case 6:return t===null&&Zo(e),null;case 13:return rh(t,e,n);case 4:return rl(e,e.stateNode.containerInfo),r=e.pendingProps,t===null?e.child=Qn(e,null,r,n):we(t,e,r,n),e.child;case 11:return r=e.type,s=e.pendingProps,s=e.elementType===r?s:qe(r,s),Eu(t,e,r,s,n);case 7:return we(t,e,e.pendingProps,n),e.child;case 8:return we(t,e,e.pendingProps.children,n),e.child;case 12:return we(t,e,e.pendingProps.children,n),e.child;case 10:e:{if(r=e.type._context,s=e.pendingProps,i=e.memoizedProps,o=s.value,F(ri,r._currentValue),r._currentValue=o,i!==null)if(Xe(i.value,o)){if(i.children===s.children&&!Ne.current){e=yt(t,e,n);break e}}else for(i=e.child,i!==null&&(i.return=e);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=pt(-1,n&-n),l.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var d=c.pending;d===null?l.next=l:(l.next=d.next,d.next=l),c.pending=l}}i.lanes|=n,l=i.alternate,l!==null&&(l.lanes|=n),ea(i.return,n,e),a.lanes|=n;break}l=l.next}}else if(i.tag===10)o=i.type===e.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(_(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),ea(o,n,e),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===e){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}we(t,e,s.children,n),e=e.child}return e;case 9:return s=e.type,r=e.pendingProps.children,Wn(e,n),s=Fe(s),r=r(s),e.flags|=1,we(t,e,r,n),e.child;case 14:return r=e.type,s=qe(r,e.pendingProps),s=qe(r.type,s),bu(t,e,r,s,n);case 15:return Zd(t,e,e.type,e.pendingProps,n);case 17:return r=e.type,s=e.pendingProps,s=e.elementType===r?s:qe(r,s),zs(t,e),e.tag=1,Ce(r)?(t=!0,ei(e)):t=!1,Wn(e,n),Jd(e,r,s),na(e,r,s,n),ia(null,e,r,!0,t,n);case 19:return sh(t,e,n);case 22:return eh(t,e,n)}throw Error(_(156,e.tag))};function xh(t,e){return Kc(t,e)}function km(t,e,n,r){this.tag=t,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,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 De(t,e,n,r){return new km(t,e,n,r)}function yl(t){return t=t.prototype,!(!t||!t.isReactComponent)}function Sm(t){if(typeof t=="function")return yl(t)?1:0;if(t!=null){if(t=t.$$typeof,t===Ua)return 11;if(t===Da)return 14}return 2}function Dt(t,e){var n=t.alternate;return n===null?(n=De(t.tag,e,t.key,t.mode),n.elementType=t.elementType,n.type=t.type,n.stateNode=t.stateNode,n.alternate=t,t.alternate=n):(n.pendingProps=e,n.type=t.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=t.flags&14680064,n.childLanes=t.childLanes,n.lanes=t.lanes,n.child=t.child,n.memoizedProps=t.memoizedProps,n.memoizedState=t.memoizedState,n.updateQueue=t.updateQueue,e=t.dependencies,n.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},n.sibling=t.sibling,n.index=t.index,n.ref=t.ref,n}function Ws(t,e,n,r,s,i){var o=2;if(r=t,typeof t=="function")yl(t)&&(o=1);else if(typeof t=="string")o=5;else e:switch(t){case Nn:return nn(n.children,s,i,e);case Ia:o=8,s|=8;break;case bo:return t=De(12,n,e,s|2),t.elementType=bo,t.lanes=i,t;case No:return t=De(13,n,e,s),t.elementType=No,t.lanes=i,t;case Co:return t=De(19,n,e,s),t.elementType=Co,t.lanes=i,t;case Pc:return Pi(n,s,i,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case Cc:o=10;break e;case Tc:o=9;break e;case Ua:o=11;break e;case Da:o=14;break e;case jt:o=16,r=null;break e}throw Error(_(130,t==null?t:typeof t,""))}return e=De(o,n,e,s),e.elementType=t,e.type=r,e.lanes=i,e}function nn(t,e,n,r){return t=De(7,t,r,e),t.lanes=n,t}function Pi(t,e,n,r){return t=De(22,t,r,e),t.elementType=Pc,t.lanes=n,t.stateNode={isHidden:!1},t}function ho(t,e,n){return t=De(6,t,null,e),t.lanes=n,t}function fo(t,e,n){return e=De(4,t.children!==null?t.children:[],t.key,e),e.lanes=n,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function jm(t,e,n,r,s){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=qi(0),this.expirationTimes=qi(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=qi(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function wl(t,e,n,r,s,i,o,a,l){return t=new jm(t,e,n,a,l),e===1?(e=1,i===!0&&(e|=8)):e=0,i=De(3,null,null,e),t.current=i,i.stateNode=t,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},nl(i),t}function Em(t,e,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(jh)}catch(t){console.error(t)}}jh(),jc.exports=$e;var Pm=jc.exports,Eh,zu=Pm;Eh=zu.createRoot,zu.hydrateRoot;const Om="modulepreload",Am=function(t){return"/"+t},Fu={},rs=function(e,n,r){let s=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));s=Promise.allSettled(n.map(l=>{if(l=Am(l),l in Fu)return;Fu[l]=!0;const c=l.endsWith(".css"),d=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${d}`))return;const h=document.createElement("link");if(h.rel=c?"stylesheet":Om,c||(h.as="script"),h.crossOrigin="",h.href=l,a&&h.setAttribute("nonce",a),document.head.appendChild(h),c)return new Promise((f,g)=>{h.addEventListener("load",f),h.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return e().catch(i)})},Rm=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...n)=>rs(async()=>{const{default:r}=await Promise.resolve().then(()=>rr);return{default:r}},void 0).then(({default:r})=>r(...n)):e=fetch,(...n)=>e(...n)};class Sl extends Error{constructor(e,n="FunctionsError",r){super(e),this.name=n,this.context=r}}class $m extends Sl{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Bu extends Sl{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Wu extends Sl{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var ga;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(ga||(ga={}));var Lm=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(d){try{c(r.next(d))}catch(h){o(h)}}function l(d){try{c(r.throw(d))}catch(h){o(h)}}function c(d){d.done?i(d.value):s(d.value).then(a,l)}c((r=r.apply(t,e||[])).next())})};class Im{constructor(e,{headers:n={},customFetch:r,region:s=ga.Any}={}){this.url=e,this.headers=n,this.region=s,this.fetch=Rm(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,n={}){var r;return Lm(this,void 0,void 0,function*(){try{const{headers:s,method:i,body:o}=n;let a={},{region:l}=n;l||(l=this.region);const c=new URL(`${this.url}/${e}`);l&&l!=="any"&&(a["x-region"]=l,c.searchParams.set("forceFunctionRegion",l));let d;o&&(s&&!Object.prototype.hasOwnProperty.call(s,"Content-Type")||!s)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",d=o):typeof o=="string"?(a["Content-Type"]="text/plain",d=o):typeof FormData<"u"&&o instanceof FormData?d=o:(a["Content-Type"]="application/json",d=JSON.stringify(o)));const h=yield this.fetch(c.toString(),{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),s),body:d}).catch(x=>{throw new $m(x)}),f=h.headers.get("x-relay-error");if(f&&f==="true")throw new Bu(h);if(!h.ok)throw new Wu(h);let g=((r=h.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),y;return g==="application/json"?y=yield h.json():g==="application/octet-stream"?y=yield h.blob():g==="text/event-stream"?y=h:g==="multipart/form-data"?y=yield h.formData():y=yield h.text(),{data:y,error:null,response:h}}catch(s){return{data:null,error:s,response:s instanceof Wu||s instanceof Bu?s.context:void 0}}})}}var je={},jl={},Li={},ss={},Ii={},Ui={},Um=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},Zn=Um();const Dm=Zn.fetch,bh=Zn.fetch.bind(Zn),Nh=Zn.Headers,Mm=Zn.Request,zm=Zn.Response,rr=Object.freeze(Object.defineProperty({__proto__:null,Headers:Nh,Request:Mm,Response:zm,default:bh,fetch:Dm},Symbol.toStringTag,{value:"Module"})),Fm=rf(rr);var Di={};Object.defineProperty(Di,"__esModule",{value:!0});let Bm=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};Di.default=Bm;var Ch=ze&&ze.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ui,"__esModule",{value:!0});const Wm=Ch(Fm),Hm=Ch(Di);let Vm=class{constructor(e){var 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=(n=e.shouldThrowOnError)!==null&&n!==void 0?n:!1,this.signal=e.signal,this.isMaybeSingle=(r=e.isMaybeSingle)!==null&&r!==void 0?r:!1,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=Wm.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,n){return this.headers=new Headers(this.headers),this.headers.set(e,n),this}then(e,n){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=>{var o,a,l,c;let d=null,h=null,f=null,g=i.status,y=i.statusText;if(i.ok){if(this.method!=="HEAD"){const p=await i.text();p===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((o=this.headers.get("Accept"))===null||o===void 0)&&o.includes("application/vnd.pgrst.plan+text"))?h=p:h=JSON.parse(p))}const E=(a=this.headers.get("Prefer"))===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),v=(l=i.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");E&&v&&v.length>1&&(f=parseInt(v[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(h)&&(h.length>1?(d={code:"PGRST116",details:`Results contain ${h.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},h=null,f=null,g=406,y="Not Acceptable"):h.length===1?h=h[0]:h=null)}else{const E=await i.text();try{d=JSON.parse(E),Array.isArray(d)&&i.status===404&&(h=[],d=null,g=200,y="OK")}catch{i.status===404&&E===""?(g=204,y="No Content"):d={message:E}}if(d&&this.isMaybeSingle&&(!((c=d==null?void 0:d.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,g=200,y="OK"),d&&this.shouldThrowOnError)throw new Hm.default(d)}return{error:d,data:h,count:f,status:g,statusText:y}});return this.shouldThrowOnError||(s=s.catch(i=>{var o,a,l;return{error:{message:`${(o=i==null?void 0:i.name)!==null&&o!==void 0?o:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(a=i==null?void 0:i.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(l=i==null?void 0:i.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),s.then(e,n)}returns(){return this}overrideTypes(){return this}};Ui.default=Vm;var qm=ze&&ze.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ii,"__esModule",{value:!0});const Km=qm(Ui);let Gm=class extends Km.default{select(e){let n=!1;const r=(e??"*").split("").map(s=>/\s/.test(s)&&!n?"":(s==='"'&&(n=!n),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:n=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){const o=i?`${i}.order`:"order",a=this.url.searchParams.get(o);return this.url.searchParams.set(o,`${a?`${a},`:""}${e}.${n?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:n,referencedTable:r=n}={}){const s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,n,{foreignTable:r,referencedTable:s=r}={}){const i=typeof s>"u"?"offset":`${s}.offset`,o=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(o,`${n-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:n=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:o="text"}={}){var a;const l=[e?"analyze":null,n?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${o}; for="${c}"; options=${l};`),o==="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}};Ii.default=Gm;var Qm=ze&&ze.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ss,"__esModule",{value:!0});const Jm=Qm(Ii);let Ym=class extends Jm.default{eq(e,n){return this.url.searchParams.append(e,`eq.${n}`),this}neq(e,n){return this.url.searchParams.append(e,`neq.${n}`),this}gt(e,n){return this.url.searchParams.append(e,`gt.${n}`),this}gte(e,n){return this.url.searchParams.append(e,`gte.${n}`),this}lt(e,n){return this.url.searchParams.append(e,`lt.${n}`),this}lte(e,n){return this.url.searchParams.append(e,`lte.${n}`),this}like(e,n){return this.url.searchParams.append(e,`like.${n}`),this}likeAllOf(e,n){return this.url.searchParams.append(e,`like(all).{${n.join(",")}}`),this}likeAnyOf(e,n){return this.url.searchParams.append(e,`like(any).{${n.join(",")}}`),this}ilike(e,n){return this.url.searchParams.append(e,`ilike.${n}`),this}ilikeAllOf(e,n){return this.url.searchParams.append(e,`ilike(all).{${n.join(",")}}`),this}ilikeAnyOf(e,n){return this.url.searchParams.append(e,`ilike(any).{${n.join(",")}}`),this}is(e,n){return this.url.searchParams.append(e,`is.${n}`),this}in(e,n){const r=Array.from(new Set(n)).map(s=>typeof s=="string"&&new RegExp("[,()]").test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,n){return typeof n=="string"?this.url.searchParams.append(e,`cs.${n}`):Array.isArray(n)?this.url.searchParams.append(e,`cs.{${n.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(n)}`),this}containedBy(e,n){return typeof n=="string"?this.url.searchParams.append(e,`cd.${n}`):Array.isArray(n)?this.url.searchParams.append(e,`cd.{${n.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(n)}`),this}rangeGt(e,n){return this.url.searchParams.append(e,`sr.${n}`),this}rangeGte(e,n){return this.url.searchParams.append(e,`nxl.${n}`),this}rangeLt(e,n){return this.url.searchParams.append(e,`sl.${n}`),this}rangeLte(e,n){return this.url.searchParams.append(e,`nxr.${n}`),this}rangeAdjacent(e,n){return this.url.searchParams.append(e,`adj.${n}`),this}overlaps(e,n){return typeof n=="string"?this.url.searchParams.append(e,`ov.${n}`):this.url.searchParams.append(e,`ov.{${n.join(",")}}`),this}textSearch(e,n,{config:r,type:s}={}){let i="";s==="plain"?i="pl":s==="phrase"?i="ph":s==="websearch"&&(i="w");const o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${o}.${n}`),this}match(e){return Object.entries(e).forEach(([n,r])=>{this.url.searchParams.append(n,`eq.${r}`)}),this}not(e,n,r){return this.url.searchParams.append(e,`not.${n}.${r}`),this}or(e,{foreignTable:n,referencedTable:r=n}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,n,r){return this.url.searchParams.append(e,`${n}.${r}`),this}};ss.default=Ym;var Xm=ze&&ze.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Li,"__esModule",{value:!0});const pr=Xm(ss);let Zm=class{constructor(e,{headers:n={},schema:r,fetch:s}){this.url=e,this.headers=new Headers(n),this.schema=r,this.fetch=s}select(e,{head:n=!1,count:r}={}){const s=n?"HEAD":"GET";let i=!1;const o=(e??"*").split("").map(a=>/\s/.test(a)&&!i?"":(a==='"'&&(i=!i),a)).join("");return this.url.searchParams.set("select",o),r&&this.headers.append("Prefer",`count=${r}`),new pr.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(e,{count:n,defaultToNull:r=!0}={}){var s;const i="POST";if(n&&this.headers.append("Prefer",`count=${n}`),r||this.headers.append("Prefer","missing=default"),Array.isArray(e)){const o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){const a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new pr.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch})}upsert(e,{onConflict:n,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){var o;const a="POST";if(this.headers.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),n!==void 0&&this.url.searchParams.set("on_conflict",n),s&&this.headers.append("Prefer",`count=${s}`),i||this.headers.append("Prefer","missing=default"),Array.isArray(e)){const l=e.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(l.length>0){const c=[...new Set(l)].map(d=>`"${d}"`);this.url.searchParams.set("columns",c.join(","))}}return new pr.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}update(e,{count:n}={}){var r;const s="PATCH";return n&&this.headers.append("Prefer",`count=${n}`),new pr.default({method:s,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch})}delete({count:e}={}){var n;const r="DELETE";return e&&this.headers.append("Prefer",`count=${e}`),new pr.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch})}};Li.default=Zm;var Th=ze&&ze.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(jl,"__esModule",{value:!0});const ev=Th(Li),tv=Th(ss);let nv=class Ph{constructor(e,{headers:n={},schema:r,fetch:s}={}){this.url=e,this.headers=new Headers(n),this.schemaName=r,this.fetch=s}from(e){const n=new URL(`${this.url}/${e}`);return new ev.default(n,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new Ph(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,n={},{head:r=!1,get:s=!1,count:i}={}){var o;let a;const l=new URL(`${this.url}/rpc/${e}`);let c;r||s?(a=r?"HEAD":"GET",Object.entries(n).filter(([h,f])=>f!==void 0).map(([h,f])=>[h,Array.isArray(f)?`{${f.join(",")}}`:`${f}`]).forEach(([h,f])=>{l.searchParams.append(h,f)})):(a="POST",c=n);const d=new Headers(this.headers);return i&&d.set("Prefer",`count=${i}`),new tv.default({method:a,url:l,headers:d,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}};jl.default=nv;var sr=ze&&ze.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(je,"__esModule",{value:!0});je.PostgrestError=je.PostgrestBuilder=je.PostgrestTransformBuilder=je.PostgrestFilterBuilder=je.PostgrestQueryBuilder=je.PostgrestClient=void 0;const Oh=sr(jl);je.PostgrestClient=Oh.default;const Ah=sr(Li);je.PostgrestQueryBuilder=Ah.default;const Rh=sr(ss);je.PostgrestFilterBuilder=Rh.default;const $h=sr(Ii);je.PostgrestTransformBuilder=$h.default;const Lh=sr(Ui);je.PostgrestBuilder=Lh.default;const Ih=sr(Di);je.PostgrestError=Ih.default;var rv=je.default={PostgrestClient:Oh.default,PostgrestQueryBuilder:Ah.default,PostgrestFilterBuilder:Rh.default,PostgrestTransformBuilder:$h.default,PostgrestBuilder:Lh.default,PostgrestError:Ih.default};const{PostgrestClient:sv,PostgrestQueryBuilder:Vy,PostgrestFilterBuilder:qy,PostgrestTransformBuilder:Ky,PostgrestBuilder:Gy,PostgrestError:Qy}=rv;class iv{static detectEnvironment(){var e;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"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if(typeof process<"u"){const n=process.versions;if(n&&n.node){const r=n.node,s=parseInt(r.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: 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 e=this.detectEnvironment();if(e.constructor)return e.constructor;let n=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(n+=` Suggested solution: ${e.workaround}`),new Error(n)}static createWebSocket(e,n){const r=this.getWebSocketConstructor();return new r(e,n)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const ov="2.15.5",av=`realtime-js/${ov}`,lv="1.0.0",ya=1e4,uv=1e3,cv=100;var Pr;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(Pr||(Pr={}));var re;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(re||(re={}));var Ge;(function(t){t.close="phx_close",t.error="phx_error",t.join="phx_join",t.reply="phx_reply",t.leave="phx_leave",t.access_token="access_token"})(Ge||(Ge={}));var wa;(function(t){t.websocket="websocket"})(wa||(wa={}));var Yt;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(Yt||(Yt={}));class dv{constructor(){this.HEADER_LENGTH=1}decode(e,n){return e.constructor===ArrayBuffer?n(this._binaryDecode(e)):n(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const n=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,n,r)}_decodeBroadcast(e,n,r){const s=n.getUint8(1),i=n.getUint8(2);let o=this.HEADER_LENGTH+2;const a=r.decode(e.slice(o,o+s));o=o+s;const l=r.decode(e.slice(o,o+i));o=o+i;const c=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:c}}}class Uh{constructor(e,n){this.callback=e,this.timerCalc=n,this.timer=void 0,this.tries=0,this.callback=e,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 z;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(z||(z={}));const Hu=(t,e,n={})=>{var r;const s=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((i,o)=>(i[o]=hv(o,t,e,s),i),{})},hv=(t,e,n,r)=>{const s=e.find(a=>a.name===t),i=s==null?void 0:s.type,o=n[t];return i&&!r.includes(i)?Dh(i,o):xa(o)},Dh=(t,e)=>{if(t.charAt(0)==="_"){const n=t.slice(1,t.length);return vv(e,n)}switch(t){case z.bool:return fv(e);case z.float4:case z.float8:case z.int2:case z.int4:case z.int8:case z.numeric:case z.oid:return pv(e);case z.json:case z.jsonb:return mv(e);case z.timestamp:return gv(e);case z.abstime:case z.date:case z.daterange:case z.int4range:case z.int8range:case z.money:case z.reltime:case z.text:case z.time:case z.timestamptz:case z.timetz:case z.tsrange:case z.tstzrange:return xa(e);default:return xa(e)}},xa=t=>t,fv=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},pv=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},mv=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch(e){return console.log(`JSON parse error: ${e}`),t}return t},vv=(t,e)=>{if(typeof t!="string")return t;const n=t.length-1,r=t[n];if(t[0]==="{"&&r==="}"){let i;const o=t.slice(1,n);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>Dh(e,a))}return t},gv=t=>typeof t=="string"?t.replace(" ","T"):t,Mh=t=>{let e=t;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")+"/api/broadcast"};class po{constructor(e,n,r={},s=ya){this.channel=e,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(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,n){var r;return this._hasReceived(e)&&n((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:n}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=n=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=n,this._matchReceive(n)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,n){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,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:e,response:n}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(n))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var Vu;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Vu||(Vu={}));class Or{constructor(e,n){this.channel=e,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=Or.syncState(this.state,s,i,o),this.pendingDiffs.forEach(l=>{this.state=Or.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=Or.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(e,n,r,s){const i=this.cloneDeep(e),o=this.transformState(n),a={},l={};return this.map(i,(c,d)=>{o[c]||(l[c]=d)}),this.map(o,(c,d)=>{const h=i[c];if(h){const f=d.map(E=>E.presence_ref),g=h.map(E=>E.presence_ref),y=d.filter(E=>g.indexOf(E.presence_ref)<0),x=h.filter(E=>f.indexOf(E.presence_ref)<0);y.length>0&&(a[c]=y),x.length>0&&(l[c]=x)}else a[c]=d}),this.syncDiff(i,{joins:a,leaves:l},r,s)}static syncDiff(e,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 c;const d=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),d.length>0){const h=e[a].map(g=>g.presence_ref),f=d.filter(g=>h.indexOf(g.presence_ref)<0);e[a].unshift(...f)}r(a,d,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;const d=l.map(h=>h.presence_ref);c=c.filter(h=>d.indexOf(h.presence_ref)<0),e[a]=c,s(a,c,l),c.length===0&&delete e[a]}),e}static map(e,n){return Object.getOwnPropertyNames(e).map(r=>n(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((n,r)=>{const s=e[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(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var qu;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(qu||(qu={}));var Ar;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Ar||(Ar={}));var ct;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(ct||(ct={}));class El{constructor(e,n={config:{}},r){this.topic=e,this.params=n,this.socket=r,this.bindings={},this.state=re.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},n.config),this.timeout=this.socket.timeout,this.joinPush=new po(this,Ge.join,this.params,this.timeout),this.rejoinTimer=new Uh(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=re.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=re.closed,this.socket._remove(this)}),this._onError(s=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,s),this.state=re.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=re.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",s=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,s),this.state=re.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Ge.reply,{},(s,i)=>{this._trigger(this._replyEventName(i),s)}),this.presence=new Or(this),this.broadcastEndpointURL=Mh(this.socket.endPoint),this.private=this.params.config.private||!1}subscribe(e,n=this.timeout){var r,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==re.closed){const{config:{broadcast:o,presence:a,private:l}}=this.params,c=(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(g=>g.filter))!==null&&s!==void 0?s:[],d=!!this.bindings[Ar.PRESENCE]&&this.bindings[Ar.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},f={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:d}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(g=>e==null?void 0:e(ct.CHANNEL_ERROR,g)),this._onClose(()=>e==null?void 0:e(ct.CLOSED)),this.updateJoinPayload(Object.assign({config:f},h)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive("ok",async({postgres_changes:g})=>{var y;if(this.socket.setAuth(),g===void 0){e==null||e(ct.SUBSCRIBED);return}else{const x=this.bindings.postgres_changes,E=(y=x==null?void 0:x.length)!==null&&y!==void 0?y:0,v=[];for(let p=0;p{this.state=re.errored,e==null||e(ct.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(g).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(ct.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,n={}){return await this.send({type:"presence",event:"track",payload:e},n.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,n,r){return this.state===re.joined&&e===Ar.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,n,r)}async send(e,n={}){var r,s;if(!this._canPush()&&e.type==="broadcast"){const{event:i,payload:o}=e,l={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(r=n.timeout)!==null&&r!==void 0?r:this.timeout);return await((s=c.body)===null||s===void 0?void 0:s.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;const c=this._push(e.type,e,n.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=re.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Ge.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{r=new po(this,Ge.leave,{},e),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(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=re.closed,this.bindings={}}async _fetchWithTimeout(e,n,r){const s=new AbortController,i=setTimeout(()=>s.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},n),{signal:s.signal}));return clearTimeout(i),o}_push(e,n,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new po(this,e,n,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>cv){const n=this.pushBuffer.shift();n&&(n.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${n.event}`,n.payload))}}_onMessage(e,n,r){return n}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,n,r){var s,i;const o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:d}=Ge;if(r&&[a,l,c,d].indexOf(o)>=0&&r!==this._joinRef())return;let f=this._onMessage(o,n,r);if(n&&!f)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(g=>{var y,x,E;return((y=g.filter)===null||y===void 0?void 0:y.event)==="*"||((E=(x=g.filter)===null||x===void 0?void 0:x.event)===null||E===void 0?void 0:E.toLocaleLowerCase())===o}).map(g=>g.callback(f,r)):(i=this.bindings[o])===null||i===void 0||i.filter(g=>{var y,x,E,v,p,m;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in g){const w=g.id,S=(y=g.filter)===null||y===void 0?void 0:y.event;return w&&((x=n.ids)===null||x===void 0?void 0:x.includes(w))&&(S==="*"||(S==null?void 0:S.toLocaleLowerCase())===((E=n.data)===null||E===void 0?void 0:E.type.toLocaleLowerCase()))}else{const w=(p=(v=g==null?void 0:g.filter)===null||v===void 0?void 0:v.event)===null||p===void 0?void 0:p.toLocaleLowerCase();return w==="*"||w===((m=n==null?void 0:n.event)===null||m===void 0?void 0:m.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===o}).map(g=>{if(typeof f=="object"&&"ids"in f){const y=f.data,{schema:x,table:E,commit_timestamp:v,type:p,errors:m}=y;f=Object.assign(Object.assign({},{schema:x,table:E,commit_timestamp:v,eventType:p,new:{},old:{},errors:m}),this._getPayloadRecords(y))}g.callback(f,r)})}_isClosed(){return this.state===re.closed}_isJoined(){return this.state===re.joined}_isJoining(){return this.state===re.joining}_isLeaving(){return this.state===re.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,n,r){const s=e.toLocaleLowerCase(),i={type:s,filter:n,callback:r};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,n){const r=e.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&&El.isEqual(s.filter,n))})),this}static isEqual(e,n){if(Object.keys(e).length!==Object.keys(n).length)return!1;for(const r in e)if(e[r]!==n[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Ge.close,{},e)}_onError(e){this._on(Ge.error,{},n=>e(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=re.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const n={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(n.new=Hu(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(n.old=Hu(e.columns,e.old_record)),n}}const mo=()=>{},Cs={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},yv=[1e3,2e3,5e3,1e4],wv=1e4,xv=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class _v{constructor(e,n){var r;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=ya,this.transport=null,this.heartbeatIntervalMs=Cs.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=mo,this.ref=0,this.reconnectTimer=null,this.logger=mo,this.conn=null,this.sendBuffer=[],this.serializer=new dv,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=s=>{let i;return s?i=s:typeof fetch>"u"?i=(...o)=>rs(async()=>{const{default:a}=await Promise.resolve().then(()=>rr);return{default:a}},void 0).then(({default:a})=>a(...o)).catch(a=>{throw new Error(`Failed to load @supabase/node-fetch: ${a.message}. This is required for HTTP requests in Node.js environments without native fetch.`)}):i=fetch,(...o)=>i(...o)},!(!((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=`${e}/${wa.websocket}`,this.httpEndpoint=Mh(e),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._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=iv.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const n=e.message;throw n.includes("Node.js")?new Error(`${n} To use Realtime in Node.js, you need to provide a WebSocket implementation: Option 1: Use Node.js 22+ which has native WebSocket support Option 2: Install and provide the "ws" package: npm install ws import ws from "ws" 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:lv}))}disconnect(e,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")},e?this.conn.close(e,n??""):this.conn.close(),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const n=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const e=await Promise.all(this.channels.map(n=>n.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,n,r){this.logger(e,n,r)}connectionState(){switch(this.conn&&this.conn.readyState){case Pr.connecting:return Yt.Connecting;case Pr.open:return Yt.Open;case Pr.closing:return Yt.Closing;default:return Yt.Closed}}isConnected(){return this.connectionState()===Yt.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,n={config:{}}){const r=`realtime:${e}`,s=this.getChannels().find(i=>i.topic===r);if(s)return s;{const i=new El(`realtime:${e}`,n,this);return this.channels.push(i),i}}push(e){const{topic:n,event:r,payload:s,ref:i}=e,o=()=>{this.encode(e,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(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;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.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,(e=this.conn)===null||e===void 0||e.close(uv,"heartbeat timeout"),setTimeout(()=>{var n;this.isConnected()||(n=this.reconnectTimer)===null||n===void 0||n.scheduleTimeout()},Cs.HEARTBEAT_TIMEOUT_FALLBACK);return}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(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let n=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));n&&(this.log("transport",`leaving duplicate topic "${e}"`),n.unsubscribe())}_remove(e){this.channels=this.channels.filter(n=>n.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,n=>{if(n.topic==="phoenix"&&n.event==="phx_reply")try{this.heartbeatCallback(n.payload.status==="ok"?"ok":"error")}catch(c){this.log("error","error in heartbeat callback",c)}n.ref&&n.ref===this.pendingHeartbeatRef&&(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(c=>c._isMember(r)).forEach(c=>c._trigger(s,i,o)),this._triggerStateCallbacks("message",n)})}_clearTimer(e){var n;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="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=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){this.conn&&(this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null),this._clearAllTimers(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=n=>{this.log("worker","worker error",n.message),this.workerRef.terminate()},this.workerRef.onmessage=n=>{n.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var n;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(n=this.reconnectTimer)===null||n===void 0||n.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(Ge.error))}_appendParams(e,n){if(Object.keys(n).length===0)return e;const r=e.match(/\?/)?"&":"?",s=new URLSearchParams(n);return`${e}${r}${s}`}_workerObjectUrl(e){let n;if(e)n=e;else{const r=new Blob([xv],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}_setConnectionState(e,n=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=n)}async _performAuth(e=null){let n;e?n=e:this.accessToken?n=await this.accessToken():n=this.accessTokenValue,this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(r=>{const s={access_token:n,version:av};n&&r.updateJoinPayload(s),r.joinedOnce&&r._isJoined()&&r._push(Ge.access_token,{access_token:n})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this.setAuth().catch(n=>{this.log("error",`error setting auth in ${e}`,n)})}_triggerStateCallbacks(e,n){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(n)}catch(s){this.log("error",`error in ${e} callback`,s)}})}catch(r){this.log("error",`error triggering ${e} callbacks`,r)}}_setupReconnectionTimer(){this.reconnectTimer=new Uh(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Cs.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var n,r,s,i,o,a,l,c,d;if(this.transport=(n=e==null?void 0:e.transport)!==null&&n!==void 0?n:null,this.timeout=(r=e==null?void 0:e.timeout)!==null&&r!==void 0?r:ya,this.heartbeatIntervalMs=(s=e==null?void 0:e.heartbeatIntervalMs)!==null&&s!==void 0?s:Cs.HEARTBEAT_INTERVAL,this.worker=(i=e==null?void 0:e.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=e==null?void 0:e.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=e==null?void 0:e.heartbeatCallback)!==null&&a!==void 0?a:mo,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(l=e==null?void 0:e.reconnectAfterMs)!==null&&l!==void 0?l:h=>yv[h-1]||wv,this.encode=(c=e==null?void 0:e.encode)!==null&&c!==void 0?c:(h,f)=>f(JSON.stringify(h)),this.decode=(d=e==null?void 0:e.decode)!==null&&d!==void 0?d:this.serializer.decode.bind(this.serializer),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}}class bl extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function se(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}class kv extends bl{constructor(e,n,r){super(e),this.name="StorageApiError",this.status=n,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class _a extends bl{constructor(e,n){super(e),this.name="StorageUnknownError",this.originalError=n}}var Sv=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(d){try{c(r.next(d))}catch(h){o(h)}}function l(d){try{c(r.throw(d))}catch(h){o(h)}}function c(d){d.done?i(d.value):s(d.value).then(a,l)}c((r=r.apply(t,e||[])).next())})};const zh=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...n)=>rs(async()=>{const{default:r}=await Promise.resolve().then(()=>rr);return{default:r}},void 0).then(({default:r})=>r(...n)):e=fetch,(...n)=>e(...n)},jv=()=>Sv(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield rs(()=>Promise.resolve().then(()=>rr),void 0)).Response:Response}),ka=t=>{if(Array.isArray(t))return t.map(n=>ka(n));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([n,r])=>{const s=n.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[s]=ka(r)}),e},Ev=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)};var hn=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(d){try{c(r.next(d))}catch(h){o(h)}}function l(d){try{c(r.throw(d))}catch(h){o(h)}}function c(d){d.done?i(d.value):s(d.value).then(a,l)}c((r=r.apply(t,e||[])).next())})};const vo=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),bv=(t,e,n)=>hn(void 0,void 0,void 0,function*(){const r=yield jv();t instanceof r&&!(n!=null&&n.noResolveJson)?t.json().then(s=>{const i=t.status||500,o=(s==null?void 0:s.statusCode)||i+"";e(new kv(vo(s),i,o))}).catch(s=>{e(new _a(vo(s),s))}):e(new _a(vo(t),t))}),Nv=(t,e,n,r)=>{const s={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"||!r?s:(Ev(r)?(s.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),s.body=JSON.stringify(r)):s.body=r,e!=null&&e.duplex&&(s.duplex=e.duplex),Object.assign(Object.assign({},s),n))};function is(t,e,n,r,s,i){return hn(this,void 0,void 0,function*(){return new Promise((o,a)=>{t(n,Nv(e,r,s,i)).then(l=>{if(!l.ok)throw l;return r!=null&&r.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>bv(l,a,r))})})}function pi(t,e,n,r){return hn(this,void 0,void 0,function*(){return is(t,"GET",e,n,r)})}function rt(t,e,n,r,s){return hn(this,void 0,void 0,function*(){return is(t,"POST",e,r,s,n)})}function Sa(t,e,n,r,s){return hn(this,void 0,void 0,function*(){return is(t,"PUT",e,r,s,n)})}function Cv(t,e,n,r){return hn(this,void 0,void 0,function*(){return is(t,"HEAD",e,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function Fh(t,e,n,r,s){return hn(this,void 0,void 0,function*(){return is(t,"DELETE",e,r,s,n)})}var ye=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(d){try{c(r.next(d))}catch(h){o(h)}}function l(d){try{c(r.throw(d))}catch(h){o(h)}}function c(d){d.done?i(d.value):s(d.value).then(a,l)}c((r=r.apply(t,e||[])).next())})};const Tv={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ku={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Pv{constructor(e,n={},r,s){this.shouldThrowOnError=!1,this.url=e,this.headers=n,this.bucketId=r,this.fetch=zh(s)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,n,r,s){return ye(this,void 0,void 0,function*(){try{let i;const o=Object.assign(Object.assign({},Ku),s);let a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",this.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",this.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(l)))),s!=null&&s.headers&&(a=Object.assign(Object.assign({},a),s.headers));const c=this._removeEmptyFolders(n),d=this._getFinalPath(c),h=yield(e=="PUT"?Sa:rt)(this.fetch,`${this.url}/object/${d}`,i,Object.assign({headers:a},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{data:{path:c,id:h.Id,fullPath:h.Key},error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(se(i))return{data:null,error:i};throw i}})}upload(e,n,r){return ye(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,n,r)})}uploadToSignedUrl(e,n,r,s){return ye(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(e),o=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",n);try{let l;const c=Object.assign({upsert:Ku.upsert},s),d=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,d["cache-control"]=`max-age=${c.cacheControl}`,d["content-type"]=c.contentType);const h=yield Sa(this.fetch,a.toString(),l,{headers:d});return{data:{path:i,fullPath:h.Key},error:null}}catch(l){if(this.shouldThrowOnError)throw l;if(se(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,n){return ye(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e);const s=Object.assign({},this.headers);n!=null&&n.upsert&&(s["x-upsert"]="true");const i=yield rt(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:s}),o=new URL(this.url+i.url),a=o.searchParams.get("token");if(!a)throw new bl("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(se(r))return{data:null,error:r};throw r}})}update(e,n,r){return ye(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,n,r)})}move(e,n,r){return ye(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:n,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(se(s))return{data:null,error:s};throw s}})}copy(e,n,r){return ye(this,void 0,void 0,function*(){try{return{data:{path:(yield rt(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:n,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers})).Key},error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(se(s))return{data:null,error:s};throw s}})}createSignedUrl(e,n,r){return ye(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=yield rt(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:n},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(se(s))return{data:null,error:s};throw s}})}createSignedUrls(e,n,r){return ye(this,void 0,void 0,function*(){try{const s=yield rt(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:n,paths:e},{headers:this.headers}),i=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:s.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${i}`):null})),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(se(s))return{data:null,error:s};throw s}})}download(e,n){return ye(this,void 0,void 0,function*(){const s=typeof(n==null?void 0:n.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((n==null?void 0:n.transform)||{}),o=i?`?${i}`:"";try{const a=this._getFinalPath(e);return{data:yield(yield pi(this.fetch,`${this.url}/${s}/${a}${o}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(this.shouldThrowOnError)throw a;if(se(a))return{data:null,error:a};throw a}})}info(e){return ye(this,void 0,void 0,function*(){const n=this._getFinalPath(e);try{const r=yield pi(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:ka(r),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(se(r))return{data:null,error:r};throw r}})}exists(e){return ye(this,void 0,void 0,function*(){const n=this._getFinalPath(e);try{return yield Cv(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(se(r)&&r instanceof _a){const s=r.originalError;if([400,404].includes(s==null?void 0:s.status))return{data:!1,error:r}}throw r}})}getPublicUrl(e,n){const r=this._getFinalPath(e),s=[],i=n!=null&&n.download?`download=${n.download===!0?"":n.download}`:"";i!==""&&s.push(i);const a=typeof(n==null?void 0:n.transform)<"u"?"render/image":"object",l=this.transformOptsToQueryString((n==null?void 0:n.transform)||{});l!==""&&s.push(l);let c=s.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${c}`)}}}remove(e){return ye(this,void 0,void 0,function*(){try{return{data:yield Fh(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(se(n))return{data:null,error:n};throw n}})}list(e,n,r){return ye(this,void 0,void 0,function*(){try{const s=Object.assign(Object.assign(Object.assign({},Tv),n),{prefix:e||""});return{data:yield rt(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(s){if(this.shouldThrowOnError)throw s;if(se(s))return{data:null,error:s};throw s}})}listV2(e,n){return ye(this,void 0,void 0,function*(){try{const r=Object.assign({},e);return{data:yield rt(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,r,{headers:this.headers},n),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(se(r))return{data:null,error:r};throw r}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const n=[];return e.width&&n.push(`width=${e.width}`),e.height&&n.push(`height=${e.height}`),e.resize&&n.push(`resize=${e.resize}`),e.format&&n.push(`format=${e.format}`),e.quality&&n.push(`quality=${e.quality}`),n.join("&")}}const Ov="2.12.1",Av={"X-Client-Info":`storage-js/${Ov}`};var wn=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(d){try{c(r.next(d))}catch(h){o(h)}}function l(d){try{c(r.throw(d))}catch(h){o(h)}}function c(d){d.done?i(d.value):s(d.value).then(a,l)}c((r=r.apply(t,e||[])).next())})};class Rv{constructor(e,n={},r,s){this.shouldThrowOnError=!1;const i=new URL(e);s!=null&&s.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),this.url=i.href,this.headers=Object.assign(Object.assign({},Av),n),this.fetch=zh(r)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(){return wn(this,void 0,void 0,function*(){try{return{data:yield pi(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(se(e))return{data:null,error:e};throw e}})}getBucket(e){return wn(this,void 0,void 0,function*(){try{return{data:yield pi(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(se(n))return{data:null,error:n};throw n}})}createBucket(e,n={public:!1}){return wn(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:n.type,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(se(r))return{data:null,error:r};throw r}})}updateBucket(e,n){return wn(this,void 0,void 0,function*(){try{return{data:yield Sa(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(se(r))return{data:null,error:r};throw r}})}emptyBucket(e){return wn(this,void 0,void 0,function*(){try{return{data:yield rt(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(se(n))return{data:null,error:n};throw n}})}deleteBucket(e){return wn(this,void 0,void 0,function*(){try{return{data:yield Fh(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(se(n))return{data:null,error:n};throw n}})}}class $v extends Rv{constructor(e,n={},r,s){super(e,n,r,s)}from(e){return new Pv(this.url,this.headers,e,this.fetch)}}const Lv="2.57.4";let xr="";typeof Deno<"u"?xr="deno":typeof document<"u"?xr="web":typeof navigator<"u"&&navigator.product==="ReactNative"?xr="react-native":xr="node";const Iv={"X-Client-Info":`supabase-js-${xr}/${Lv}`},Uv={headers:Iv},Dv={schema:"public"},Mv={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},zv={};var Fv=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(d){try{c(r.next(d))}catch(h){o(h)}}function l(d){try{c(r.throw(d))}catch(h){o(h)}}function c(d){d.done?i(d.value):s(d.value).then(a,l)}c((r=r.apply(t,e||[])).next())})};const Bv=t=>{let e;return t?e=t:typeof fetch>"u"?e=bh:e=fetch,(...n)=>e(...n)},Wv=()=>typeof Headers>"u"?Nh:Headers,Hv=(t,e,n)=>{const r=Bv(n),s=Wv();return(i,o)=>Fv(void 0,void 0,void 0,function*(){var a;const l=(a=yield e())!==null&&a!==void 0?a:t;let c=new s(o==null?void 0:o.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),r(i,Object.assign(Object.assign({},o),{headers:c}))})};var Vv=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(d){try{c(r.next(d))}catch(h){o(h)}}function l(d){try{c(r.throw(d))}catch(h){o(h)}}function c(d){d.done?i(d.value):s(d.value).then(a,l)}c((r=r.apply(t,e||[])).next())})};function qv(t){return t.endsWith("/")?t:t+"/"}function Kv(t,e){var n,r;const{db:s,auth:i,realtime:o,global:a}=t,{db:l,auth:c,realtime:d,global:h}=e,f={db:Object.assign(Object.assign({},l),s),auth:Object.assign(Object.assign({},c),i),realtime:Object.assign(Object.assign({},d),o),storage:{},global:Object.assign(Object.assign(Object.assign({},h),a),{headers:Object.assign(Object.assign({},(n=h==null?void 0:h.headers)!==null&&n!==void 0?n:{}),(r=a==null?void 0:a.headers)!==null&&r!==void 0?r:{})}),accessToken:()=>Vv(this,void 0,void 0,function*(){return""})};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function Gv(t){const e=t==null?void 0:t.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(qv(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}const Bh="2.71.1",jn=30*1e3,ja=3,go=ja*jn,Qv="http://localhost:9999",Jv="supabase.auth.token",Yv={"X-Client-Info":`gotrue-js/${Bh}`},Ea="X-Supabase-Api-Version",Wh={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Xv=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Zv=10*60*1e3;class Nl extends Error{constructor(e,n,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function R(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class eg extends Nl{constructor(e,n,r){super(e,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function tg(t){return R(t)&&t.name==="AuthApiError"}class Hh extends Nl{constructor(e,n){super(e),this.name="AuthUnknownError",this.originalError=n}}class Ht extends Nl{constructor(e,n,r,s){super(e,r,s),this.name=n,this.status=r}}class St extends Ht{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function ng(t){return R(t)&&t.name==="AuthSessionMissingError"}class Ts extends Ht{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Ps extends Ht{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Os extends Ht{constructor(e,n=null){super(e,"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 rg(t){return R(t)&&t.name==="AuthImplicitGrantRedirectError"}class Gu extends Ht{constructor(e,n=null){super(e,"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 ba extends Ht{constructor(e,n){super(e,"AuthRetryableFetchError",n,void 0)}}function yo(t){return R(t)&&t.name==="AuthRetryableFetchError"}class Qu extends Ht{constructor(e,n,r){super(e,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class Na extends Ht{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const mi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Ju=` \r=`.split(""),sg=(()=>{const t=new Array(128);for(let e=0;e=6;){const r=e.queue>>e.queuedBits-6&63;n(mi[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;n(mi[r]),e.queuedBits-=6}}function Vh(t,e,n){const r=sg[t];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)n(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Xu(t){const e=[],n=o=>{e.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{ag(o,r,n)};for(let o=0;o>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function og(t,e){for(let n=0;n55295&&r<=56319){const s=(r-55296)*1024&65535;r=(t.charCodeAt(n+1)-56320&65535|s)+65536,n+=1}ig(r,e)}}function ag(t,e,n){if(e.utf8seq===0){if(t<=127){n(t);return}for(let r=1;r<6;r+=1)if(!(t>>7-r&1)){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&n(e.codepoint)}}function lg(t){const e=[],n={queue:0,queuedBits:0},r=s=>{e.push(s)};for(let s=0;se.push(n)),new Uint8Array(e)}function cg(t){const e=[],n={queue:0,queuedBits:0},r=s=>{e.push(s)};return t.forEach(s=>Yu(s,n,r)),Yu(null,n,r),e.join("")}function dg(t){return Math.round(Date.now()/1e3)+t}function hg(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}const Ve=()=>typeof window<"u"&&typeof document<"u",qt={tested:!1,writable:!1},qh=()=>{if(!Ve())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(qt.tested)return qt.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),qt.tested=!0,qt.writable=!0}catch{qt.tested=!0,qt.writable=!1}return qt.writable};function fg(t){const e={},n=new URL(t);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return n.searchParams.forEach((r,s)=>{e[s]=r}),e}const Kh=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...n)=>rs(async()=>{const{default:r}=await Promise.resolve().then(()=>rr);return{default:r}},void 0).then(({default:r})=>r(...n)):e=fetch,(...n)=>e(...n)},pg=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",En=async(t,e,n)=>{await t.setItem(e,JSON.stringify(n))},Kt=async(t,e)=>{const n=await t.getItem(e);if(!n)return null;try{return JSON.parse(n)}catch{return n}},kt=async(t,e)=>{await t.removeItem(e)};class Mi{constructor(){this.promise=new Mi.promiseConstructor((e,n)=>{this.resolve=e,this.reject=n})}}Mi.promiseConstructor=Promise;function wo(t){const e=t.split(".");if(e.length!==3)throw new Na("Invalid JWT structure");for(let r=0;r{setTimeout(()=>e(null),t)})}function vg(t,e){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await t(i);if(!e(i,null,o)){r(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function gg(t){return("0"+t.toString(16)).substr(-2)}function yg(){const e=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(e),Array.from(e,gg).join("")}async function wg(t){const n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function xg(t){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."),t;const n=await wg(t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function xn(t,e,n=!1){const r=yg();let s=r;n&&(s+="/PASSWORD_RECOVERY"),await En(t,`${e}-code-verifier`,s);const i=await xg(r);return[i,r===i?"plain":"s256"]}const _g=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function kg(t){const e=t.headers.get(Ea);if(!e||!e.match(_g))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Sg(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function jg(t){switch(t){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 Eg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function _n(t){if(!Eg.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function xo(){const t={};return new Proxy(t,{get:(e,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:(e,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:(e,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 Zu(t){return JSON.parse(JSON.stringify(t))}var bg=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(t);st.msg||t.message||t.error_description||t.error||JSON.stringify(t),Ng=[502,503,504];async function ec(t){var e;if(!pg(t))throw new ba(Jt(t),0);if(Ng.includes(t.status))throw new ba(Jt(t),t.status);let n;try{n=await t.json()}catch(i){throw new Hh(Jt(i),i)}let r;const s=kg(t);if(s&&s.getTime()>=Wh["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 Qu(Jt(n),t.status,((e=n.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new St}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 Qu(Jt(n),t.status,n.weak_password.reasons);throw new eg(Jt(n),t.status||500,r)}const Cg=(t,e,n,r)=>{const s={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),n))};async function I(t,e,n,r){var s;const i=Object.assign({},r==null?void 0:r.headers);i[Ea]||(i[Ea]=Wh["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 Tg(t,e,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 Tg(t,e,n,r,s,i){const o=Cg(e,r,s,i);let a;try{a=await t(n,Object.assign({},o))}catch(l){throw console.error(l),new ba(Jt(l),0)}if(a.ok||await ec(a),r!=null&&r.noResolveJson)return a;try{return await a.json()}catch(l){await ec(l)}}function lt(t){var e;let n=null;Rg(t)&&(n=Object.assign({},t),t.expires_at||(n.expires_at=dg(t.expires_in)));const r=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:n,user:r},error:null}}function tc(t){const e=lt(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Ct(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Pg(t){return{data:t,error:null}}function Og(t){const{action_link:e,email_otp:n,hashed_token:r,redirect_to:s,verification_type:i}=t,o=bg(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,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 Ag(t){return t}function Rg(t){return t.access_token&&t.refresh_token&&t.expires_in}const _o=["global","local","others"];var $g=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(t);s0&&(g.forEach(y=>{const x=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),E=JSON.parse(y.split(";")[1].split("=")[1]);c[`${E}Page`]=x}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(R(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){_n(e);try{return await I(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Ct})}catch(n){if(R(n))return{data:{user:null},error:n};throw n}}async updateUserById(e,n){_n(e);try{return await I(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:n,headers:this.headers,xform:Ct})}catch(r){if(R(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,n=!1){_n(e);try{return await I(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:n},xform:Ct})}catch(r){if(R(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){_n(e.userId);try{const{data:n,error:r}=await I(this.fetch,"GET",`${this.url}/admin/users/${e.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(e){_n(e.userId),_n(e.id);try{return{data:await I(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(n){if(R(n))return{data:null,error:n};throw n}}}function nc(t={}){return{getItem:e=>t[e]||null,setItem:(e,n)=>{t[e]=n},removeItem:e=>{delete t[e]}}}function Ig(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}const kn={debug:!!(globalThis&&qh()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Gh extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Ug extends Gh{}async function Dg(t,e,n){kn.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),kn.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async s=>{if(s){kn.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await n()}finally{kn.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw kn.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Ug(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(kn.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()}}))}Ig();const Mg={url:Qv,storageKey:Jv,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Yv,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function rc(t,e,n){return await n()}const Sn={};class Jr{constructor(e){var n,r;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=Jr.nextInstanceID,Jr.nextInstanceID+=1,this.instanceID>0&&Ve()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const s=Object.assign(Object.assign({},Mg),e);if(this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.persistSession=s.persistSession,this.storageKey=s.storageKey,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Lg({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Kh(s.fetch),this.lock=s.lock||rc,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:Ve()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=Dg:this.lock=rc,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)},this.persistSession?(s.storage?this.storage=s.storage:qh()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=nc(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=nc(this.memoryStorage)),Ve()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}get jwks(){var e,n;return(n=(e=Sn[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&n!==void 0?n:{keys:[]}}set jwks(e){Sn[this.storageKey]=Object.assign(Object.assign({},Sn[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,n;return(n=(e=Sn[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&n!==void 0?n:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Sn[this.storageKey]=Object.assign(Object.assign({},Sn[this.storageKey]),{cachedAt:e})}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Bh}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{const n=fg(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),Ve()&&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),rg(i)){const l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:o,redirectType:a}=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)?{error:n}:{error:new Hh("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var n,r,s;try{const i=await I(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.captchaToken}},xform:lt}),{data:o,error:a}=i;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(R(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var n,r,s;try{let i;if("email"in e){const{email:d,password:h,options:f}=e;let g=null,y=null;this.flowType==="pkce"&&([g,y]=await xn(this.storage,this.storageKey)),i=await I(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:d,password:h,data:(n=f==null?void 0:f.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:g,code_challenge_method:y},xform:lt})}else if("phone"in e){const{phone:d,password:h,options:f}=e;i=await I(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:h,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},channel:(s=f==null?void 0:f.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:lt})}else throw new Ps("You must provide either an email or phone number and a password");const{data:o,error:a}=i;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(R(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let n;if("email"in e){const{email:i,password:o,options:a}=e;n=await I(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:tc})}else if("phone"in e){const{phone:i,password:o,options:a}=e;n=await I(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:tc})}else throw new Ps("You must provide either an email or phone number and a password");const{data:r,error:s}=n;return s?{data:{user:null,session:null},error:s}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Ts}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(n){if(R(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOAuth(e){var n,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(n=e.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:n}=e;if(n==="solana")return await this.signInWithSolana(e);throw new Error(`@supabase/auth-js: Unsupported chain "${n}"`)}async signInWithSolana(e){var n,r,s,i,o,a,l,c,d,h,f,g;let y,x;if("message"in e)y=e.message,x=e.signature;else{const{chain:E,wallet:v,statement:p,options:m}=e;let w;if(Ve())if(typeof v=="object")w=v;else{const k=window;if("solana"in k&&typeof k.solana=="object"&&("signIn"in k.solana&&typeof k.solana.signIn=="function"||"signMessage"in k.solana&&typeof k.solana.signMessage=="function"))w=k.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 v!="object"||!(m!=null&&m.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=v}const S=new URL((n=m==null?void 0:m.url)!==null&&n!==void 0?n:window.location.href);if("signIn"in w&&w.signIn){const k=await w.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},m==null?void 0:m.signInWithSolana),{version:"1",domain:S.host,uri:S.href}),p?{statement:p}:null));let j;if(Array.isArray(k)&&k[0]&&typeof k[0]=="object")j=k[0];else if(k&&typeof k=="object"&&"signedMessage"in k&&"signature"in k)j=k;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in j&&"signature"in j&&(typeof j.signedMessage=="string"||j.signedMessage instanceof Uint8Array)&&j.signature instanceof Uint8Array)y=typeof j.signedMessage=="string"?j.signedMessage:new TextDecoder().decode(j.signedMessage),x=j.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in w)||typeof w.signMessage!="function"||!("publicKey"in w)||typeof w!="object"||!w.publicKey||!("toBase58"in w.publicKey)||typeof w.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${S.host} wants you to sign in with your Solana account:`,w.publicKey.toBase58(),...p?["",p,""]:[""],"Version: 1",`URI: ${S.href}`,`Issued At: ${(s=(r=m==null?void 0:m.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=m==null?void 0:m.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${m.signInWithSolana.notBefore}`]:[],...!((o=m==null?void 0:m.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${m.signInWithSolana.expirationTime}`]:[],...!((a=m==null?void 0:m.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${m.signInWithSolana.chainId}`]:[],...!((l=m==null?void 0:m.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${m.signInWithSolana.nonce}`]:[],...!((c=m==null?void 0:m.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${m.signInWithSolana.requestId}`]:[],...!((h=(d=m==null?void 0:m.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...m.signInWithSolana.resources.map(j=>`- ${j}`)]:[]].join(` `);const k=await w.signMessage(new TextEncoder().encode(y),"utf8");if(!k||!(k instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");x=k}}try{const{data:E,error:v}=await I(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:cg(x)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:lt});if(v)throw v;return!E||!E.session||!E.user?{data:{user:null,session:null},error:new Ts}:(E.session&&(await this._saveSession(E.session),await this._notifyAllSubscribers("SIGNED_IN",E.session)),{data:Object.assign({},E),error:v})}catch(E){if(R(E))return{data:{user:null,session:null},error:E};throw E}}async _exchangeCodeForSession(e){const n=await Kt(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(n??"").split("/");try{const{data:i,error:o}=await I(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:lt});if(await kt(this.storage,`${this.storageKey}-code-verifier`),o)throw o;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Ts}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:s??null}),error:o})}catch(i){if(R(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(e){try{const{options:n,provider:r,token:s,access_token:i,nonce:o}=e,a=await I(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:lt}),{data:l,error:c}=a;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Ts}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(n){if(R(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOtp(e){var n,r,s,i,o;try{if("email"in e){const{email:a,options:l}=e;let c=null,d=null;this.flowType==="pkce"&&([c,d]=await xn(this.storage,this.storageKey));const{error:h}=await I(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:c,code_challenge_method:d},redirectTo:l==null?void 0:l.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in e){const{phone:a,options:l}=e,{data:c,error:d}=await I(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{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:d}}throw new Ps("You must provide either an email or phone number.")}catch(a){if(R(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var n,r;try{let s,i;"options"in e&&(s=(n=e.options)===null||n===void 0?void 0:n.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:a}=await I(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:lt});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,c=o.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(s){if(R(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithSSO(e){var n,r,s;try{let i=null,o=null;return this.flowType==="pkce"&&([i,o]=await xn(this.storage,this.storageKey)),await I(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(n=e.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r:void 0}),!((s=e==null?void 0:e.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:o}),headers:this.headers,xform:Pg})}catch(i){if(R(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:n},error:r}=e;if(r)throw r;if(!n)throw new St;const{error:s}=await I(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(R(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const n=`${this.url}/resend`;if("email"in e){const{email:r,type:s,options:i}=e,{error:o}=await I(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{data:{user:null,session:null},error:o}}else if("phone"in e){const{phone:r,type:s,options:i}=e,{data:o,error:a}=await I(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:a}}throw new Ps("You must provide either an email or phone number and a type")}catch(n){if(R(n))return{data:{user:null,session:null},error:n};throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async n=>n))}async _acquireLock(e,n){this._debug("#_acquireLock","begin",e);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}`,e,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(e){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await e(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 e=null;const n=await Kt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?e=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=e.expires_at?e.expires_at*1e3-Date.now()(!o&&c==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),o=!0,this.suppressGetSessionWarning=!0),Reflect.get(l,c,d))})}return{data:{session:e},error:null}}const{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:s},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await I(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ct}):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 St}:await I(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:Ct})})}catch(n){if(R(n))return ng(n)&&(await this._removeSession(),await kt(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:n};throw n}}async updateUser(e,n={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,n))}async _updateUser(e,n={}){try{return await this._useSession(async r=>{const{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new St;const o=s.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await xn(this.storage,this.storageKey));const{data:c,error:d}=await I(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:Ct});if(d)throw d;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(R(r))return{data:{user:null},error:r};throw r}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new St;const n=Date.now()/1e3;let r=n,s=!0,i=null;const{payload:o}=wo(e.access_token);if(o.exp&&(r=o.exp,s=r<=n),s){const{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};i=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(n){if(R(n))return{data:{session:null,user:null},error:n};throw n}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async n=>{var r;if(!e){const{data:o,error:a}=n;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(e!=null&&e.refresh_token))throw new St;const{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(n){if(R(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(e,n){try{if(!Ve())throw new Os("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Os(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(n){case"implicit":if(this.flowType==="pkce")throw new Gu("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Os("Not a valid implicit grant flow url.");break;default:}if(n==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Gu("No code detected.");const{data:p,error:m}=await this._exchangeCodeForSession(e.code);if(m)throw m;const w=new URL(window.location.href);return w.searchParams.delete("code"),window.history.replaceState(window.history.state,"",w.toString()),{data:{session:p.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:c}=e;if(!i||!a||!o||!c)throw new Os("No session defined in URL");const d=Math.round(Date.now()/1e3),h=parseInt(a);let f=d+h;l&&(f=parseInt(l));const g=f-d;g*1e3<=jn&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${h}s`);const y=f-h;d-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,f,d):d-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,f,d);const{data:x,error:E}=await this._getUser(i);if(E)throw E;const v={provider_token:r,provider_refresh_token:s,access_token:i,expires_in:h,expires_at:f,refresh_token:o,token_type:c,user:x.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:v,redirectType:e.type},error:null}}catch(r){if(R(r))return{data:{session:null,redirectType:null},error:r};throw r}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const n=await Kt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&n)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async n=>{var r;const{data:s,error:i}=n;if(i)return{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,e);if(a&&!(tg(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await kt(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const n=hg(),r={id:n,callback:e,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(-1,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(e){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(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,n={}){let r=null,s=null;this.flowType==="pkce"&&([r,s]=await xn(this.storage,this.storageKey,!0));try{return await I(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(i){if(R(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(e=n.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(n){if(R(n))return{data:null,error:n};throw n}}async linkIdentity(e){var n;try{const{data:r,error:s}=await this._useSession(async i=>{var o,a,l,c,d;const{data:h,error:f}=i;if(f)throw f;const g=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await I(this.fetch,"GET",g,{headers:this.headers,jwt:(d=(c=h.session)===null||c===void 0?void 0:c.access_token)!==null&&d!==void 0?d:void 0})});if(s)throw s;return Ve()&&!(!((n=e.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),{data:{provider:e.provider,url:r==null?void 0:r.url},error:null}}catch(r){if(R(r))return{data:{provider:e.provider,url:null},error:r};throw r}}async unlinkIdentity(e){try{return await this._useSession(async n=>{var r,s;const{data:i,error:o}=n;if(o)throw o;return await I(this.fetch,"DELETE",`${this.url}/user/identities/${e.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{data:null,error:n};throw n}}async _refreshAccessToken(e){const n=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{const r=Date.now();return await vg(async s=>(s>0&&await mg(200*Math.pow(2,s-1)),this._debug(n,"refreshing attempt",s),await I(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:lt})),(s,i)=>{const o=200*Math.pow(2,s);return i&&yo(i)&&Date.now()+o-r{try{await a.callback(e,n)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;athis._autoRefreshTokenTick(),jn);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async 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-e)/jn);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${jn}ms, refresh threshold is ${ja} ticks`),s<=ja&&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(e){if(e.isAcquireTimeout||e instanceof Gh)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ve()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const n=`#_onVisibilityChanged(${e})`;this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(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(e,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 xn(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}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;return i?{data:null,error:i}:await I(this.fetch,"DELETE",`${this.url}/factors/${e.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{data:null,error:n};throw n}}async _enroll(e){try{return await this._useSession(async n=>{var r,s;const{data:i,error:o}=n;if(o)return{data:null,error:o};const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:l,error:c}=await I(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 c?{data:null,error:c}:(e.factorType==="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}`),{data:l,error:null})})}catch(n){if(R(n))return{data:null,error:n};throw n}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;if(i)return{data:null,error:i};const{data:o,error:a}=await I(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(n){if(R(n))return{data:null,error:n};throw n}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;return i?{data:null,error:i}:await I(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},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{data:null,error:n};throw n}})}async _challengeAndVerify(e){const{data:n,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:n.id,code:e.code})}async _listFactors(){const{data:{user:e},error:n}=await this.getUser();if(n)return{data:null,error:n};const r=(e==null?void 0:e.factors)||[],s=r.filter(o=>o.factor_type==="totp"&&o.status==="verified"),i=r.filter(o=>o.factor_type==="phone"&&o.status==="verified");return{data:{all:r,totp:s,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var n,r;const{data:{session:s},error:i}=e;if(i)return{data:null,error:i};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:o}=wo(s.access_token);let a=null;o.aal&&(a=o.aal);let l=a;((r=(n=s.user.factors)===null||n===void 0?void 0:n.filter(h=>h.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(l="aal2");const d=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:d},error:null}}))}async fetchJwk(e,n={keys:[]}){let r=n.keys.find(a=>a.kid===e);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(a=>a.kid===e),r&&this.jwks_cached_at+Zv>s)return r;const{data:i,error:o}=await I(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===e),!r)?null:r}async getClaims(e,n={}){try{let r=e;if(!r){const{data:g,error:y}=await this.getSession();if(y||!g.session)return{data:null,error:y};r=g.session.access_token}const{header:s,payload:i,signature:o,raw:{header:a,payload:l}}=wo(r);n!=null&&n.allowExpired||Sg(i.exp);const c=!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(!c){const{error:g}=await this.getUser(r);if(g)throw g;return{data:{claims:i,header:s,signature:o},error:null}}const d=jg(s.alg),h=await crypto.subtle.importKey("jwk",c,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,o,ug(`${a}.${l}`)))throw new Na("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(r){if(R(r))return{data:null,error:r};throw r}}}Jr.nextInstanceID=0;const zg=Jr;class Fg extends zg{constructor(e){super(e)}}var Bg=function(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(d){try{c(r.next(d))}catch(h){o(h)}}function l(d){try{c(r.throw(d))}catch(h){o(h)}}function c(d){d.done?i(d.value):s(d.value).then(a,l)}c((r=r.apply(t,e||[])).next())})};class Wg{constructor(e,n,r){var s,i,o;this.supabaseUrl=e,this.supabaseKey=n;const a=Gv(e);if(!n)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const l=`sb-${a.hostname.split(".")[0]}-auth-token`,c={db:Dv,realtime:zv,auth:Object.assign(Object.assign({},Mv),{storageKey:l}),global:Uv},d=Kv(r??{},c);this.storageKey=(s=d.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(i=d.global.headers)!==null&&i!==void 0?i:{},d.accessToken?(this.accessToken=d.accessToken,this.auth=new Proxy({},{get:(h,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=d.auth)!==null&&o!==void 0?o:{},this.headers,d.global.fetch),this.fetch=Hv(n,this._getAccessToken.bind(this),d.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},d.realtime)),this.rest=new sv(new URL("rest/v1",a).href,{headers:this.headers,schema:d.db.schema,fetch:this.fetch}),this.storage=new $v(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),d.accessToken||this._listenForAuthEvents()}get functions(){return new Im(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,n={},r={}){return this.rest.rpc(e,n,r)}channel(e,n={config:{}}){return this.realtime.channel(e,n)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,n;return Bg(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:r}=yield this.auth.getSession();return(n=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&n!==void 0?n:this.supabaseKey})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:n,detectSessionInUrl:r,storage:s,userStorage:i,storageKey:o,flowType:a,lock:l,debug:c},d,h){const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Fg({url:this.authUrl.href,headers:Object.assign(Object.assign({},f),d),storageKey:o,autoRefreshToken:e,persistSession:n,detectSessionInUrl:r,storage:s,userStorage:i,flowType:a,lock:l,debug:c,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(g=>g.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new _v(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((n,r)=>{this._handleTokenChanged(n,"CLIENT",r==null?void 0:r.access_token)})}_handleTokenChanged(e,n,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?this.changedAccessToken=r:e==="SIGNED_OUT"&&(this.realtime.setAuth(),n=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Hg=(t,e,n)=>new Wg(t,e,n);function Vg(){if(typeof window<"u"||typeof process>"u")return!1;const t=process.version;if(t==null)return!1;const e=t.match(/^v(\d+)\./);return e?parseInt(e[1],10)<=18:!1}Vg()&&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 qg="https://supabase.myassistant.guru",Kg="sb_publishable_6xgj-cDxaHPcf4iZ5bF2a0_1w0qrTea",Q=Hg(qg,Kg,{auth:{persistSession:!0,autoRefreshToken:!0}}),Qh=T.createContext(void 0);async function Jh(t){const{data:e,error:n}=await Q.from("profiles").select("id, email, plan_id, role, created_at").eq("id",t).maybeSingle();return n?null:e}async function sc(t){const e=await Jh(t.id);if(e)return e;const{count:n}=await Q.from("profiles").select("id",{count:"exact",head:!0}),r=(n??0)===0?"admin":"user",{data:s,error:i}=await Q.from("profiles").insert({id:t.id,email:t.email??"",role:r}).select("id, email, plan_id, role, created_at").maybeSingle();return i?null:s}function Gg({children:t}){const[e,n]=T.useState({session:null,user:null,profile:null,loading:!0});T.useEffect(()=>{let a=!0;Q.auth.getSession().then(({data:c})=>{if(!a)return;const d=c.session;(async()=>{if(d!=null&&d.user){const f=await sc(d.user);a&&n({session:d,user:d.user,profile:f,loading:!1})}else a&&n({session:null,user:null,profile:null,loading:!1})})()});const{data:l}=Q.auth.onAuthStateChange((c,d)=>{(async()=>{if(d!=null&&d.user){const h=await sc(d.user);n({session:d,user:d.user,profile:h,loading:!1})}else n({session:null,user:null,profile:null,loading:!1})})()});return()=>{a=!1,l.subscription.unsubscribe()}},[]);const r=async(a,l)=>{const{error:c}=await Q.auth.signUp({email:a,password:l});return{error:(c==null?void 0:c.message)??null}},s=async(a,l)=>{const{error:c}=await Q.auth.signInWithPassword({email:a,password:l});return{error:(c==null?void 0:c.message)??null}},i=async()=>{await Q.auth.signOut()},o=async()=>{if(!e.user)return;const a=await Jh(e.user.id);a&&n(l=>({...l,profile:a}))};return u.jsx(Qh.Provider,{value:{...e,signUp:r,signIn:s,signOut:i,refreshProfile:o},children:t})}function fn(){const t=T.useContext(Qh);if(!t)throw new Error("useAuth must be used within AuthProvider");return t}function Yh(){const[t,e]=T.useState(()=>window.location.hash.slice(1)||"/");return T.useEffect(()=>{const n=()=>{e(window.location.hash.slice(1)||"/"),window.scrollTo(0,0)};return window.addEventListener("hashchange",n),()=>window.removeEventListener("hashchange",n)},[]),t}function be(t){window.location.hash=t}function Qg(t,e){const n=t.split("/").filter(Boolean),r=e.split("/").filter(Boolean);if(n.length!==r.length)return null;const s={};for(let i=0;i{e&&be(e),s==null||s(o)},className:`inline-flex items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-medium transition-all duration-150 disabled:opacity-50 disabled:pointer-events-none ${Jg[t]} ${r}`,...i,children:n})}function pe({children:t,className:e=""}){return u.jsx("div",{className:`rounded-2xl border border-[var(--line)] bg-white ${e}`,children:t})}const Yg={neutral:"bg-[var(--line)] text-[var(--muted)]",brand:"bg-blue-50 text-[var(--brand)]",success:"bg-emerald-50 text-emerald-700",warning:"bg-amber-50 text-amber-700",error:"bg-red-50 text-red-700"};function Dn({tone:t="neutral",children:e}){return u.jsx("span",{className:`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium ${Yg[t]}`,children:e})}function rn({className:t=""}){return u.jsx("span",{className:`inline-block h-4 w-4 rounded-full border-2 border-current border-t-transparent animate-spin-slow ${t}`})}function vi({label:t,children:e,hint:n}){return u.jsxs("label",{className:"block",children:[u.jsx("span",{className:"mb-1.5 block text-sm font-medium text-[var(--ink)]",children:t}),e,n&&u.jsx("span",{className:"mt-1 block text-xs text-[var(--muted)]",children:n})]})}function Yr(t){return u.jsx("input",{...t,className:`w-full rounded-lg border border-[var(--line-2)] bg-white px-3.5 py-2.5 text-sm text-[var(--ink)] placeholder:text-[var(--muted)]/70 outline-none transition-colors focus:border-[var(--brand)] focus:ring-2 focus:ring-blue-500/15 ${t.className??""}`})}/** * @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 Xg={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 Zg=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),L=(t,e)=>{const n=T.forwardRef(({color:r="currentColor",size:s=24,strokeWidth:i=2,absoluteStrokeWidth:o,className:a="",children:l,...c},d)=>T.createElement("svg",{ref:d,...Xg,width:s,height:s,stroke:r,strokeWidth:o?Number(i)*24/Number(s):i,className:["lucide",`lucide-${Zg(t)}`,a].join(" "),...c},[...e.map(([h,f])=>T.createElement(h,f)),...Array.isArray(l)?l:[l]]));return n.displayName=`${t}`,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 ey=L("AlertOctagon",[["polygon",{points:"7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2",key:"h1p8hx"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** * @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 Ca=L("AlertTriangle",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z",key:"c3ski4"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @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 ty=L("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** * @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 Cl=L("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** * @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 ny=L("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/** * @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 Vn=L("CheckCircle2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @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 Xh=L("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** * @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 gi=L("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** * @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 ry=L("Container",[["path",{d:"M22 7.7c0-.6-.4-1.2-.8-1.5l-6.3-3.9a1.72 1.72 0 0 0-1.7 0l-10.3 6c-.5.2-.9.8-.9 1.4v6.6c0 .5.4 1.2.8 1.5l6.3 3.9a1.72 1.72 0 0 0 1.7 0l10.3-6c.5-.3.9-1 .9-1.5Z",key:"1t2lqe"}],["path",{d:"M10 21.9V14L2.1 9.1",key:"o7czzq"}],["path",{d:"m10 14 11.9-6.9",key:"zm5e20"}],["path",{d:"M14 19.8v-8.1",key:"159ecu"}],["path",{d:"M18 17.5V9.4",key:"11uown"}]]);/** * @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 sy=L("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]);/** * @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 iy=L("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/** * @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 oy=L("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** * @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 ay=L("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** * @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 ly=L("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/** * @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 uy=L("FolderKanban",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M12 10v2",key:"hh53o1"}],["path",{d:"M16 10v6",key:"1d6xys"}]]);/** * @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 Zh=L("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]);/** * @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 cy=L("Github",[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]]);/** * @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 dy=L("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** * @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 hy=L("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"}]]);/** * @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 ef=L("KeyRound",[["path",{d:"M2 18v3c0 .6.4 1 1 1h4v-3h3v-3h2l1.4-1.4a6.5 6.5 0 1 0-4-4Z",key:"167ctg"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);/** * @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 ko=L("Loader2",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** * @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 tf=L("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** * @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 fy=L("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** * @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 ic=L("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** * @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 So=L("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** * @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 oc=L("Power",[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]]);/** * @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 os=L("Rocket",[["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z",key:"m3kijz"}],["path",{d:"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z",key:"1fmvmk"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0",key:"1f8sc4"}],["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}]]);/** * @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 py=L("Send",[["path",{d:"m22 2-7 20-4-9-9-4Z",key:"1q3vgg"}],["path",{d:"M22 2 11 13",key:"nzbqef"}]]);/** * @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 my=L("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/** * @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 yi=L("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @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 vy=L("Shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);/** * @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 ac=L("Sparkles",[["path",{d:"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z",key:"17u4zn"}],["path",{d:"M5 3v4",key:"bklmnn"}],["path",{d:"M19 17v4",key:"iiml17"}],["path",{d:"M3 5h4",key:"nem4j1"}],["path",{d:"M17 19h4",key:"lbex7p"}]]);/** * @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 lc=L("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** * @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 uc=L("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** * @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 gy=L("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** * @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 Tl=L("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]);/** * @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 nf=L("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** * @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 cc=L("Zap",[["polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2",key:"45s27k"}]]);function yy(){const{user:t,profile:e,signOut:n}=fn();return u.jsx("header",{className:"sticky top-0 z-40 border-b border-[var(--line)] bg-white/80 backdrop-blur-md",children:u.jsxs("div",{className:"mx-auto flex h-16 max-w-6xl items-center justify-between px-5",children:[u.jsxs("button",{onClick:()=>be(t?"/projects":"/"),className:"flex items-center gap-2",children:[u.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-[var(--ink)] text-white",children:u.jsx(os,{className:"h-4 w-4"})}),u.jsx("span",{className:"text-[15px] font-semibold tracking-tight text-[var(--ink)]",children:"CodeAI"})]}),t?u.jsxs("div",{className:"flex items-center gap-3",children:[(e==null?void 0:e.role)==="admin"&&u.jsx(H,{variant:"ghost",to:"/admin",className:"px-2.5",title:"Admin dashboard",children:u.jsx(vy,{className:"h-4 w-4"})}),u.jsx("span",{className:"hidden text-sm text-[var(--muted)] sm:block",children:e==null?void 0:e.email}),u.jsx("span",{className:"rounded-full bg-[var(--line)] px-2.5 py-1 text-xs font-medium capitalize text-[var(--muted)]",children:(e==null?void 0:e.plan_id)??"free"}),u.jsx(H,{variant:"ghost",onClick:()=>n(),className:"px-2.5",children:u.jsx(fy,{className:"h-4 w-4"})})]}):u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(H,{variant:"ghost",to:"/login",className:"text-sm",children:"Sign in"}),u.jsx(H,{to:"/signup",className:"text-sm",children:"Get started"})]})]})})}const wy=[{id:"free",name:"Free",price_cents:0,project_cap:1,ram_mb:512,cpu_cores:.5,fix_retry_cap:1,priority:0,features:["1 project","512MB RAM","1 auto-fix attempt","Standard 12h SLA"]},{id:"pro",name:"Pro",price_cents:1900,project_cap:5,ram_mb:2048,cpu_cores:1,fix_retry_cap:5,priority:1,features:["5 projects","2GB RAM","5 auto-fix attempts","Priority escalation","Email alerts"]},{id:"scale",name:"Scale",price_cents:4900,project_cap:25,ram_mb:4096,cpu_cores:2,fix_retry_cap:20,priority:2,features:["25 projects","4GB RAM","20 auto-fix attempts","Highest priority","Slack integration","Custom domains"]}];function xy(){const[t,e]=T.useState(wy);return T.useEffect(()=>{Q.from("plans").select("*").order("price_cents",{ascending:!0}).then(({data:n})=>{n&&n.length&&e(n)})},[]),u.jsxs("div",{className:"bg-[var(--paper)]",children:[u.jsxs("section",{className:"relative overflow-hidden",children:[u.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-blue-50/60 via-transparent to-transparent"}),u.jsx("div",{className:"relative mx-auto max-w-6xl px-5 pt-20 pb-16 sm:pt-28",children:u.jsxs("div",{className:"mx-auto max-w-3xl text-center",children:[u.jsxs("div",{className:"mb-5 inline-flex items-center gap-2 rounded-full border border-[var(--line)] bg-white px-3.5 py-1.5 text-xs font-medium text-[var(--muted)]",children:[u.jsx("span",{className:"flex h-1.5 w-1.5 rounded-full bg-emerald-500"}),"Built for Bolt, Lovable & Replit exports"]}),u.jsxs("h1",{className:"text-4xl font-semibold tracking-tight text-[var(--ink)] sm:text-6xl",children:["Deploy your vibe-coded app.",u.jsx("br",{}),u.jsx("span",{className:"text-[var(--brand)]",children:"We fix it when it breaks."})]}),u.jsx("p",{className:"mx-auto mt-6 max-w-xl text-lg text-[var(--muted)]",children:"Connect a repo, get a live URL. If the deploy or runtime throws errors, a chain of narrow AI agents attempts a scoped fix — and escalates to a human with a 12-hour SLA when it can't."}),u.jsxs("div",{className:"mt-8 flex items-center justify-center gap-3",children:[u.jsxs(H,{to:"/signup",className:"px-6 py-3 text-base",children:["Deploy your first app",u.jsx(Cl,{className:"h-4 w-4"})]}),u.jsx(H,{variant:"secondary",to:"/login",className:"px-6 py-3 text-base",children:"Sign in"})]}),u.jsx("p",{className:"mt-4 text-xs text-[var(--muted)]",children:"Free tier includes 1 project · No credit card required"})]})})]}),u.jsxs("section",{className:"mx-auto max-w-6xl px-5 py-16",children:[u.jsx("h2",{className:"text-center text-2xl font-semibold tracking-tight text-[var(--ink)]",children:"From repo to live URL, automatically"}),u.jsx("div",{className:"mt-12 grid gap-6 sm:grid-cols-2 lg:grid-cols-4",children:[{icon:Zh,title:"Connect",desc:"Paste a GitHub URL or upload a zip. We clone, detect the stack, and scan for required env vars."},{icon:yi,title:"Configure",desc:"Schema-match against your code, set up RLS, generate a placeholder .env you fill in yourself."},{icon:ry,title:"Deploy",desc:"We generate a Dockerfile, build an isolated container, and route a subdomain through Nginx."},{icon:Tl,title:"Auto-fix",desc:"On error, a triage agent classifies it and a fix agent proposes a scoped diff — then re-verifies."}].map((n,r)=>u.jsxs(pe,{className:"p-6",children:[u.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-[var(--ink)] text-white",children:u.jsx(n.icon,{className:"h-5 w-5"})}),u.jsxs("div",{className:"mt-4 flex items-center gap-2",children:[u.jsxs("span",{className:"text-xs font-medium text-[var(--muted)]",children:["0",r+1]}),u.jsx("h3",{className:"text-base font-semibold text-[var(--ink)]",children:n.title})]}),u.jsx("p",{className:"mt-2 text-sm leading-relaxed text-[var(--muted)]",children:n.desc})]},n.title))})]}),u.jsx("section",{className:"border-y border-[var(--line)] bg-white",children:u.jsx("div",{className:"mx-auto grid max-w-6xl gap-6 px-5 py-12 sm:grid-cols-3",children:[{icon:tf,title:"Secrets never touch an LLM",desc:"Agents read env var names only. You enter real values via the dashboard."},{icon:yi,title:"Scoped fixes only",desc:"Fix agents edit only the file(s) an error implicates. Anything wider escalates."},{icon:gi,title:"12-hour human SLA",desc:"When automation is exhausted, a human picks it up — faster on paid plans."}].map(n=>u.jsxs("div",{className:"flex gap-3",children:[u.jsx(n.icon,{className:"h-5 w-5 shrink-0 text-[var(--brand)]"}),u.jsxs("div",{children:[u.jsx("h4",{className:"text-sm font-semibold text-[var(--ink)]",children:n.title}),u.jsx("p",{className:"mt-1 text-sm text-[var(--muted)]",children:n.desc})]})]},n.title))})}),u.jsxs("section",{className:"mx-auto max-w-6xl px-5 py-20",children:[u.jsxs("div",{className:"text-center",children:[u.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-[var(--ink)]",children:"Simple, honest pricing"}),u.jsx("p",{className:"mt-2 text-[var(--muted)]",children:"Start free. Upgrade when you need more projects or faster fixes."})]}),u.jsx("div",{className:"mt-12 grid gap-6 lg:grid-cols-3",children:t.map(n=>{const r=n.id==="pro";return u.jsxs(pe,{className:`relative flex flex-col p-7 ${r?"border-[var(--brand)] ring-1 ring-[var(--brand)]":""}`,children:[r&&u.jsx("span",{className:"absolute -top-3 left-7 rounded-full bg-[var(--brand)] px-3 py-1 text-xs font-medium text-white",children:"Most popular"}),u.jsx("h3",{className:"text-lg font-semibold text-[var(--ink)]",children:n.name}),u.jsxs("div",{className:"mt-2 flex items-baseline gap-1",children:[u.jsxs("span",{className:"text-4xl font-semibold tracking-tight text-[var(--ink)]",children:["$",n.price_cents/100]}),u.jsx("span",{className:"text-sm text-[var(--muted)]",children:"/mo"})]}),u.jsx("ul",{className:"mt-6 flex-1 space-y-3",children:n.features.map(s=>u.jsxs("li",{className:"flex items-start gap-2.5 text-sm text-[var(--ink-2)]",children:[u.jsx(Xh,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-500"}),s]},s))}),u.jsx(H,{to:"/signup",variant:r?"primary":"secondary",className:"mt-7 w-full justify-center",children:n.price_cents===0?"Start free":`Choose ${n.name}`})]},n.id)})})]}),u.jsx("footer",{className:"border-t border-[var(--line)] bg-white",children:u.jsxs("div",{className:"mx-auto flex max-w-6xl flex-col items-center justify-between gap-4 px-5 py-8 sm:flex-row",children:[u.jsxs("div",{className:"flex items-center gap-2 text-sm text-[var(--muted)]",children:[u.jsx(os,{className:"h-4 w-4"}),"CodeAI"]}),u.jsx("p",{className:"text-xs text-[var(--muted)]",children:"Deploy safely. Fix automatically. Escalate to humans."})]})})]})}function dc({mode:t}){const{signUp:e,signIn:n}=fn(),[r,s]=T.useState(""),[i,o]=T.useState(""),[a,l]=T.useState(null),[c,d]=T.useState(!1),h=t==="signup",f=async g=>{g.preventDefault(),l(null),d(!0);const y=h?await e(r,i):await n(r,i);if(d(!1),y.error){l(y.error);return}be("/projects")};return u.jsx("div",{className:"flex min-h-[calc(100vh-4rem)] items-center justify-center px-5 py-12",children:u.jsxs("div",{className:"w-full max-w-sm",children:[u.jsxs("div",{className:"mb-8 text-center",children:[u.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--ink)] text-white",children:u.jsx(os,{className:"h-6 w-6"})}),u.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-[var(--ink)]",children:h?"Create your account":"Welcome back"}),u.jsx("p",{className:"mt-2 text-sm text-[var(--muted)]",children:h?"Start with the Free plan. Upgrade anytime.":"Sign in to manage your deployments."})]}),u.jsxs(pe,{className:"p-6",children:[u.jsxs("form",{onSubmit:f,className:"space-y-4",children:[u.jsx(vi,{label:"Email",children:u.jsx(Yr,{type:"email",required:!0,value:r,onChange:g=>s(g.target.value),placeholder:"you@example.com",autoComplete:"email"})}),u.jsx(vi,{label:"Password",children:u.jsx(Yr,{type:"password",required:!0,minLength:6,value:i,onChange:g=>o(g.target.value),placeholder:"At least 6 characters",autoComplete:h?"new-password":"current-password"})}),a&&u.jsx("div",{className:"rounded-lg bg-red-50 px-3.5 py-2.5 text-sm text-red-700",children:a}),u.jsxs(H,{type:"submit",disabled:c,className:"w-full justify-center",children:[c?"Please wait…":h?"Create account":"Sign in",!c&&u.jsx(Cl,{className:"h-4 w-4"})]})]}),u.jsx("div",{className:"mt-5 text-center text-sm text-[var(--muted)]",children:h?u.jsxs(u.Fragment,{children:["Already have an account?"," ",u.jsx("button",{onClick:()=>be("/login"),className:"font-medium text-[var(--brand)] hover:underline",children:"Sign in"})]}):u.jsxs(u.Fragment,{children:["New here?"," ",u.jsx("button",{onClick:()=>be("/signup"),className:"font-medium text-[var(--brand)] hover:underline",children:"Create an account"})]})})]}),h&&u.jsx("p",{className:"mt-4 text-center text-xs text-[var(--muted)]",children:"By signing up you agree to our Terms. No credit card required for Free."})]})})}const _y={ingesting:{label:"Ingesting",tone:"brand",icon:ko},configuring:{label:"Configuring",tone:"brand",icon:ko},deploying:{label:"Deploying",tone:"brand",icon:ko},fixing:{label:"Auto-fixing",tone:"warning",icon:Tl},live:{label:"Live",tone:"success",icon:Vn},failed:{label:"Failed",tone:"error",icon:Ca},escalated:{label:"Escalated",tone:"warning",icon:Ca}};function ky(){const{profile:t}=fn(),[e,n]=T.useState(null);if(T.useEffect(()=>{Q.from("projects").select("*").order("created_at",{ascending:!1}).then(({data:s})=>n(s??[]))},[]),!e)return u.jsx("div",{className:"flex min-h-[60vh] items-center justify-center",children:u.jsx(rn,{className:"h-6 w-6 text-[var(--brand)]"})});const r=t?e.length>=(t.plan_id==="free"?1:t.plan_id==="pro"?5:25):!1;return u.jsxs("div",{className:"mx-auto max-w-4xl px-5 py-10",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-[var(--ink)]",children:"Your projects"}),u.jsxs("p",{className:"mt-1 text-sm text-[var(--muted)]",children:[e.length," of ",(t==null?void 0:t.plan_id)==="free"?1:(t==null?void 0:t.plan_id)==="pro"?5:25," used"]})]}),u.jsxs(H,{to:"/connect",disabled:r,children:[u.jsx(So,{className:"h-4 w-4"}),"New project"]})]}),r&&u.jsxs("div",{className:"mt-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:["You've reached your plan's project limit."," ",u.jsx("button",{onClick:()=>be("/upgrade"),className:"font-medium underline",children:"Upgrade to add more"}),"."]}),e.length===0?u.jsxs(pe,{className:"mt-8 p-12 text-center",children:[u.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--line)]",children:u.jsx(So,{className:"h-6 w-6 text-[var(--muted)]"})}),u.jsx("h3",{className:"mt-4 text-base font-semibold text-[var(--ink)]",children:"No projects yet"}),u.jsx("p",{className:"mt-1 text-sm text-[var(--muted)]",children:"Connect a repo to deploy your first app."}),u.jsxs(H,{to:"/connect",className:"mt-6",children:["Connect a project",u.jsx(So,{className:"h-4 w-4"})]})]}):u.jsx("div",{className:"mt-8 space-y-3",children:e.map(s=>{const i=_y[s.status],o=i.icon;return u.jsxs("button",{onClick:()=>be(`/projects/${s.id}`),className:"group flex w-full items-center justify-between rounded-xl border border-[var(--line)] bg-white p-5 text-left transition-all hover:border-[var(--ink)] hover:shadow-sm",children:[u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-[var(--paper)] text-[var(--ink)]",children:u.jsx(dy,{className:"h-5 w-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"text-sm font-semibold text-[var(--ink)]",children:s.name}),u.jsxs("p",{className:"mt-0.5 text-xs text-[var(--muted)]",children:[s.source_type==="github"?s.source_url:"Uploaded zip"," · ",new Date(s.created_at).toLocaleDateString()]})]})]}),u.jsx("div",{className:"flex items-center gap-3",children:u.jsxs(Dn,{tone:i.tone,children:[u.jsx(o,{className:`h-3 w-3 ${s.status==="ingesting"||s.status==="configuring"||s.status==="deploying"?"animate-spin-slow":""}`}),i.label]})})]},s.id)})})]})}const Sy="/api";function as(t){const e=Sy.replace(/\/$/,""),n=t.startsWith("/")?t:`/${t}`;return`${e}${n}`}async function ls(){var n;const{data:t}=await Q.auth.getSession(),e=(n=t.session)==null?void 0:n.access_token;if(!e)throw new Error("You must be signed in to use the deployment backend.");return{Authorization:`Bearer ${e}`}}async function us(t){const e=await t.json().catch(()=>({}));if(!t.ok)throw new Error(e.error??"Backend request failed.");return e}async function jy(t){const e=await ls(),n=new FormData;n.set("source_type",t.sourceType),t.sourceUrl&&n.set("source_url",t.sourceUrl),t.name&&n.set("name",t.name),t.file&&n.set("zip",t.file);const r=await fetch(as("/ingest"),{method:"POST",headers:e,body:n});return us(r)}async function Ey(t,e){const n=await ls(),r=await fetch(as("/env"),{method:"POST",headers:{...n,"Content-Type":"application/json"},body:JSON.stringify({project_id:t,values:e})});return us(r)}async function by(t){const e=await ls(),n=await fetch(as("/deploy"),{method:"POST",headers:{...e,"Content-Type":"application/json"},body:JSON.stringify({project_id:t})});return us(n)}async function Ny(t){const e=await ls(),n=await fetch(as("/deploy/terminate"),{method:"POST",headers:{...e,"Content-Type":"application/json"},body:JSON.stringify({project_id:t})});return us(n)}async function Cy(t,e){const n=await ls(),r=await fetch(as("/chat"),{method:"POST",headers:{...n,"Content-Type":"application/json"},body:JSON.stringify({project_id:t,message:e})});return us(r)}function Ty(){const[t,e]=T.useState("github"),[n,r]=T.useState(""),[s,i]=T.useState(null),[o,a]=T.useState(!1),[l,c]=T.useState(null),d=async h=>{var f;if(h.preventDefault(),c(null),t==="github"&&!n.trim()){c("Paste a GitHub URL.");return}if(t==="upload"&&!s){c("Upload a zip file.");return}a(!0);try{const g=t==="github"?n.trim():void 0,y=t==="github"?((f=n.trim().split("/").pop())==null?void 0:f.replace(/\.git$/,""))??"my-app":s.name.replace(/\.zip$/,""),x=await jy({sourceType:t,sourceUrl:g,file:t==="upload"?s:void 0,name:y});be(`/projects/${x.project_id}`)}catch(g){c(g instanceof Error?g.message:"Could not create project.")}finally{a(!1)}};return u.jsxs("div",{className:"mx-auto max-w-xl px-5 py-10",children:[u.jsxs("div",{className:"mb-8",children:[u.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-[var(--ink)]",children:"Connect a project"}),u.jsx("p",{className:"mt-1 text-sm text-[var(--muted)]",children:"Paste a GitHub URL or upload a zip. We'll analyze the stack and required env vars."})]}),u.jsxs(pe,{className:"p-6",children:[u.jsxs("div",{className:"mb-6 flex gap-2 rounded-lg bg-[var(--paper)] p-1",children:[u.jsxs("button",{onClick:()=>e("github"),className:`flex flex-1 items-center justify-center gap-2 rounded-md py-2 text-sm font-medium transition-colors ${t==="github"?"bg-white text-[var(--ink)] shadow-sm":"text-[var(--muted)]"}`,children:[u.jsx(cy,{className:"h-4 w-4"}),"GitHub URL"]}),u.jsxs("button",{onClick:()=>e("upload"),className:`flex flex-1 items-center justify-center gap-2 rounded-md py-2 text-sm font-medium transition-colors ${t==="upload"?"bg-white text-[var(--ink)] shadow-sm":"text-[var(--muted)]"}`,children:[u.jsx(uc,{className:"h-4 w-4"}),"Upload zip"]})]}),u.jsxs("form",{onSubmit:d,className:"space-y-5",children:[t==="github"?u.jsx(vi,{label:"Repository URL",hint:"Public repos only for now. Private repo support is on the roadmap.",children:u.jsx(Yr,{value:n,onChange:h=>r(h.target.value),placeholder:"https://github.com/you/your-app",autoCapitalize:"off",autoCorrect:"off"})}):u.jsx(vi,{label:"Project zip",hint:"Max 50MB. We extract and analyze it in an isolated container.",children:u.jsxs("label",{className:"flex cursor-pointer items-center justify-center gap-3 rounded-lg border-2 border-dashed border-[var(--line-2)] px-4 py-8 text-sm text-[var(--muted)] transition-colors hover:border-[var(--brand)] hover:text-[var(--brand)]",children:[u.jsx(uc,{className:"h-5 w-5"}),s?u.jsx("span",{className:"font-medium text-[var(--ink)]",children:s.name}):"Click to upload a .zip",u.jsx("input",{type:"file",accept:".zip",className:"hidden",onChange:h=>{var f;return i(((f=h.target.files)==null?void 0:f[0])??null)}})]})}),l&&u.jsx("div",{className:"rounded-lg bg-red-50 px-3.5 py-2.5 text-sm text-red-700",children:l}),u.jsxs(H,{type:"submit",disabled:o,className:"w-full justify-center",children:[o?"Analyzing…":"Connect & analyze",!o&&u.jsx(Cl,{className:"h-4 w-4"})]})]})]}),u.jsx("div",{className:"mt-6 space-y-3",children:[{icon:ly,title:"Stack detection",desc:"Framework, package manager, build command."},{icon:ef,title:"Env var scan",desc:"We list required variable names — you fill the values."},{icon:yi,title:"Safety check",desc:"Size limits and pattern scan flag suspicious code."}].map(h=>u.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[u.jsx(h.icon,{className:"mt-0.5 h-4 w-4 shrink-0 text-[var(--muted)]"}),u.jsxs("div",{children:[u.jsx("span",{className:"font-medium text-[var(--ink)]",children:h.title}),u.jsxs("span",{className:"text-[var(--muted)]",children:[" — ",h.desc]})]})]},h.title))})]})}const Py={fix_failed:{title:"Auto-fix attempts exhausted",body:"Your plan's retry cap is reached. Upgrade for more automated fix attempts and priority review."},escalation:{title:"Waiting for manual review",body:"Standard SLA is 12 hours. Upgrade to cut that to under 2 hours with priority queue access."},free_tier:{title:"You're on the Free plan",body:"Unlock more projects, higher container resources, and faster escalation by upgrading."},limit_reached:{title:"Project limit reached",body:"Your current plan caps the number of projects you can deploy. Upgrade to add more."}};function jo({context:t,currentPlan:e,compact:n}){const{title:r,body:s}=Py[t],i=e==="free"?"pro":"scale";return n?u.jsxs("button",{onClick:()=>be("/upgrade"),className:"inline-flex items-center gap-1.5 rounded-lg bg-blue-50 px-3 py-1.5 text-xs font-medium text-[var(--brand)] transition-colors hover:bg-blue-100",children:[u.jsx(cc,{className:"h-3.5 w-3.5"}),"Upgrade to ",i==="pro"?"Pro":"Scale"]}):u.jsx("div",{className:"rounded-2xl border border-blue-200 bg-gradient-to-br from-blue-50 to-white p-6 animate-fade-in",children:u.jsxs("div",{className:"flex items-start gap-3",children:[u.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-[var(--brand)] text-white",children:t==="escalation"?u.jsx(gi,{className:"h-5 w-5"}):u.jsx(cc,{className:"h-5 w-5"})}),u.jsxs("div",{className:"flex-1",children:[u.jsx("h3",{className:"text-base font-semibold text-[var(--ink)]",children:r}),u.jsx("p",{className:"mt-1 text-sm text-[var(--muted)]",children:s}),u.jsxs("div",{className:"mt-4 flex items-center gap-3",children:[u.jsxs(H,{to:"/upgrade",children:["Upgrade for faster review",u.jsx(ny,{className:"h-4 w-4"})]}),u.jsx("span",{className:"text-xs text-[var(--muted)]",children:"Plans from $19/mo"})]})]})]})})}const hc=[{key:"ingesting",label:"Ingesting repo",icon:Zh},{key:"configuring",label:"Configuring schema & auth",icon:my},{key:"deploying",label:"Building & deploying",icon:os},{key:"fixing",label:"Auto-fixing errors",icon:Tl},{key:"live",label:"Live",icon:Vn}],Oy={ingesting:0,configuring:1,deploying:2,fixing:3,live:4,failed:3,escalated:3};function Ay({id:t}){const{profile:e}=fn(),[n,r]=T.useState(null),[s,i]=T.useState([]),[o,a]=T.useState(null),[l,c]=T.useState({}),[d,h]=T.useState(!1),[f,g]=T.useState(!1),[y,x]=T.useState(!1),[E,v]=T.useState(!1),[p,m]=T.useState(!1),[w,S]=T.useState(!1),[k,j]=T.useState(!1),[C,B]=T.useState(!1),[$,ge]=T.useState([{role:"assistant",text:"Hi! I'm your AI deployment assistant. Ask me anything about this project — its status, stack, env vars, or how to fix issues."}]),[Ze,xt]=T.useState(""),[pn,cs]=T.useState(!1),mn=T.useRef(null);if(T.useEffect(()=>{Q.from("projects").select("*").eq("id",t).maybeSingle().then(({data:P})=>{P&&r(P)}),Q.from("agent_logs").select("*").eq("project_id",t).order("created_at",{ascending:!0}).then(({data:P})=>i(P??[])),Q.from("escalations").select("*").eq("project_id",t).eq("status","open").order("created_at",{ascending:!1}).limit(1).maybeSingle().then(({data:P})=>a(P??null))},[t]),T.useEffect(()=>{const P=Q.channel(`project-status-${t}`).on("postgres_changes",{event:"*",schema:"public",table:"projects",filter:`id=eq.${t}`},Z=>{Z.new&&r(Z.new)}).on("postgres_changes",{event:"INSERT",schema:"public",table:"agent_logs",filter:`project_id=eq.${t}`},Z=>{Z.new&&i(We=>[...We,Z.new])}).subscribe();return()=>{Q.removeChannel(P)}},[t]),T.useEffect(()=>{var P;(P=mn.current)==null||P.scrollIntoView({behavior:"smooth"})},[$,pn]),!n)return u.jsx("div",{className:"flex min-h-[60vh] items-center justify-center",children:u.jsx(rn,{className:"h-6 w-6 text-[var(--brand)]"})});const Vt=Oy[n.status],b=n.status==="live",O=n.status==="failed",A=n.status==="escalated"||!!o,K=!b&&!A,te=async()=>{h(!0);try{await Ey(t,l),x(!0),setTimeout(()=>x(!1),2500)}finally{h(!1)}},vn=async()=>{m(!0);try{await Ny(t),r(P=>P&&{...P,status:"failed",subdomain:null}),v(!1)}finally{m(!1)}},at=async()=>{g(!0);try{await by(t)}finally{g(!1)}},ir=async()=>{j(!0);const{error:P}=await Q.from("projects").delete().eq("id",t);j(!1),P||be("/projects")},et=async()=>{if(!Ze.trim())return;const P=Ze.trim();xt(""),ge(Z=>[...Z,{role:"user",text:P}]),cs(!0);try{const{reply:Z}=await Cy(t,P);ge(We=>[...We,{role:"assistant",text:Z}])}catch(Z){ge(We=>[...We,{role:"assistant",text:Z instanceof Error?Z.message:"Assistant request failed."}])}finally{cs(!1)}},gn=o?new Date(o.sla_due_at).getTime()-Date.now():0,Pl=Math.max(0,Math.floor(gn/36e5));return u.jsxs("div",{className:"mx-auto max-w-3xl px-5 py-10",children:[u.jsxs("button",{onClick:()=>be("/projects"),className:"mb-6 inline-flex items-center gap-1.5 text-sm text-[var(--muted)] transition-colors hover:text-[var(--ink)]",children:[u.jsx(ty,{className:"h-4 w-4"}),"All projects"]}),u.jsxs("div",{className:"flex items-start justify-between gap-4",children:[u.jsxs("div",{children:[u.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-[var(--ink)]",children:n.name}),u.jsxs("p",{className:"mt-1 text-sm text-[var(--muted)]",children:[n.source_type==="github"?n.source_url:"Uploaded zip"," · ",n.subdomain]})]}),b&&n.subdomain&&u.jsxs("a",{href:`https://${n.subdomain}`,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 rounded-lg border border-[var(--line-2)] bg-white px-3.5 py-2 text-sm font-medium text-[var(--ink)] transition-colors hover:border-[var(--ink)]",children:["Visit site",u.jsx(ay,{className:"h-3.5 w-3.5"})]})]}),u.jsxs("div",{className:"mt-4 flex items-center gap-2",children:[u.jsxs(H,{onClick:at,disabled:f||n.status==="deploying",className:"text-sm",children:[u.jsx(os,{className:"h-4 w-4"}),f||n.status==="deploying"?"Deploying…":"Deploy"]}),n.status!=="failed"&&u.jsxs(H,{variant:"secondary",onClick:()=>v(!0),className:"text-sm",children:[u.jsx(oc,{className:"h-4 w-4"}),"Terminate deploy"]}),u.jsxs(H,{variant:"ghost",onClick:()=>S(!0),className:"text-sm text-red-600 hover:bg-red-50 hover:text-red-700",children:[u.jsx(lc,{className:"h-4 w-4"}),"Delete project"]})]}),n.safety_flag&&u.jsxs("div",{className:"mt-4 flex items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800",children:[u.jsx(yi,{className:"mt-0.5 h-4 w-4 shrink-0"}),u.jsx("span",{children:"Safety scan flagged this repo for review. An admin will check it before deploy proceeds."})]}),u.jsxs(pe,{className:"mt-8 p-6",children:[u.jsx("h2",{className:"text-sm font-semibold text-[var(--ink)]",children:"Deployment pipeline"}),u.jsx("div",{className:"mt-5",children:u.jsx("div",{className:"flex items-center",children:hc.map((P,Z)=>{const We=Zu.jsxs("div",{className:"grid grid-cols-[1fr_1.4fr] gap-3",children:[u.jsx("div",{className:"flex items-center rounded-lg bg-[var(--paper)] px-3 py-2 font-mono text-xs text-[var(--ink-2)]",children:P}),u.jsx(Yr,{type:"password",placeholder:"Enter value",value:l[P]??"",onChange:Z=>c(We=>({...We,[P]:Z.target.value}))})]},P)),u.jsxs("div",{className:"flex items-center gap-3 pt-1",children:[u.jsx(H,{onClick:te,disabled:d,variant:"secondary",children:d?"Saving…":"Save to .env"}),y&&u.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-emerald-600",children:[u.jsx(Vn,{className:"h-4 w-4"}),"Saved"]})]})]})]}),u.jsxs(pe,{className:"mt-6 p-6",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(sy,{className:"h-4 w-4 text-[var(--muted)]"}),u.jsx("h2",{className:"text-sm font-semibold text-[var(--ink)]",children:"Schema"})]}),u.jsx("p",{className:"mt-1 text-xs text-[var(--muted)]",children:"Schema source detected during ingestion. The schema-match agent validates field names and types against your code before applying."}),u.jsx("div",{className:"mt-3 rounded-lg bg-[var(--paper)] px-3.5 py-2.5 font-mono text-xs text-[var(--ink-2)]",children:n.schema_source??"No schema file found — flagged for user input."})]}),u.jsxs(pe,{className:"mt-6 p-6",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(hy,{className:"h-4 w-4 text-[var(--muted)]"}),u.jsx("h2",{className:"text-sm font-semibold text-[var(--ink)]",children:"Agent action history"})]}),s.length===0?u.jsx("p",{className:"mt-4 text-sm text-[var(--muted)]",children:"No agent actions yet."}):u.jsx("ol",{className:"mt-4 space-y-3",children:s.map(P=>u.jsxs("li",{className:"flex items-start gap-3 text-sm",children:[u.jsx("span",{className:`mt-1.5 h-2 w-2 shrink-0 rounded-full ${P.success?"bg-emerald-500":"bg-red-500"}`}),u.jsxs("div",{className:"flex-1",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("span",{className:"font-medium text-[var(--ink)]",children:P.agent}),u.jsx("span",{className:"text-xs text-[var(--muted)]",children:new Date(P.created_at).toLocaleString()})]}),u.jsxs("p",{className:"mt-0.5 text-[var(--muted)]",children:[P.action,P.token_cost>0&&` · ${P.token_cost} tokens`]})]})]},P.id))})]}),(e==null?void 0:e.plan_id)==="free"&&b&&u.jsx("div",{className:"mt-6",children:u.jsx(jo,{context:"free_tier",currentPlan:"free"})}),C&&u.jsxs("div",{className:"fixed inset-0 z-50 flex items-end justify-end p-4 sm:p-6",children:[u.jsx("div",{className:"absolute inset-0 bg-black/20 backdrop-blur-sm",onClick:()=>B(!1)}),u.jsxs("div",{className:"relative flex h-[28rem] w-full max-w-md flex-col overflow-hidden rounded-2xl border border-[var(--line-2)] bg-white shadow-2xl",children:[u.jsxs("div",{className:"flex items-center justify-between border-b border-[var(--line)] px-4 py-3",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-[var(--brand)] text-white",children:u.jsx(ic,{className:"h-4 w-4"})}),u.jsxs("div",{children:[u.jsx("p",{className:"text-sm font-semibold text-[var(--ink)]",children:"AI Assistant"}),u.jsx("p",{className:"text-xs text-[var(--muted)]",children:"Ask about this project"})]})]}),u.jsx("button",{onClick:()=>B(!1),className:"rounded-lg p-1.5 text-[var(--muted)] transition-colors hover:bg-[var(--paper)] hover:text-[var(--ink)]",children:u.jsx(nf,{className:"h-4 w-4"})})]}),u.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 space-y-3",children:[$.map((P,Z)=>u.jsx("div",{className:`flex ${P.role==="user"?"justify-end":"justify-start"}`,children:u.jsx("div",{className:`max-w-[80%] rounded-2xl px-3.5 py-2.5 text-sm ${P.role==="user"?"bg-[var(--brand)] text-white":"bg-[var(--paper)] text-[var(--ink)]"}`,children:P.text})},Z)),pn&&u.jsx("div",{className:"flex justify-start",children:u.jsx("div",{className:"rounded-2xl bg-[var(--paper)] px-3.5 py-2.5",children:u.jsx(rn,{className:"h-4 w-4 text-[var(--muted)]"})})}),u.jsx("div",{ref:mn})]}),u.jsx("div",{className:"border-t border-[var(--line)] p-3",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(Yr,{value:Ze,onChange:P=>xt(P.target.value),onKeyDown:P=>{P.key==="Enter"&&!P.shiftKey&&(P.preventDefault(),et())},placeholder:"Ask about status, stack, env vars...",className:"flex-1"}),u.jsx(H,{onClick:et,disabled:pn||!Ze.trim(),className:"px-3",children:u.jsx(py,{className:"h-4 w-4"})})]})})]})]}),!C&&u.jsx("button",{onClick:()=>B(!0),className:"fixed bottom-6 right-6 z-40 flex h-12 w-12 items-center justify-center rounded-full bg-[var(--brand)] text-white shadow-lg shadow-blue-500/30 transition-all hover:scale-105 hover:bg-[var(--brand-2)] active:scale-95",title:"AI Assistant",children:u.jsx(ic,{className:"h-5 w-5"})}),E&&u.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[u.jsx("div",{className:"absolute inset-0 bg-black/20 backdrop-blur-sm",onClick:()=>v(!1)}),u.jsxs(pe,{className:"relative w-full max-w-md p-6",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-red-50 text-red-600",children:u.jsx(oc,{className:"h-5 w-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"text-base font-semibold text-[var(--ink)]",children:"Terminate deployment"}),u.jsx("p",{className:"text-sm text-[var(--muted)]",children:"The app goes offline immediately."})]})]}),u.jsx("p",{className:"mt-4 text-sm text-[var(--muted)]",children:"This will take your app offline and clear its subdomain. The project itself is kept so you can redeploy later. This action cannot be undone."}),u.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[u.jsx(H,{variant:"secondary",onClick:()=>v(!1),children:"Cancel"}),u.jsx(H,{variant:"danger",onClick:vn,disabled:p,children:p?"Terminating…":"Terminate"})]})]})]}),w&&u.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[u.jsx("div",{className:"absolute inset-0 bg-black/20 backdrop-blur-sm",onClick:()=>S(!1)}),u.jsxs(pe,{className:"relative w-full max-w-md p-6",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-red-50 text-red-600",children:u.jsx(lc,{className:"h-5 w-5"})}),u.jsxs("div",{children:[u.jsx("h3",{className:"text-base font-semibold text-[var(--ink)]",children:"Delete project"}),u.jsx("p",{className:"text-sm text-[var(--muted)]",children:"Permanently remove this project."})]})]}),u.jsx("p",{className:"mt-4 text-sm text-[var(--muted)]",children:"This will permanently delete the project, its agent logs, escalations, and spend records. This action cannot be undone."}),u.jsxs("div",{className:"mt-6 flex justify-end gap-2",children:[u.jsx(H,{variant:"secondary",onClick:()=>S(!1),children:"Cancel"}),u.jsx(H,{variant:"danger",onClick:ir,disabled:k,children:k?"Deleting…":"Delete forever"})]})]})]})]})}const Ry=[{id:"free",name:"Free",price_cents:0,project_cap:1,ram_mb:512,cpu_cores:.5,fix_retry_cap:1,priority:0,features:["1 project","512MB RAM","1 auto-fix attempt","Standard 12h SLA"]},{id:"pro",name:"Pro",price_cents:1900,project_cap:5,ram_mb:2048,cpu_cores:1,fix_retry_cap:5,priority:1,features:["5 projects","2GB RAM","5 auto-fix attempts","Priority escalation","Email alerts"]},{id:"scale",name:"Scale",price_cents:4900,project_cap:25,ram_mb:4096,cpu_cores:2,fix_retry_cap:20,priority:2,features:["25 projects","4GB RAM","20 auto-fix attempts","Highest priority","Slack integration","Custom domains"]}];function $y(){const{profile:t,refreshProfile:e}=fn(),[n,r]=T.useState(Ry),[s,i]=T.useState(null);T.useEffect(()=>{Q.from("plans").select("*").order("price_cents",{ascending:!0}).then(({data:a})=>{a&&a.length&&r(a)})},[]);const o=async a=>{i(a),await Q.from("profiles").update({plan_id:a}).eq("id",t.id),await e(),i(null)};return t?u.jsxs("div",{className:"mx-auto max-w-4xl px-5 py-10",children:[u.jsxs("div",{className:"text-center",children:[u.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-[var(--ink)]",children:"Choose your plan"}),u.jsxs("p",{className:"mt-2 text-sm text-[var(--muted)]",children:["You're currently on ",u.jsx("span",{className:"font-medium capitalize text-[var(--ink)]",children:t.plan_id}),"."]})]}),u.jsx("div",{className:"mt-10 grid gap-6 lg:grid-cols-3",children:n.map(a=>{const l=a.id===t.plan_id,c=a.id==="pro";return u.jsxs(pe,{className:`relative flex flex-col p-7 ${c?"border-[var(--brand)] ring-1 ring-[var(--brand)]":""}`,children:[c&&!l&&u.jsx("span",{className:"absolute -top-3 left-7 rounded-full bg-[var(--brand)] px-3 py-1 text-xs font-medium text-white",children:"Most popular"}),u.jsx("h3",{className:"text-lg font-semibold text-[var(--ink)]",children:a.name}),u.jsxs("div",{className:"mt-2 flex items-baseline gap-1",children:[u.jsxs("span",{className:"text-4xl font-semibold tracking-tight text-[var(--ink)]",children:["$",a.price_cents/100]}),u.jsx("span",{className:"text-sm text-[var(--muted)]",children:"/mo"})]}),u.jsx("ul",{className:"mt-6 flex-1 space-y-3",children:a.features.map(d=>u.jsxs("li",{className:"flex items-start gap-2.5 text-sm text-[var(--ink-2)]",children:[u.jsx(Xh,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-500"}),d]},d))}),l?u.jsxs("div",{className:"mt-7 flex items-center justify-center gap-2 rounded-lg bg-emerald-50 py-2.5 text-sm font-medium text-emerald-700",children:[u.jsx(Vn,{className:"h-4 w-4"}),"Current plan"]}):u.jsx(H,{onClick:()=>o(a.id),disabled:s!==null,variant:c?"primary":"secondary",className:"mt-7 w-full justify-center",children:s===a.id?"Updating…":`Switch to ${a.name}`})]},a.id)})}),u.jsx("p",{className:"mt-6 text-center text-xs text-[var(--muted)]",children:"Billing is not yet wired in this demo — plan changes take effect immediately for testing."})]}):u.jsx("div",{className:"flex min-h-[60vh] items-center justify-center",children:u.jsx(rn,{className:"h-6 w-6 text-[var(--brand)]"})})}function Ly(){const{profile:t}=fn(),[e,n]=T.useState(null),[r,s]=T.useState(null),[i,o]=T.useState(null),[a,l]=T.useState(null);if(T.useEffect(()=>{Q.from("projects").select("id, name, status, created_at, profiles!inner(email, plan_id)").order("created_at",{ascending:!1}).then(({data:d})=>{const h=(d??[]).map(f=>{var g,y;return{id:f.id,name:f.name,status:f.status,created_at:f.created_at,user_email:((g=f.profiles)==null?void 0:g.email)??"—",plan_id:((y=f.profiles)==null?void 0:y.plan_id)??"free"}});n(h)}),Q.from("escalations").select("id, reason, status, sla_due_at, created_at, projects!inner(name), profiles!inner(email)").eq("status","open").order("sla_due_at",{ascending:!0}).then(({data:d})=>{const h=(d??[]).map(f=>{var g,y;return{id:f.id,reason:f.reason,status:f.status,sla_due_at:f.sla_due_at,created_at:f.created_at,project_name:((g=f.projects)==null?void 0:g.name)??"—",user_email:((y=f.profiles)==null?void 0:y.email)??"—"}});s(h)}),Q.from("api_spend").select("cost_micros").then(({data:d})=>{const h=(d??[]).reduce((f,g)=>f+Number(g.cost_micros??0),0);o(h)}),Q.from("profiles").select("id",{count:"exact",head:!0}).then(({count:d})=>{l(d??0)})},[]),!t||t.role!=="admin")return u.jsxs("div",{className:"mx-auto max-w-md px-5 py-20 text-center",children:[u.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--line)]",children:u.jsx(tf,{className:"h-6 w-6 text-[var(--muted)]"})}),u.jsx("h1",{className:"mt-4 text-xl font-semibold text-[var(--ink)]",children:"Admin access required"}),u.jsx("p",{className:"mt-2 text-sm text-[var(--muted)]",children:"This area is restricted to admin accounts."}),u.jsx(H,{to:"/projects",className:"mt-6",children:"Back to projects"})]});const c=[{icon:gy,label:"Users",value:a},{icon:uy,label:"Projects",value:e==null?void 0:e.length},{icon:ey,label:"Open escalations",value:r==null?void 0:r.length},{icon:iy,label:"API spend",value:i!=null?`$${(i/1e6).toFixed(2)}`:null}];return u.jsxs("div",{className:"mx-auto max-w-5xl px-5 py-10",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{children:[u.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-[var(--ink)]",children:"Admin"}),u.jsx("p",{className:"mt-1 text-sm text-[var(--muted)]",children:"Platform overview and escalation queue."})]}),u.jsxs(Dn,{tone:"brand",children:[u.jsx(ac,{className:"h-3 w-3"}),"Admin"]})]}),u.jsx("div",{className:"mt-8 grid grid-cols-2 gap-4 lg:grid-cols-4",children:c.map(d=>u.jsxs(pe,{className:"p-5",children:[u.jsxs("div",{className:"flex items-center gap-2 text-[var(--muted)]",children:[u.jsx(d.icon,{className:"h-4 w-4"}),u.jsx("span",{className:"text-xs font-medium",children:d.label})]}),u.jsx("div",{className:"mt-2 text-2xl font-semibold text-[var(--ink)]",children:d.value===null||d.value===void 0?u.jsx(rn,{className:"h-5 w-5"}):d.value})]},d.label))}),u.jsx("h2",{className:"mt-10 text-sm font-semibold text-[var(--ink)]",children:"Escalation queue"}),u.jsx(pe,{className:"mt-3 divide-y divide-[var(--line)]",children:r?r.length===0?u.jsx("p",{className:"p-6 text-sm text-[var(--muted)]",children:"No open escalations."}):r.map(d=>{const h=Math.max(0,Math.floor((new Date(d.sla_due_at).getTime()-Date.now())/36e5));return u.jsxs("div",{className:"flex items-center justify-between p-4",children:[u.jsxs("div",{children:[u.jsx("p",{className:"text-sm font-medium text-[var(--ink)]",children:d.project_name}),u.jsxs("p",{className:"text-xs text-[var(--muted)]",children:[d.user_email," · ",d.reason]})]}),u.jsxs(Dn,{tone:h<4?"error":"warning",children:[h,"h left"]})]},d.id)}):u.jsx("div",{className:"p-6",children:u.jsx(rn,{className:"h-5 w-5 text-[var(--brand)]"})})}),u.jsx("h2",{className:"mt-10 text-sm font-semibold text-[var(--ink)]",children:"All projects"}),u.jsx(pe,{className:"mt-3 divide-y divide-[var(--line)]",children:e?e.length===0?u.jsx("p",{className:"p-6 text-sm text-[var(--muted)]",children:"No projects yet."}):e.map(d=>u.jsxs("button",{onClick:()=>be(`/projects/${d.id}`),className:"flex w-full items-center justify-between p-4 text-left transition-colors hover:bg-[var(--paper)]",children:[u.jsxs("div",{children:[u.jsx("p",{className:"text-sm font-medium text-[var(--ink)]",children:d.name}),u.jsxs("p",{className:"text-xs text-[var(--muted)]",children:[d.user_email," · ",new Date(d.created_at).toLocaleDateString()]})]}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx("span",{className:"text-xs capitalize text-[var(--muted)]",children:d.plan_id}),u.jsx(Dn,{tone:d.status==="live"?"success":d.status==="escalated"||d.status==="failed"?"error":"brand",children:d.status})]})]},d.id)):u.jsx("div",{className:"p-6",children:u.jsx(rn,{className:"h-5 w-5 text-[var(--brand)]"})})}),u.jsxs("div",{className:"mt-10 rounded-2xl border border-dashed border-[var(--line-2)] p-6",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(ac,{className:"h-4 w-4 text-[var(--muted)]"}),u.jsx("h2",{className:"text-sm font-semibold text-[var(--ink)]",children:"Generate from scratch"}),u.jsx(Dn,{tone:"neutral",children:"Admin only"})]}),u.jsx("p",{className:"mt-1 text-xs text-[var(--muted)]",children:"Internal testing tool for the upcoming scaffold-based project generation feature. Hidden from regular users."}),u.jsx(H,{variant:"secondary",className:"mt-4",disabled:!0,children:"Coming soon"})]})]})}function Iy(){const[t,e]=T.useState(null),[n,r]=T.useState(!1);if(T.useEffect(()=>{const i=o=>{o.preventDefault(),e(o)};return window.addEventListener("beforeinstallprompt",i),()=>window.removeEventListener("beforeinstallprompt",i)},[]),!t||n)return null;const s=async()=>{await t.prompt(),e(null)};return u.jsx("div",{className:"fixed bottom-4 left-1/2 z-50 -translate-x-1/2 animate-fade-in",children:u.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-[var(--line)] bg-white px-4 py-3 shadow-lg",children:[u.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-[var(--ink)] text-white",children:u.jsx(oy,{className:"h-4 w-4"})}),u.jsxs("div",{className:"text-sm",children:[u.jsx("p",{className:"font-medium text-[var(--ink)]",children:"Install CodeAI"}),u.jsx("p",{className:"text-xs text-[var(--muted)]",children:"Add to your home screen for quick access"})]}),u.jsx("button",{onClick:s,className:"ml-2 rounded-lg bg-[var(--brand)] px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-[var(--brand-2)]",children:"Install"}),u.jsx("button",{onClick:()=>r(!0),className:"text-[var(--muted)] hover:text-[var(--ink)]",children:u.jsx(nf,{className:"h-4 w-4"})})]})})}function mr({children:t}){const{user:e,loading:n}=fn();return n?null:e?u.jsx(u.Fragment,{children:t}):(be("/login"),null)}function Uy(){const t=Yh();if(t==="/"||t==="")return u.jsx(xy,{});if(t==="/login")return u.jsx(dc,{mode:"login"});if(t==="/signup")return u.jsx(dc,{mode:"signup"});if(t==="/projects")return u.jsx(mr,{children:u.jsx(ky,{})});if(t==="/connect")return u.jsx(mr,{children:u.jsx(Ty,{})});if(t==="/upgrade")return u.jsx(mr,{children:u.jsx($y,{})});if(t==="/admin")return u.jsx(mr,{children:u.jsx(Ly,{})});const e=Qg(t,"/projects/:id");return e?u.jsx(mr,{children:u.jsx(Ay,{id:e.id})}):u.jsxs("div",{className:"flex min-h-[60vh] flex-col items-center justify-center text-center",children:[u.jsx("p",{className:"text-lg font-semibold text-[var(--ink)]",children:"Page not found"}),u.jsx(H,{to:"/",className:"mt-4",children:"Go home"})]})}function Dy(){const t=Yh(),e=t==="/"||t==="";return u.jsxs("div",{className:"min-h-screen bg-[var(--paper)]",children:[!e&&u.jsx(yy,{}),u.jsx("main",{children:u.jsx(Uy,{})}),u.jsx(Iy,{})]})}function My(){return u.jsx(Gg,{children:u.jsx(Dy,{})})}Eh(document.getElementById("root")).render(u.jsx(T.StrictMode,{children:u.jsx(My,{})}));