/")+"/"),ks(i,e,r,"",function(u){return u})):i!=null&&(xa(i)&&(i=om(i,r+(!i.key||o&&o.key===i.key?"":(""+i.key).replace(Ec,"/")+"/")+t)),e.push(i)),1;if(o=0,n=n===""?".":n+":",bc(t))for(var a=0;a{"use strict";Lc.exports=Nc()});var Wc=qt(Y=>{"use strict";function Oa(t,e){var r=t.length;t.push(e);e:for(;0>>1,i=t[n];if(0>>1;nEs(a,r))lEs(u,a)?(t[n]=u,t[l]=r,n=l):(t[n]=a,t[o]=r,n=o);else if(lEs(u,r))t[n]=u,t[l]=r,n=l;else break e}}return e}function Es(t,e){var r=t.sortIndex-e.sortIndex;return r!==0?r:t.id-e.id}typeof performance=="object"&&typeof performance.now=="function"?(jc=performance,Y.unstable_now=function(){return jc.now()}):(Ra=Date,Dc=Ra.now(),Y.unstable_now=function(){return Ra.now()-Dc});var jc,Ra,Dc,At=[],lr=[],cm=1,it=null,Ce=3,Rs=!1,jr=!1,ti=!1,zc=typeof setTimeout=="function"?setTimeout:null,Bc=typeof clearTimeout=="function"?clearTimeout:null,$c=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function Pa(t){for(var e=vt(lr);e!==null;){if(e.callback===null)xs(lr);else if(e.startTime<=t)xs(lr),e.sortIndex=e.expirationTime,Oa(At,e);else break;e=vt(lr)}}function Ia(t){if(ti=!1,Pa(t),!jr)if(vt(At)!==null)jr=!0,La(Na);else{var e=vt(lr);e!==null&&ja(Ia,e.startTime-t)}}function Na(t,e){jr=!1,ti&&(ti=!1,Bc(ri),ri=-1),Rs=!0;var r=Ce;try{for(Pa(e),it=vt(At);it!==null&&(!(it.expirationTime>e)||t&&!Hc());){var n=it.callback;if(typeof n=="function"){it.callback=null,Ce=it.priorityLevel;var i=n(it.expirationTime<=e);e=Y.unstable_now(),typeof i=="function"?it.callback=i:it===vt(At)&&xs(At),Pa(e)}else xs(At);it=vt(At)}if(it!==null)var s=!0;else{var o=vt(lr);o!==null&&ja(Ia,o.startTime-e),s=!1}return s}finally{it=null,Ce=r,Rs=!1}}var Cs=!1,Ts=null,ri=-1,Mc=5,Fc=-1;function Hc(){return!(Y.unstable_now()-Fct||125n?(t.sortIndex=r,Oa(lr,t),vt(At)===null&&t===vt(lr)&&(ti?(Bc(ri),ri=-1):ti=!0,ja(Ia,r-n))):(t.sortIndex=i,Oa(At,t),jr||Rs||(jr=!0,La(Na))),t};Y.unstable_shouldYield=Hc;Y.unstable_wrapCallback=function(t){var e=Ce;return function(){var r=Ce;Ce=e;try{return t.apply(this,arguments)}finally{Ce=r}}}});var Vc=qt((Ow,qc)=>{"use strict";qc.exports=Wc()});var Qf=qt(Ze=>{"use strict";var dm=$e(),Qe=Vc();function E(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),il=Object.prototype.hasOwnProperty,hm=/^[: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]*$/,Kc={},Gc={};function fm(t){return il.call(Gc,t)?!0:il.call(Kc,t)?!1:hm.test(t)?Gc[t]=!0:(Kc[t]=!0,!1)}function pm(t,e,r,n){if(r!==null&&r.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(t=t.toLowerCase().slice(0,5),t!=="data-"&&t!=="aria-");default:return!1}}function gm(t,e,r,n){if(e===null||typeof e>"u"||pm(t,e,r,n))return!0;if(n)return!1;if(r!==null)switch(r.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 Be(t,e,r,n,i,s,o){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=t,this.type=e,this.sanitizeURL=s,this.removeEmptyString=o}var Re={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){Re[t]=new Be(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];Re[e]=new Be(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){Re[t]=new Be(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){Re[t]=new Be(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){Re[t]=new Be(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){Re[t]=new Be(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){Re[t]=new Be(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){Re[t]=new Be(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){Re[t]=new Be(t,5,!1,t.toLowerCase(),null,!1,!1)});var Xl=/[\-:]([a-z])/g;function Ql(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(Xl,Ql);Re[e]=new Be(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(Xl,Ql);Re[e]=new Be(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(Xl,Ql);Re[e]=new Be(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){Re[t]=new Be(t,1,!1,t.toLowerCase(),null,!1,!1)});Re.xlinkHref=new Be("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){Re[t]=new Be(t,1,!1,t.toLowerCase(),null,!0,!0)});function Yl(t,e,r,n){var i=Re.hasOwnProperty(e)?Re[e]:null;(i!==null?i.type!==0:n||!(2a||i[o]!==s[a]){var l=`
`+i[o].replace(" at new "," at ");return t.displayName&&l.includes("")&&(l=l.replace("",t.displayName)),l}while(1<=o&&0<=a);break}}}finally{$a=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?di(t):""}function mm(t){switch(t.tag){case 5:return di(t.type);case 16:return di("Lazy");case 13:return di("Suspense");case 19:return di("SuspenseList");case 0:case 2:case 15:return t=Ua(t.type,!1),t;case 11:return t=Ua(t.type.render,!1),t;case 1:return t=Ua(t.type,!0),t;default:return""}}function ll(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 dn:return"Fragment";case cn:return"Portal";case sl:return"Profiler";case Zl:return"StrictMode";case ol:return"Suspense";case al:return"SuspenseList"}if(typeof t=="object")switch(t.$typeof){case th:return(t.displayName||"Context")+".Consumer";case eh:return(t._context.displayName||"Context")+".Provider";case eu:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case tu:return e=t.displayName||null,e!==null?e:ll(t.type)||"Memo";case cr:e=t._payload,t=t._init;try{return ll(t(e))}catch{}}return null}function ym(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 ll(e);case 8:return e===Zl?"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 Er(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function nh(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function vm(t){var e=nh(t)?"checked":"value",r=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),n=""+t[e];if(!t.hasOwnProperty(e)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var i=r.get,s=r.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return i.call(this)},set:function(o){n=""+o,s.call(this,o)}}),Object.defineProperty(t,e,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(o){n=""+o},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function Os(t){t._valueTracker||(t._valueTracker=vm(t))}function ih(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=nh(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function io(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 ul(t,e){var r=e.checked;return le({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function Xc(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=Er(e.value!=null?e.value:r),t._wrapperState={initialChecked:n,initialValue:r,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function sh(t,e){e=e.checked,e!=null&&Yl(t,"checked",e,!1)}function cl(t,e){sh(t,e);var r=Er(e.value),n=e.type;if(r!=null)n==="number"?(r===0&&t.value===""||t.value!=r)&&(t.value=""+r):t.value!==""+r&&(t.value=""+r);else if(n==="submit"||n==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?dl(t,e.type,r):e.hasOwnProperty("defaultValue")&&dl(t,e.type,Er(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function Qc(t,e,r){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var n=e.type;if(!(n!=="submit"&&n!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,r||e===t.value||(t.value=e),t.defaultValue=e}r=t.name,r!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,r!==""&&(t.name=r)}function dl(t,e,r){(e!=="number"||io(t.ownerDocument)!==t)&&(r==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+r&&(t.defaultValue=""+r))}var hi=Array.isArray;function kn(t,e,r,n){if(t=t.options,e){e={};for(var i=0;i"+e.valueOf().toString()+"",e=Ps.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function Ti(t,e){if(e){var r=t.firstChild;if(r&&r===t.lastChild&&r.nodeType===3){r.nodeValue=e;return}}t.textContent=e}var gi={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},wm=["Webkit","ms","Moz","O"];Object.keys(gi).forEach(function(t){wm.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),gi[e]=gi[t]})});function uh(t,e,r){return e==null||typeof e=="boolean"||e===""?"":r||typeof e!="number"||e===0||gi.hasOwnProperty(t)&&gi[t]?(""+e).trim():e+"px"}function ch(t,e){t=t.style;for(var r in e)if(e.hasOwnProperty(r)){var n=r.indexOf("--")===0,i=uh(r,e[r],n);r==="float"&&(r="cssFloat"),n?t.setProperty(r,i):t[r]=i}}var _m=le({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 pl(t,e){if(e){if(_m[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(E(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(E(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(E(61))}if(e.style!=null&&typeof e.style!="object")throw Error(E(62))}}function gl(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 ml=null;function ru(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var yl=null,bn=null,En=null;function ed(t){if(t=Hi(t)){if(typeof yl!="function")throw Error(E(280));var e=t.stateNode;e&&(e=No(e),yl(t.stateNode,t.type,e))}}function dh(t){bn?En?En.push(t):En=[t]:bn=t}function hh(){if(bn){var t=bn,e=En;if(En=bn=null,ed(t),e)for(t=0;t>>=0,t===0?32:31-(Pm(t)/Im|0)|0}var Is=64,Ns=4194304;function fi(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 lo(t,e){var r=t.pendingLanes;if(r===0)return 0;var n=0,i=t.suspendedLanes,s=t.pingedLanes,o=r&268435455;if(o!==0){var a=o&~i;a!==0?n=fi(a):(s&=o,s!==0&&(n=fi(s)))}else o=r&~i,o!==0?n=fi(o):s!==0&&(n=fi(s));if(n===0)return 0;if(e!==0&&e!==n&&!(e&i)&&(i=n&-n,s=e&-e,i>=s||i===16&&(s&4194240)!==0))return e;if(n&4&&(n|=r&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=n;0r;r++)e.push(t);return e}function Mi(t,e,r){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-bt(e),t[e]=r}function Dm(t,e){var r=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 n=t.eventTimes;for(t=t.expirationTimes;0=yi),ud=" ",cd=!1;function Ih(t,e){switch(t){case"keyup":return cy.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Nh(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var hn=!1;function hy(t,e){switch(t){case"compositionend":return Nh(e);case"keypress":return e.which!==32?null:(cd=!0,ud);case"textInput":return t=e.data,t===ud&&cd?null:t;default:return null}}function fy(t,e){if(hn)return t==="compositionend"||!cu&&Ih(t,e)?(t=Oh(),Js=au=pr=null,hn=!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:r,offset:e-t};t=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=fd(r)}}function $h(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?$h(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Uh(){for(var t=window,e=io();e instanceof t.HTMLIFrameElement;){try{var r=typeof e.contentWindow.location.href=="string"}catch{r=!1}if(r)t=e.contentWindow;else break;e=io(t.document)}return e}function du(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 ky(t){var e=Uh(),r=t.focusedElem,n=t.selectionRange;if(e!==r&&r&&r.ownerDocument&&$h(r.ownerDocument.documentElement,r)){if(n!==null&&du(r)){if(e=n.start,t=n.end,t===void 0&&(t=e),"selectionStart"in r)r.selectionStart=e,r.selectionEnd=Math.min(t,r.value.length);else if(t=(e=r.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var i=r.textContent.length,s=Math.min(n.start,i);n=n.end===void 0?s:Math.min(n.end,i),!t.extend&&s>n&&(i=n,n=s,s=i),i=pd(r,s);var o=pd(r,n);i&&o&&(t.rangeCount!==1||t.anchorNode!==i.node||t.anchorOffset!==i.offset||t.focusNode!==o.node||t.focusOffset!==o.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),t.removeAllRanges(),s>n?(t.addRange(e),t.extend(o.node,o.offset)):(e.setEnd(o.node,o.offset),t.addRange(e)))}}for(e=[],t=r;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,fn=null,bl=null,wi=null,El=!1;function gd(t,e,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;El||fn==null||fn!==io(n)||(n=fn,"selectionStart"in n&&du(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),wi&&Pi(wi,n)||(wi=n,n=ho(bl,"onSelect"),0mn||(t.current=Ol[mn],Ol[mn]=null,mn--)}function Z(t,e){mn++,Ol[mn]=t.current,t.current=e}var Tr={},Ie=Rr(Tr),He=Rr(!1),Hr=Tr;function An(t,e){var r=t.type.contextTypes;if(!r)return Tr;var n=t.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in r)i[s]=e[s];return n&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=i),i}function We(t){return t=t.childContextTypes,t!=null}function po(){ne(He),ne(Ie)}function Ed(t,e,r){if(Ie.current!==Tr)throw Error(E(168));Z(Ie,e),Z(He,r)}function Kh(t,e,r){var n=t.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var i in n)if(!(i in e))throw Error(E(108,ym(t)||"Unknown",i));return le({},r,n)}function go(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||Tr,Hr=Ie.current,Z(Ie,t),Z(He,He.current),!0}function Td(t,e,r){var n=t.stateNode;if(!n)throw Error(E(169));r?(t=Kh(t,e,Hr),n.__reactInternalMemoizedMergedChildContext=t,ne(He),ne(Ie),Z(Ie,t)):ne(He),Z(He,r)}var Kt=null,Lo=!1,Ja=!1;function Gh(t){Kt===null?Kt=[t]:Kt.push(t)}function Iy(t){Lo=!0,Gh(t)}function Cr(){if(!Ja&&Kt!==null){Ja=!0;var t=0,e=Q;try{var r=Kt;for(Q=1;t>=o,i-=o,Gt=1<<32-bt(e)+i|r<P?(H=S,S=null):H=S.sibling;var x=p(f,S,g[P],_);if(x===null){S===null&&(S=H);break}t&&S&&x.alternate===null&&e(f,S),h=s(x,h,P),w===null?k=x:w.sibling=x,w=x,S=H}if(P===g.length)return r(f,S),se&&Dr(f,P),k;if(S===null){for(;PP?(H=S,S=null):H=S.sibling;var X=p(f,S,x.value,_);if(X===null){S===null&&(S=H);break}t&&S&&X.alternate===null&&e(f,S),h=s(X,h,P),w===null?k=X:w.sibling=X,w=X,S=H}if(x.done)return r(f,S),se&&Dr(f,P),k;if(S===null){for(;!x.done;P++,x=g.next())x=d(f,x.value,_),x!==null&&(h=s(x,h,P),w===null?k=x:w.sibling=x,w=x);return se&&Dr(f,P),k}for(S=n(f,S);!x.done;P++,x=g.next())x=m(S,f,P,x.value,_),x!==null&&(t&&x.alternate!==null&&S.delete(x.key===null?P:x.key),h=s(x,h,P),w===null?k=x:w.sibling=x,w=x);return t&&S.forEach(function(ar){return e(f,ar)}),se&&Dr(f,P),k}function b(f,h,g,_){if(typeof g=="object"&&g!==null&&g.type===dn&&g.key===null&&(g=g.props.children),typeof g=="object"&&g!==null){switch(g.$typeof){case As:e:{for(var k=g.key,w=h;w!==null;){if(w.key===k){if(k=g.type,k===dn){if(w.tag===7){r(f,w.sibling),h=i(w,g.props.children),h.return=f,f=h;break e}}else if(w.elementType===k||typeof k=="object"&&k!==null&&k.$typeof===cr&&Cd(k)===w.type){r(f,w.sibling),h=i(w,g.props),h.ref=ai(f,w,g),h.return=f,f=h;break e}r(f,w);break}else e(f,w);w=w.sibling}g.type===dn?(h=Fr(g.props.children,f.mode,_,g.key),h.return=f,f=h):(_=no(g.type,g.key,g.props,null,f.mode,_),_.ref=ai(f,h,g),_.return=f,f=_)}return o(f);case cn:e:{for(w=g.key;h!==null;){if(h.key===w)if(h.tag===4&&h.stateNode.containerInfo===g.containerInfo&&h.stateNode.implementation===g.implementation){r(f,h.sibling),h=i(h,g.children||[]),h.return=f,f=h;break e}else{r(f,h);break}else e(f,h);h=h.sibling}h=nl(g,f.mode,_),h.return=f,f=h}return o(f);case cr:return w=g._init,b(f,h,w(g._payload),_)}if(hi(g))return y(f,h,g,_);if(ni(g))return v(f,h,g,_);Ws(f,g)}return typeof g=="string"&&g!==""||typeof g=="number"?(g=""+g,h!==null&&h.tag===6?(r(f,h.sibling),h=i(h,g),h.return=f,f=h):(r(f,h),h=rl(g,f.mode,_),h.return=f,f=h),o(f)):r(f,h)}return b}var Pn=Yh(!0),Zh=Yh(!1),vo=Rr(null),wo=null,wn=null,gu=null;function mu(){gu=wn=wo=null}function yu(t){var e=vo.current;ne(vo),t._currentValue=e}function Nl(t,e,r){for(;t!==null;){var n=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,n!==null&&(n.childLanes|=e)):n!==null&&(n.childLanes&e)!==e&&(n.childLanes|=e),t===r)break;t=t.return}}function xn(t,e){wo=t,gu=wn=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(Fe=!0),t.firstContext=null)}function ut(t){var e=t._currentValue;if(gu!==t)if(t={context:t,memoizedValue:e,next:null},wn===null){if(wo===null)throw Error(E(308));wn=t,wo.dependencies={lanes:0,firstContext:t}}else wn=wn.next=t;return e}var zr=null;function vu(t){zr===null?zr=[t]:zr.push(t)}function ef(t,e,r,n){var i=e.interleaved;return i===null?(r.next=r,vu(e)):(r.next=i.next,i.next=r),e.interleaved=r,Zt(t,n)}function Zt(t,e){t.lanes|=e;var r=t.alternate;for(r!==null&&(r.lanes|=e),r=t,t=t.return;t!==null;)t.childLanes|=e,r=t.alternate,r!==null&&(r.childLanes|=e),r=t,t=t.return;return r.tag===3?r.stateNode:null}var dr=!1;function wu(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function tf(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 Xt(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function _r(t,e,r){var n=t.updateQueue;if(n===null)return null;if(n=n.shared,G&2){var i=n.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),n.pending=e,Zt(t,r)}return i=n.interleaved,i===null?(e.next=e,vu(n)):(e.next=i.next,i.next=e),n.interleaved=e,Zt(t,r)}function Qs(t,e,r){if(e=e.updateQueue,e!==null&&(e=e.shared,(r&4194240)!==0)){var n=e.lanes;n&=t.pendingLanes,r|=n,e.lanes=r,iu(t,r)}}function Ad(t,e){var r=t.updateQueue,n=t.alternate;if(n!==null&&(n=n.updateQueue,r===n)){var i=null,s=null;if(r=r.firstBaseUpdate,r!==null){do{var o={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};s===null?i=s=o:s=s.next=o,r=r.next}while(r!==null);s===null?i=s=e:s=s.next=e}else i=s=e;r={baseState:n.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:n.shared,effects:n.effects},t.updateQueue=r;return}t=r.lastBaseUpdate,t===null?r.firstBaseUpdate=e:t.next=e,r.lastBaseUpdate=e}function _o(t,e,r,n){var i=t.updateQueue;dr=!1;var s=i.firstBaseUpdate,o=i.lastBaseUpdate,a=i.shared.pending;if(a!==null){i.shared.pending=null;var l=a,u=l.next;l.next=null,o===null?s=u:o.next=u,o=l;var c=t.alternate;c!==null&&(c=c.updateQueue,a=c.lastBaseUpdate,a!==o&&(a===null?c.firstBaseUpdate=u:a.next=u,c.lastBaseUpdate=l))}if(s!==null){var d=i.baseState;o=0,c=u=l=null,a=s;do{var p=a.lane,m=a.eventTime;if((n&p)===p){c!==null&&(c=c.next={eventTime:m,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var y=t,v=a;switch(p=e,m=r,v.tag){case 1:if(y=v.payload,typeof y=="function"){d=y.call(m,d,p);break e}d=y;break e;case 3:y.flags=y.flags&-65537|128;case 0:if(y=v.payload,p=typeof y=="function"?y.call(m,d,p):y,p==null)break e;d=le({},d,p);break e;case 2:dr=!0}}a.callback!==null&&a.lane!==0&&(t.flags|=64,p=i.effects,p===null?i.effects=[a]:p.push(a))}else m={eventTime:m,lane:p,tag:a.tag,payload:a.payload,callback:a.callback,next:null},c===null?(u=c=m,l=d):c=c.next=m,o|=p;if(a=a.next,a===null){if(a=i.shared.pending,a===null)break;p=a,a=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(!0);if(c===null&&(l=d),i.baseState=l,i.firstBaseUpdate=u,i.lastBaseUpdate=c,e=i.shared.interleaved,e!==null){i=e;do o|=i.lane,i=i.next;while(i!==e)}else s===null&&(i.shared.lanes=0);Vr|=o,t.lanes=o,t.memoizedState=d}}function Od(t,e,r){if(t=e.effects,e.effects=null,t!==null)for(e=0;er?r:4,t(!0);var n=Qa.transition;Qa.transition={};try{t(!1),e()}finally{Q=r,Qa.transition=n}}function wf(){return ct().memoizedState}function Dy(t,e,r){var n=kr(t);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},_f(t))Sf(e,r);else if(r=ef(t,e,r,n),r!==null){var i=ze();Et(r,t,n,i),kf(r,e,n)}}function $y(t,e,r){var n=kr(t),i={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(_f(t))Sf(e,i);else{var s=t.alternate;if(t.lanes===0&&(s===null||s.lanes===0)&&(s=e.lastRenderedReducer,s!==null))try{var o=e.lastRenderedState,a=s(o,r);if(i.hasEagerState=!0,i.eagerState=a,Tt(a,o)){var l=e.interleaved;l===null?(i.next=i,vu(e)):(i.next=l.next,l.next=i),e.interleaved=i;return}}catch{}finally{}r=ef(t,e,i,n),r!==null&&(i=ze(),Et(r,t,n,i),kf(r,e,n))}}function _f(t){var e=t.alternate;return t===ae||e!==null&&e===ae}function Sf(t,e){_i=ko=!0;var r=t.pending;r===null?e.next=e:(e.next=r.next,r.next=e),t.pending=e}function kf(t,e,r){if(r&4194240){var n=e.lanes;n&=t.pendingLanes,r|=n,e.lanes=r,iu(t,r)}}var bo={readContext:ut,useCallback:Ae,useContext:Ae,useEffect:Ae,useImperativeHandle:Ae,useInsertionEffect:Ae,useLayoutEffect:Ae,useMemo:Ae,useReducer:Ae,useRef:Ae,useState:Ae,useDebugValue:Ae,useDeferredValue:Ae,useTransition:Ae,useMutableSource:Ae,useSyncExternalStore:Ae,useId:Ae,unstable_isNewReconciler:!1},Uy={readContext:ut,useCallback:function(t,e){return Pt().memoizedState=[t,e===void 0?null:e],t},useContext:ut,useEffect:Id,useImperativeHandle:function(t,e,r){return r=r!=null?r.concat([t]):null,Zs(4194308,4,pf.bind(null,e,t),r)},useLayoutEffect:function(t,e){return Zs(4194308,4,t,e)},useInsertionEffect:function(t,e){return Zs(4,2,t,e)},useMemo:function(t,e){var r=Pt();return e=e===void 0?null:e,t=t(),r.memoizedState=[t,e],t},useReducer:function(t,e,r){var n=Pt();return e=r!==void 0?r(e):e,n.memoizedState=n.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},n.queue=t,t=t.dispatch=Dy.bind(null,ae,t),[n.memoizedState,t]},useRef:function(t){var e=Pt();return t={current:t},e.memoizedState=t},useState:Pd,useDebugValue:Ru,useDeferredValue:function(t){return Pt().memoizedState=t},useTransition:function(){var t=Pd(!1),e=t[0];return t=jy.bind(null,t[1]),Pt().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,r){var n=ae,i=Pt();if(se){if(r===void 0)throw Error(E(407));r=r()}else{if(r=e(),be===null)throw Error(E(349));qr&30||of(n,e,r)}i.memoizedState=r;var s={value:r,getSnapshot:e};return i.queue=s,Id(lf.bind(null,n,s,t),[t]),n.flags|=2048,zi(9,af.bind(null,n,s,r,e),void 0,null),r},useId:function(){var t=Pt(),e=be.identifierPrefix;if(se){var r=Jt,n=Gt;r=(n&~(1<<32-bt(n)-1)).toString(32)+r,e=":"+e+"R"+r,r=$i++,0<\/script>",t=t.removeChild(t.firstChild)):typeof n.is=="string"?t=o.createElement(r,{is:n.is}):(t=o.createElement(r),r==="select"&&(o=t,n.multiple?o.multiple=!0:n.size&&(o.size=n.size))):t=o.createElementNS(t,r),t[It]=e,t[Li]=n,If(t,e,!1,!1),e.stateNode=t;e:{switch(o=gl(r,n),r){case"dialog":re("cancel",t),re("close",t),i=n;break;case"iframe":case"object":case"embed":re("load",t),i=n;break;case"video":case"audio":for(i=0;iLn&&(e.flags|=128,n=!0,li(s,!1),e.lanes=4194304)}else{if(!n)if(t=So(o),t!==null){if(e.flags|=128,n=!0,r=t.updateQueue,r!==null&&(e.updateQueue=r,e.flags|=4),li(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!se)return Oe(e),null}else 2*ge()-s.renderingStartTime>Ln&&r!==1073741824&&(e.flags|=128,n=!0,li(s,!1),e.lanes=4194304);s.isBackwards?(o.sibling=e.child,e.child=o):(r=s.last,r!==null?r.sibling=o:e.child=o,s.last=o)}return s.tail!==null?(e=s.tail,s.rendering=e,s.tail=e.sibling,s.renderingStartTime=ge(),e.sibling=null,r=oe.current,Z(oe,n?r&1|2:r&1),e):(Oe(e),null);case 22:case 23:return Nu(),n=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?Ge&1073741824&&(Oe(e),e.subtreeFlags&6&&(e.flags|=8192)):Oe(e),null;case 24:return null;case 25:return null}throw Error(E(156,e.tag))}function Vy(t,e){switch(fu(e),e.tag){case 1:return We(e.type)&&po(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return In(),ne(He),ne(Ie),ku(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return Su(e),null;case 13:if(ne(oe),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(E(340));On()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return ne(oe),null;case 4:return In(),null;case 10:return yu(e.type._context),null;case 22:case 23:return Nu(),null;case 24:return null;default:return null}}var Vs=!1,Pe=!1,Ky=typeof WeakSet=="function"?WeakSet:Set,N=null;function _n(t,e){var r=t.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){de(t,e,n)}else r.current=null}function Fl(t,e,r){try{r()}catch(n){de(t,e,n)}}var Hd=!1;function Gy(t,e){if(Tl=uo,t=Uh(),du(t)){if("selectionStart"in t)var r={start:t.selectionStart,end:t.selectionEnd};else e:{r=(r=t.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var i=n.anchorOffset,s=n.focusNode;n=n.focusOffset;try{r.nodeType,s.nodeType}catch{r=null;break e}var o=0,a=-1,l=-1,u=0,c=0,d=t,p=null;t:for(;;){for(var m;d!==r||i!==0&&d.nodeType!==3||(a=o+i),d!==s||n!==0&&d.nodeType!==3||(l=o+n),d.nodeType===3&&(o+=d.nodeValue.length),(m=d.firstChild)!==null;)p=d,d=m;for(;;){if(d===t)break t;if(p===r&&++u===i&&(a=o),p===s&&++c===n&&(l=o),(m=d.nextSibling)!==null)break;d=p,p=d.parentNode}d=m}r=a===-1||l===-1?null:{start:a,end:l}}else r=null}r=r||{start:0,end:0}}else r=null;for(xl={focusedElem:t,selectionRange:r},uo=!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 v=y.memoizedProps,b=y.memoizedState,f=e.stateNode,h=f.getSnapshotBeforeUpdate(e.elementType===e.type?v:_t(e.type,v),b);f.__reactInternalSnapshotBeforeUpdate=h}break;case 3:var g=e.stateNode.containerInfo;g.nodeType===1?g.textContent="":g.nodeType===9&&g.documentElement&&g.removeChild(g.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(E(163))}}catch(_){de(e,e.return,_)}if(t=e.sibling,t!==null){t.return=e.return,N=t;break}N=e.return}return y=Hd,Hd=!1,y}function Si(t,e,r){var n=e.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var i=n=n.next;do{if((i.tag&t)===t){var s=i.destroy;i.destroy=void 0,s!==void 0&&Fl(e,r,s)}i=i.next}while(i!==n)}}function $o(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var r=e=e.next;do{if((r.tag&t)===t){var n=r.create;r.destroy=n()}r=r.next}while(r!==e)}}function Hl(t){var e=t.ref;if(e!==null){var r=t.stateNode;switch(t.tag){case 5:t=r;break;default:t=r}typeof e=="function"?e(t):e.current=t}}function jf(t){var e=t.alternate;e!==null&&(t.alternate=null,jf(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[It],delete e[Li],delete e[Al],delete e[Oy],delete e[Py])),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 Df(t){return t.tag===5||t.tag===3||t.tag===4}function Wd(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Df(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 Wl(t,e,r){var n=t.tag;if(n===5||n===6)t=t.stateNode,e?r.nodeType===8?r.parentNode.insertBefore(t,e):r.insertBefore(t,e):(r.nodeType===8?(e=r.parentNode,e.insertBefore(t,r)):(e=r,e.appendChild(t)),r=r._reactRootContainer,r!=null||e.onclick!==null||(e.onclick=fo));else if(n!==4&&(t=t.child,t!==null))for(Wl(t,e,r),t=t.sibling;t!==null;)Wl(t,e,r),t=t.sibling}function ql(t,e,r){var n=t.tag;if(n===5||n===6)t=t.stateNode,e?r.insertBefore(t,e):r.appendChild(t);else if(n!==4&&(t=t.child,t!==null))for(ql(t,e,r),t=t.sibling;t!==null;)ql(t,e,r),t=t.sibling}var Te=null,St=!1;function ur(t,e,r){for(r=r.child;r!==null;)$f(t,e,r),r=r.sibling}function $f(t,e,r){if(Nt&&typeof Nt.onCommitFiberUnmount=="function")try{Nt.onCommitFiberUnmount(Ao,r)}catch{}switch(r.tag){case 5:Pe||_n(r,e);case 6:var n=Te,i=St;Te=null,ur(t,e,r),Te=n,St=i,Te!==null&&(St?(t=Te,r=r.stateNode,t.nodeType===8?t.parentNode.removeChild(r):t.removeChild(r)):Te.removeChild(r.stateNode));break;case 18:Te!==null&&(St?(t=Te,r=r.stateNode,t.nodeType===8?Ga(t.parentNode,r):t.nodeType===1&&Ga(t,r),Ai(t)):Ga(Te,r.stateNode));break;case 4:n=Te,i=St,Te=r.stateNode.containerInfo,St=!0,ur(t,e,r),Te=n,St=i;break;case 0:case 11:case 14:case 15:if(!Pe&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){i=n=n.next;do{var s=i,o=s.destroy;s=s.tag,o!==void 0&&(s&2||s&4)&&Fl(r,e,o),i=i.next}while(i!==n)}ur(t,e,r);break;case 1:if(!Pe&&(_n(r,e),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(a){de(r,e,a)}ur(t,e,r);break;case 21:ur(t,e,r);break;case 22:r.mode&1?(Pe=(n=Pe)||r.memoizedState!==null,ur(t,e,r),Pe=n):ur(t,e,r);break;default:ur(t,e,r)}}function qd(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var r=t.stateNode;r===null&&(r=t.stateNode=new Ky),e.forEach(function(n){var i=nv.bind(null,t,n);r.has(n)||(r.add(n),n.then(i,i))})}}function wt(t,e){var r=e.deletions;if(r!==null)for(var n=0;ni&&(i=o),n&=~s}if(n=i,n=ge()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*Xy(n/1960))-n,10t?16:t,gr===null)var n=!1;else{if(t=gr,gr=null,xo=0,G&6)throw Error(E(331));var i=G;for(G|=4,N=t.current;N!==null;){var s=N,o=s.child;if(N.flags&16){var a=s.deletions;if(a!==null){for(var l=0;lge()-Pu?Mr(t,0):Ou|=r),qe(t,e)}function qf(t,e){e===0&&(t.mode&1?(e=Ns,Ns<<=1,!(Ns&130023424)&&(Ns=4194304)):e=1);var r=ze();t=Zt(t,e),t!==null&&(Mi(t,e,r),qe(t,r))}function rv(t){var e=t.memoizedState,r=0;e!==null&&(r=e.retryLane),qf(t,r)}function nv(t,e){var r=0;switch(t.tag){case 13:var n=t.stateNode,i=t.memoizedState;i!==null&&(r=i.retryLane);break;case 19:n=t.stateNode;break;default:throw Error(E(314))}n!==null&&n.delete(e),qf(t,r)}var Vf;Vf=function(t,e,r){if(t!==null)if(t.memoizedProps!==e.pendingProps||He.current)Fe=!0;else{if(!(t.lanes&r)&&!(e.flags&128))return Fe=!1,Wy(t,e,r);Fe=!!(t.flags&131072)}else Fe=!1,se&&e.flags&1048576&&Jh(e,yo,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;eo(t,e),t=e.pendingProps;var i=An(e,Ie.current);xn(e,r),i=Eu(null,e,n,t,i,r);var s=Tu();return e.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,We(n)?(s=!0,go(e)):s=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,wu(e),i.updater=Do,e.stateNode=i,i._reactInternals=e,jl(e,n,t,r),e=Ul(null,e,n,!0,s,r)):(e.tag=0,se&&s&&hu(e),Ue(null,e,i,r),e=e.child),e;case 16:n=e.elementType;e:{switch(eo(t,e),t=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=sv(n),t=_t(n,t),i){case 0:e=$l(null,e,n,t,r);break e;case 1:e=Bd(null,e,n,t,r);break e;case 11:e=Ud(null,e,n,t,r);break e;case 14:e=zd(null,e,n,_t(n.type,t),r);break e}throw Error(E(306,n,""))}return e;case 0:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:_t(n,i),$l(t,e,n,i,r);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:_t(n,i),Bd(t,e,n,i,r);case 3:e:{if(Af(e),t===null)throw Error(E(387));n=e.pendingProps,s=e.memoizedState,i=s.element,tf(t,e),_o(e,n,null,r);var o=e.memoizedState;if(n=o.element,s.isDehydrated)if(s={element:n,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},e.updateQueue.baseState=s,e.memoizedState=s,e.flags&256){i=Nn(Error(E(423)),e),e=Md(t,e,n,r,i);break e}else if(n!==i){i=Nn(Error(E(424)),e),e=Md(t,e,n,r,i);break e}else for(Je=wr(e.stateNode.containerInfo.firstChild),Xe=e,se=!0,kt=null,r=Zh(e,null,n,r),e.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(On(),n===i){e=er(t,e,r);break e}Ue(t,e,n,r)}e=e.child}return e;case 5:return rf(e),t===null&&Il(e),n=e.type,i=e.pendingProps,s=t!==null?t.memoizedProps:null,o=i.children,Rl(n,i)?o=null:s!==null&&Rl(n,s)&&(e.flags|=32),Cf(t,e),Ue(t,e,o,r),e.child;case 6:return t===null&&Il(e),null;case 13:return Of(t,e,r);case 4:return _u(e,e.stateNode.containerInfo),n=e.pendingProps,t===null?e.child=Pn(e,null,n,r):Ue(t,e,n,r),e.child;case 11:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:_t(n,i),Ud(t,e,n,i,r);case 7:return Ue(t,e,e.pendingProps,r),e.child;case 8:return Ue(t,e,e.pendingProps.children,r),e.child;case 12:return Ue(t,e,e.pendingProps.children,r),e.child;case 10:e:{if(n=e.type._context,i=e.pendingProps,s=e.memoizedProps,o=i.value,Z(vo,n._currentValue),n._currentValue=o,s!==null)if(Tt(s.value,o)){if(s.children===i.children&&!He.current){e=er(t,e,r);break e}}else for(s=e.child,s!==null&&(s.return=e);s!==null;){var a=s.dependencies;if(a!==null){o=s.child;for(var l=a.firstContext;l!==null;){if(l.context===n){if(s.tag===1){l=Xt(-1,r&-r),l.tag=2;var u=s.updateQueue;if(u!==null){u=u.shared;var c=u.pending;c===null?l.next=l:(l.next=c.next,c.next=l),u.pending=l}}s.lanes|=r,l=s.alternate,l!==null&&(l.lanes|=r),Nl(s.return,r,e),a.lanes|=r;break}l=l.next}}else if(s.tag===10)o=s.type===e.type?null:s.child;else if(s.tag===18){if(o=s.return,o===null)throw Error(E(341));o.lanes|=r,a=o.alternate,a!==null&&(a.lanes|=r),Nl(o,r,e),o=s.sibling}else o=s.child;if(o!==null)o.return=s;else for(o=s;o!==null;){if(o===e){o=null;break}if(s=o.sibling,s!==null){s.return=o.return,o=s;break}o=o.return}s=o}Ue(t,e,i.children,r),e=e.child}return e;case 9:return i=e.type,n=e.pendingProps.children,xn(e,r),i=ut(i),n=n(i),e.flags|=1,Ue(t,e,n,r),e.child;case 14:return n=e.type,i=_t(n,e.pendingProps),i=_t(n.type,i),zd(t,e,n,i,r);case 15:return xf(t,e,e.type,e.pendingProps,r);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:_t(n,i),eo(t,e),e.tag=1,We(n)?(t=!0,go(e)):t=!1,xn(e,r),bf(e,n,i),jl(e,n,i,r),Ul(null,e,n,!0,t,r);case 19:return Pf(t,e,r);case 22:return Rf(t,e,r)}throw Error(E(156,e.tag))};function Kf(t,e){return wh(t,e)}function iv(t,e,r,n){this.tag=t,this.key=r,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=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function at(t,e,r,n){return new iv(t,e,r,n)}function ju(t){return t=t.prototype,!(!t||!t.isReactComponent)}function sv(t){if(typeof t=="function")return ju(t)?1:0;if(t!=null){if(t=t.$typeof,t===eu)return 11;if(t===tu)return 14}return 2}function br(t,e){var r=t.alternate;return r===null?(r=at(t.tag,e,t.key,t.mode),r.elementType=t.elementType,r.type=t.type,r.stateNode=t.stateNode,r.alternate=t,t.alternate=r):(r.pendingProps=e,r.type=t.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=t.flags&14680064,r.childLanes=t.childLanes,r.lanes=t.lanes,r.child=t.child,r.memoizedProps=t.memoizedProps,r.memoizedState=t.memoizedState,r.updateQueue=t.updateQueue,e=t.dependencies,r.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},r.sibling=t.sibling,r.index=t.index,r.ref=t.ref,r}function no(t,e,r,n,i,s){var o=2;if(n=t,typeof t=="function")ju(t)&&(o=1);else if(typeof t=="string")o=5;else e:switch(t){case dn:return Fr(r.children,i,s,e);case Zl:o=8,i|=8;break;case sl:return t=at(12,r,e,i|2),t.elementType=sl,t.lanes=s,t;case ol:return t=at(13,r,e,i),t.elementType=ol,t.lanes=s,t;case al:return t=at(19,r,e,i),t.elementType=al,t.lanes=s,t;case rh:return zo(r,i,s,e);default:if(typeof t=="object"&&t!==null)switch(t.$typeof){case eh:o=10;break e;case th:o=9;break e;case eu:o=11;break e;case tu:o=14;break e;case cr:o=16,n=null;break e}throw Error(E(130,t==null?t:typeof t,""))}return e=at(o,r,e,i),e.elementType=t,e.type=n,e.lanes=s,e}function Fr(t,e,r,n){return t=at(7,t,n,e),t.lanes=r,t}function zo(t,e,r,n){return t=at(22,t,n,e),t.elementType=rh,t.lanes=r,t.stateNode={isHidden:!1},t}function rl(t,e,r){return t=at(6,t,null,e),t.lanes=r,t}function nl(t,e,r){return e=at(4,t.children!==null?t.children:[],t.key,e),e.lanes=r,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function ov(t,e,r,n,i){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=Ba(0),this.expirationTimes=Ba(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ba(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Du(t,e,r,n,i,s,o,a,l){return t=new ov(t,e,r,a,l),e===1?(e=1,s===!0&&(e|=8)):e=0,s=at(3,null,null,e),t.current=s,s.stateNode=t,s.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},wu(s),t}function av(t,e,r){var n=3{"use strict";function Yf(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Yf)}catch(t){console.error(t)}}Yf(),Zf.exports=Qf()});var rp=qt(Bu=>{"use strict";var tp=ep();Bu.createRoot=tp.createRoot,Bu.hydrateRoot=tp.hydrateRoot;var Nw});var xg=qt(_a=>{"use strict";var ww=$e(),_w=Symbol.for("react.element"),Sw=Symbol.for("react.fragment"),kw=Object.prototype.hasOwnProperty,bw=ww.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Ew={key:!0,ref:!0,__self:!0,__source:!0};function Tg(t,e,r){var n,i={},s=null,o=null;r!==void 0&&(s=""+r),e.key!==void 0&&(s=""+e.key),e.ref!==void 0&&(o=e.ref);for(n in e)kw.call(e,n)&&!Ew.hasOwnProperty(n)&&(i[n]=e[n]);if(t&&t.defaultProps)for(n in e=t.defaultProps,e)i[n]===void 0&&(i[n]=e[n]);return{$typeof:_w,type:t,key:s,ref:o,props:i,_owner:bw.current}}_a.Fragment=Sw;_a.jsx=Tg;_a.jsxs=Tg});var ie=qt((Nk,Rg)=>{"use strict";Rg.exports=xg()});var Lr=q($e()),Fg=q(rp());var J="#C9A84C",rr="#f5ecd7",z="#a88a2e",Wo="#faf7f0",me="#333",O="#888",R="#fff",C="#e8e0cc",dt="#e74c3c",Mu="#27ae60";var Ar={\u4E88\u7D04\u6E08:"#3498db",\u6765\u5E97:"#2ecc71",\u65BD\u8853\u4E2D:"#f39c12",\u30B7\u30E3\u30F3\u30D7\u30FC\u4E2D:"#1abc9c",\u30AB\u30C3\u30C8\u4E2D:"#e67e22",\u30C9\u30E9\u30A4\u4E2D:"#9b59b6",\u4ED5\u4E0A\u3052\u4E2D:"#e91e63",\u5B8C\u4E86:"#27ae60",\u304A\u8FCE\u3048\u5F85\u3061:"#ff9800",\u5F15\u6E21\u6E08:"#95a5a6",\u30AD\u30E3\u30F3\u30BB\u30EB:"#e74c3c",\u30CE\u30FC\u30B7\u30E7\u30FC:"#7f8c8d"},np=["\u4E88\u7D04\u6E08","\u6765\u5E97","\u65BD\u8853\u4E2D","\u30B7\u30E3\u30F3\u30D7\u30FC\u4E2D","\u30AB\u30C3\u30C8\u4E2D","\u30C9\u30E9\u30A4\u4E2D","\u4ED5\u4E0A\u3052\u4E2D","\u5B8C\u4E86","\u304A\u8FCE\u3048\u5F85\u3061","\u5F15\u6E21\u6E08","\u30AD\u30E3\u30F3\u30BB\u30EB","\u30CE\u30FC\u30B7\u30E7\u30FC"];var ip=["\u73FE\u91D1","\u30AF\u30EC\u30B8\u30C3\u30C8","\u96FB\u5B50\u30DE\u30CD\u30FC","QR\u6C7A\u6E08","\u58F2\u639B","\u305D\u306E\u4ED6"],sp={\u73FE\u91D1:"\u{1F4B4}",\u30AF\u30EC\u30B8\u30C3\u30C8:"\u{1F4B3}",\u96FB\u5B50\u30DE\u30CD\u30FC:"\u{1F4F1}",QR\u6C7A\u6E08:"\u{1F4F7}",\u58F2\u639B:"\u{1F4DD}",\u305D\u306E\u4ED6:"\u{1F516}"};var op=["\u30C8\u30EA\u30DF\u30F3\u30B0","\u30B7\u30E3\u30F3\u30D7\u30FC","\u30B9\u30D1","\u30AA\u30D7\u30B7\u30E7\u30F3","\u7269\u8CA9","\u305D\u306E\u4ED6"],qi={\u30C8\u30EA\u30DF\u30F3\u30B0:"\u2702\uFE0F",\u30B7\u30E3\u30F3\u30D7\u30FC:"\u{1FAE7}",\u30B9\u30D1:"\u{1F9D6}",\u30AA\u30D7\u30B7\u30E7\u30F3:"\u{1F380}",\u7269\u8CA9:"\u{1F6D2}",\u305D\u306E\u4ED6:"\u{1F4E6}"},ap=["\u30C8\u30A4\u30D7\u30FC\u30C9\u30EB","\u30C1\u30EF\u30EF","\u30DE\u30EB\u30C1\u30FC\u30BA","\u30DD\u30E1\u30E9\u30CB\u30A2\u30F3","\u30E8\u30FC\u30AF\u30B7\u30E3\u30FC\u30C6\u30EA\u30A2","\u30DF\u30CB\u30C1\u30E5\u30A2\u30C0\u30C3\u30AF\u30B9","\u30B7\u30FC\u30BA\u30FC","\u30D5\u30EC\u30F3\u30C1\u30D6\u30EB\u30C9\u30C3\u30B0","\u67F4\u72AC","\u30DF\u30CB\u30C1\u30E5\u30A2\u30B7\u30E5\u30CA\u30A6\u30B6\u30FC","\u30D1\u30D4\u30E8\u30F3","\u30B3\u30FC\u30AE\u30FC","\u30B4\u30FC\u30EB\u30C7\u30F3\u30EC\u30C8\u30EA\u30D0\u30FC","\u30E9\u30D6\u30E9\u30C9\u30FC\u30EB","\u30D3\u30B7\u30E7\u30F3\u30D5\u30EA\u30FC\u30BC","\u30AD\u30E3\u30D0\u30EA\u30A2","\u30B8\u30E3\u30C3\u30AF\u30E9\u30C3\u30BB\u30EB","\u30DC\u30FC\u30C0\u30FC\u30B3\u30EA\u30FC","\u30D1\u30B0","\u30DA\u30AD\u30CB\u30FC\u30BA","MIX","\u305D\u306E\u4ED6"],lp=["\u30AA\u30B9","\u30E1\u30B9","\u4E0D\u660E"],up=["owner","manager","staff"],Vi={owner:"\u30AA\u30FC\u30CA\u30FC",manager:"\u30DE\u30CD\u30FC\u30B8\u30E3\u30FC",staff:"\u30B9\u30BF\u30C3\u30D5"},cp=[{key:"dashboard",label:"\u30DB\u30FC\u30E0",icon:"\u{1F3E0}"},{key:"appointments",label:"\u4E88\u7D04",icon:"\u{1F4C5}"},{key:"status-board",label:"\u30B9\u30C6\u30FC\u30BF\u30B9",icon:"\u{1F4CB}"},{key:"pos",label:"\u30EC\u30B8",icon:"\u{1F4B0}"},{key:"customers",label:"\u9867\u5BA2",icon:"\u{1F464}"},{key:"pets",label:"\u30DA\u30C3\u30C8",icon:"\u{1F415}"},{key:"records",label:"\u30AB\u30EB\u30C6",icon:"\u{1F4F8}"},{key:"services",label:"\u30E1\u30CB\u30E5\u30FC",icon:"\u2702\uFE0F"},{key:"reports",label:"\u65E5\u5831",icon:"\u{1F4CA}"},{key:"staff",label:"\u30B9\u30BF\u30C3\u30D5",icon:"\u{1F465}"}],I="44px",ht="95vw",ft="500px",Ne=2500,Fu=6;var Ft=q($e());function Xr(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);it?(...e)=>t(...e):(...e)=>fetch(...e);var $n=class extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}toJSON(){return{name:this.name,message:this.message,context:this.context}}},Ki=class extends $n{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},Un=class extends $n{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},zn=class extends $n{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Gi;(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"})(Gi||(Gi={}));var Ji=class{constructor(e,{headers:r={},customFetch:n,region:i=Gi.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=hp(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return dp(this,arguments,void 0,function*(r,n={}){var i;let s,o;try{let{headers:a,method:l,body:u,signal:c,timeout:d}=n,p={},{region:m}=n;m||(m=this.region);let y=new URL(`${this.url}/${r}`);m&&m!=="any"&&(p["x-region"]=m,y.searchParams.set("forceFunctionRegion",m));let v,b=!!a&&Object.keys(a).some(w=>w.toLowerCase()==="content-type");u&&!b?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(p["Content-Type"]="application/octet-stream",v=u):typeof u=="string"?(p["Content-Type"]="text/plain",v=u):typeof FormData<"u"&&u instanceof FormData?v=u:(p["Content-Type"]="application/json",v=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?v=JSON.stringify(u):v=u;let f=c;d&&(o=new AbortController,s=setTimeout(()=>o.abort(),d),c?(f=o.signal,c.addEventListener("abort",()=>o.abort())):f=o.signal);let h=yield this.fetch(y.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),a),body:v,signal:f}).catch(w=>{throw new Ki(w)}),g=h.headers.get("x-relay-error");if(g&&g==="true")throw new Un(h);if(!h.ok)throw new zn(h);let _=((i=h.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),k;return _==="application/json"?k=yield h.json():_==="application/octet-stream"||_==="application/pdf"?k=yield h.blob():_==="text/event-stream"?k=h:_==="multipart/form-data"?k=yield h.formData():k=yield h.text(),{data:k,error:null,response:h}}catch(a){return{data:null,error:a,response:a instanceof zn||a instanceof Un?a.context:void 0}}finally{s&&clearTimeout(s)}})}};var fp=t=>Math.min(1e3*2**t,3e4),hv=[520,503],yp=["GET","HEAD","OPTIONS"],Hu=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function pp(t,e){return new Promise(r=>{if(e?.aborted){r();return}let n=setTimeout(()=>{e?.removeEventListener("abort",i),r()},t);function i(){clearTimeout(n),r()}e?.addEventListener("abort",i)})}function fv(t,e,r,n){return!(!n||r>=3||!yp.includes(t)||!hv.includes(e))}var pv=class{constructor(t){var e,r,n,i,s;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(n=t.shouldStripNulls)!==null&&n!==void 0?n:!1,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,this.retryEnabled=(s=t.retry)!==null&&s!==void 0?s:!0,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var r=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){let o=this.headers.get("Accept");o==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!o||o==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let n=this.fetch,s=(async()=>{let o=0;for(;;){let u={};r.headers.forEach((d,p)=>{u[p]=d}),o>0&&(u["X-Retry-Count"]=String(o));let c;try{c=await n(r.url.toString(),{method:r.method,headers:u,body:JSON.stringify(r.body,(d,p)=>typeof p=="bigint"?p.toString():p),signal:r.signal})}catch(d){if(d?.name==="AbortError"||d?.code==="ABORT_ERR"||!yp.includes(r.method))throw d;if(r.retryEnabled&&o<3){let p=fp(o);o++,await pp(p,r.signal);continue}throw d}if(fv(r.method,c.status,o,r.retryEnabled)){var a,l;let d=(a=(l=c.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&a!==void 0?a:null,p=d!==null?Math.max(0,parseInt(d,10)||0)*1e3:fp(o);await c.text(),o++,await pp(p,r.signal);continue}return await r.processResponse(c)}})();return this.shouldThrowOnError||(s=s.catch(o=>{var a;let l="",u="",c="",d=o?.cause;if(d){var p,m,y,v;let h=(p=d?.message)!==null&&p!==void 0?p:"",g=(m=d?.code)!==null&&m!==void 0?m:"";l=`${(y=o?.name)!==null&&y!==void 0?y:"FetchError"}: ${o?.message}`,l+=`
Caused by: ${(v=d?.name)!==null&&v!==void 0?v:"Error"}: ${h}`,g&&(l+=` (${g})`),d?.stack&&(l+=`
${d.stack}`)}else{var b;l=(b=o?.stack)!==null&&b!==void 0?b:""}let f=this.url.toString().length;return o?.name==="AbortError"||o?.code==="ABORT_ERR"?(c="",u="Request was aborted (timeout or manual cancellation)",f>this.urlLengthLimit&&(u+=`. Note: Your request URL is ${f} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(d?.name==="HeadersOverflowError"||d?.code==="UND_ERR_HEADERS_OVERFLOW")&&(c="",u="HTTP headers exceeded server limits (typically 16KB)",f>this.urlLengthLimit&&(u+=`. Your request URL is ${f} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${(a=o?.name)!==null&&a!==void 0?a:"FetchError"}: ${o?.message}`,details:l,hint:u,code:c},data:null,count:null,status:0,statusText:""}})),s.then(t,e)}async processResponse(t){var e=this;let r=null,n=null,i=null,s=t.status,o=t.statusText;if(t.ok){var a,l;if(e.method!=="HEAD"){var u;let p=await t.text();if(p!=="")if(e.headers.get("Accept")==="text/csv")n=p;else if(e.headers.get("Accept")&&(!((u=e.headers.get("Accept"))===null||u===void 0)&&u.includes("application/vnd.pgrst.plan+text")))n=p;else try{n=JSON.parse(p)}catch{if(r={message:p},n=null,e.shouldThrowOnError)throw new Hu({message:p,details:"",hint:"",code:""})}}let c=(a=e.headers.get("Prefer"))===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),d=(l=t.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");c&&d&&d.length>1&&(i=parseInt(d[1])),e.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(r={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,i=null,s=406,o="Not Acceptable"):n.length===1?n=n[0]:n=null)}else{let c=await t.text();try{r=JSON.parse(c),Array.isArray(r)&&t.status===404&&(n=[],r=null,s=200,o="OK")}catch{t.status===404&&c===""?(s=204,o="No Content"):r={message:c}}if(r&&e.shouldThrowOnError)throw new Hu(r)}return{success:r===null,error:r,data:n,count:i,status:s,statusText:o}}returns(){return this}overrideTypes(){return this}},gv=class extends pv{throwOnError(){return super.throwOnError()}select(t){let e=!1,r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:n,referencedTable:i=n}={}){let s=i?`${i}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){let i=typeof n>"u"?"offset":`${n}.offset`,s=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(s,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:n=!1,wal:i=!1,format:s="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},gp=new RegExp("[,()]"),Bn=class extends gv{throwOnError(){return super.throwOnError()}eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&gp.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&gp.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let i="";n==="plain"?i="pl":n==="phrase"?i="ph":n==="websearch"&&(i="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},mv=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:i=8e3,retry:s}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=i,this.retry=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:n}=e??{},i=r?"HEAD":"GET",s=!1,o=(t??"*").split("").map(u=>/\s/.test(u)&&!s?"":(u==='"'&&(s=!s),u)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),n&&l.append("Prefer",`count=${n}`),new Bn({method:i,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=!0}={}){var n;let i="POST",{url:s,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(a.length>0){let l=[...new Set(a)].map(u=>`"${u}"`);s.searchParams.set("columns",l.join(","))}}return new Bn({method:i,url:s,headers:o,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:n,defaultToNull:i=!0}={}){var s;let o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),n&&l.append("Prefer",`count=${n}`),i||l.append("Prefer","missing=default"),Array.isArray(t)){let u=t.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(u.length>0){let c=[...new Set(u)].map(d=>`"${d}"`);a.searchParams.set("columns",c.join(","))}}return new Bn({method:o,url:a,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;let n="PATCH",{url:i,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new Bn({method:n,url:i,headers:s,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;let r="DELETE",{url:n,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new Bn({method:r,url:n,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function Xi(t){"@babel/helpers - typeof";return Xi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Xi(t)}function yv(t,e){if(Xi(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(Xi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function vv(t){var e=yv(t,"string");return Xi(e)=="symbol"?e:e+""}function wv(t,e,r){return(e=vv(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function mp(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function qo(t){for(var e=1;e0?this.fetch=(u,c)=>{let d=new AbortController,p=setTimeout(()=>d.abort(),s),m=c?.signal;if(m){if(m.aborted)return clearTimeout(p),l(u,c);let y=()=>{clearTimeout(p),d.abort()};return m.addEventListener("abort",y,{once:!0}),l(u,qo(qo({},c),{},{signal:d.signal})).finally(()=>{clearTimeout(p),m.removeEventListener("abort",y)})}return l(u,qo(qo({},c),{},{signal:d.signal})).finally(()=>clearTimeout(p))}:this.fetch=l,this.retry=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new mv(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new wp(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,r={},{head:n=!1,get:i=!1,count:s}={}){var o;let a,l=new URL(`${this.url}/rpc/${e}`),u,c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),d=n&&Object.values(r).some(c);d?(a="POST",u=r):n||i?(a=n?"HEAD":"GET",Object.entries(r).filter(([m,y])=>y!==void 0).map(([m,y])=>[m,Array.isArray(y)?`{${y.join(",")}}`:`${y}`]).forEach(([m,y])=>{l.searchParams.append(m,y)})):(a="POST",u=r);let p=new Headers(this.headers);return d?p.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&p.set("Prefer",`count=${s}`),new Bn({method:a,url:l,headers:p,schema:this.schemaName,body:u,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};var Wu=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};let r=globalThis;if(typeof globalThis<"u"&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};let n=typeof global<"u"?global:void 0;if(n&&typeof n.WebSocket<"u")return{type:"native",wsConstructor:n.WebSocket};if(typeof globalThis<"u"&&typeof r.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"&&r.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."};let i=globalThis.process;if(i){let s=i.versions;if(s&&s.node)return{type:"unsupported",error:"Node.js detected but native WebSocket not found.",workaround:"Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{return this.detectEnvironment().type==="native"}catch{return!1}}},qu=Wu;var _p="2.110.1";var Sp=`realtime-js/${_p}`,kp="1.0.0",Vu="2.0.0",bp=Vu;var Ep=1e4;var Tp=100;var jt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Vo={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var Qi={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var Yi=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var i,s;let o=e.topic,a=(i=e.ref)!==null&&i!==void 0?i:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",u=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(c).length===0?"":JSON.stringify(c);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);let p=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+u.length+d.length,m=new ArrayBuffer(this.HEADER_LENGTH+p),y=new DataView(m),v=0;y.setUint8(v++,this.KINDS.userBroadcastPush),y.setUint8(v++,l.length),y.setUint8(v++,a.length),y.setUint8(v++,o.length),y.setUint8(v++,u.length),y.setUint8(v++,d.length),y.setUint8(v++,r),Array.from(l,f=>y.setUint8(v++,f.charCodeAt(0))),Array.from(a,f=>y.setUint8(v++,f.charCodeAt(0))),Array.from(o,f=>y.setUint8(v++,f.charCodeAt(0))),Array.from(u,f=>y.setUint8(v++,f.charCodeAt(0))),Array.from(d,f=>y.setUint8(v++,f.charCodeAt(0)));var b=new Uint8Array(m.byteLength+n.byteLength);return b.set(new Uint8Array(m),0),b.set(new Uint8Array(n),m.byteLength),b.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){let n=JSON.parse(e),[i,s,o,a,l]=n;return r({join_ref:i,ref:s,topic:o,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),n=r.getUint8(0),i=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,i)}}_decodeUserBroadcast(e,r,n){let i=r.getUint8(1),s=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,u=n.decode(e.slice(l,l+i));l=l+i;let c=n.decode(e.slice(l,l+s));l=l+s;let d=n.decode(e.slice(l,l+o));l=l+o;let p=e.slice(l,e.byteLength),m=a===this.JSON_ENCODING?JSON.parse(n.decode(p)):p,y={type:this.BROADCAST_EVENT,event:c,payload:m};return o>0&&(y.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:y}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}};var ee;(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"})(ee||(ee={}));var Gu=(t,e,r={})=>{var n;let i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((s,o)=>(s[o]=_v(o,t,e,i),s),{}):{}},_v=(t,e,r,n)=>{let i=e.find(a=>a.name===t),s=i?.type,o=r[t];return s&&!n.includes(s)?xp(s,o):Ku(o)},xp=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Ev(e,r)}switch(t){case ee.bool:return Sv(e);case ee.float4:case ee.float8:case ee.int2:case ee.int4:case ee.int8:case ee.numeric:case ee.oid:return kv(e);case ee.json:case ee.jsonb:return bv(e);case ee.timestamp:return Tv(e);case ee.abstime:case ee.date:case ee.daterange:case ee.int4range:case ee.int8range:case ee.money:case ee.reltime:case ee.text:case ee.time:case ee.timestamptz:case ee.timetz:case ee.tsrange:case ee.tstzrange:return Ku(e);default:return Ku(e)}},Ku=t=>t,Sv=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},kv=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},bv=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Ev=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let s,o=t.slice(1,r);try{s=JSON.parse("["+o+"]")}catch{s=o?o.split(","):[]}return s.map(a=>xp(e,a))}return t},Tv=t=>typeof t=="string"?t.replace(" ","T"):t,Ko=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var es=t=>typeof t=="function"?t:function(){return t},Rv=typeof self<"u"?self:null,Fn=typeof window<"u"?window:null,Dt=Rv||Fn||globalThis,Cv="2.0.0",Av=1e4,Ov=1e3,$t={connecting:0,open:1,closing:2,closed:3},Ve={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},nr={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Ju={longpoll:"longpoll",websocket:"websocket"},Pv={complete:4},Xu="base64url.bearer.phx.",Go=class{constructor(t,e,r,n){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},Rp=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Iv=class{constructor(t,e,r){this.state=Ve.closed,this.topic=t,this.params=es(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Go(this,nr.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Rp(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Ve.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",n=>{this.state=Ve.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Ve.closed,this.socket.remove(this)}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=Ve.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Go(this,nr.leave,es({}),this.timeout).send(),this.state=Ve.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(nr.reply,(n,i)=>{this.trigger(this.replyEventName(i),n)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Ve.closed,this.bindings=[]}onClose(t){this.on(nr.close,t)}onError(t){return this.on(nr.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new Go(this,t,function(){return e},r);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Ve.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(nr.close,"leave")},r=new Go(this,nr.leave,es({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,n){return this.topic!==t?!1:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:n}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Ve.joining,this.joinPush.resend(t))}trigger(t,e,r,n){let i=this.onMessage(t,e,r,n);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter(o=>o.event===t&&this.filterBindings(o,e,r));for(let o=0;ol.abort(),i);a.signal=l.signal}return Dt.fetch(e,a).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>o&&o(u)).catch(u=>{u.name==="AbortError"&&s?s():o&&o(null)}),l}static xdomainRequest(t,e,r,n,i,s,o){return t.timeout=i,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);o&&o(a)},s&&(t.ontimeout=s),t.onprogress=()=>{},t.send(n),t}static xhrRequest(t,e,r,n,i,s,o,a){t.open(e,r,!0),t.timeout=s;for(let[l,u]of Object.entries(n))t.setRequestHeader(l,u);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===Pv.complete&&a){let l=this.parseJSON(t.responseText);a(l)}},o&&(t.ontimeout=o),t.send(i),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let i=e?`${e}[${n}]`:n,s=t[n];typeof s=="object"?r.push(this.serialize(s,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(s))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},Nv=t=>{let e="",r=new Uint8Array(t),n=r.byteLength;for(let i=0;ithis.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Ju.websocket),"$1/"+Ju.longpoll)}endpointURL(){return Xo.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=$t.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===$t.open||this.readyState===$t.connecting}poll(){let t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:n,messages:i}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=n}else r=0;switch(r){case 200:i.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=$t.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=Nv(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let i of this.reqs)i.abort();this.readyState=$t.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n)}ajax(t,e,r,n,i){let s,o=()=>{this.reqs.delete(s),n()};s=Xo.request(t,this.endpointURL(),e,r,this.timeout,o,a=>{this.reqs.delete(s),this.isActive()&&i(a)}),this.reqs.add(s)}},Cp=class Zi{constructor(e,r={}){let n=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(n.state,i=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Zi.syncState(this.state,i,s,o),this.pendingDiffs.forEach(l=>{this.state=Zi.syncDiff(this.state,l,s,o)}),this.pendingDiffs=[],a()}),this.channel.on(n.diff,i=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=Zi.syncDiff(this.state,i,s,o),a())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return Zi.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,n,i){let s=this.clone(e),o={},a={};return this.map(s,(l,u)=>{r[l]||(a[l]=u)}),this.map(r,(l,u)=>{let c=s[l];if(c){let d=u.metas.map(v=>v.phx_ref),p=c.metas.map(v=>v.phx_ref),m=u.metas.filter(v=>p.indexOf(v.phx_ref)<0),y=c.metas.filter(v=>d.indexOf(v.phx_ref)<0);m.length>0&&(o[l]=u,o[l].metas=m),y.length>0&&(a[l]=this.clone(c),a[l].metas=y)}else o[l]=u}),this.syncDiff(s,{joins:o,leaves:a},n,i)}static syncDiff(e,r,n,i){let{joins:s,leaves:o}=this.clone(r);return n||(n=function(){}),i||(i=function(){}),this.map(s,(a,l)=>{let u=e[a];if(e[a]=this.clone(l),u){let c=e[a].metas.map(p=>p.phx_ref),d=u.metas.filter(p=>c.indexOf(p.phx_ref)<0);e[a].metas.unshift(...d)}n(a,u,l)}),this.map(o,(a,l)=>{let u=e[a];if(!u)return;let c=l.metas.map(d=>d.phx_ref);u.metas=u.metas.filter(d=>c.indexOf(d.phx_ref)<0),i(a,u,l),u.metas.length===0&&delete e[a]}),e}static list(e,r){return r||(r=function(n,i){return i}),this.map(e,(n,i)=>r(n,i))}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static clone(e){return JSON.parse(JSON.stringify(e))}},Jo={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,n,i,s,o]=JSON.parse(t);return e({join_ref:r,ref:n,topic:i,event:s,payload:o})}},binaryEncode(t){let{join_ref:e,ref:r,event:n,topic:i,payload:s}=t,o=this.META_LENGTH+e.length+r.length+i.length+n.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),l=new DataView(a),u=0;l.setUint8(u++,this.KINDS.push),l.setUint8(u++,e.length),l.setUint8(u++,r.length),l.setUint8(u++,i.length),l.setUint8(u++,n.length),Array.from(e,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(r,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(i,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(n,d=>l.setUint8(u++,d.charCodeAt(0)));var c=new Uint8Array(a.byteLength+s.byteLength);return c.set(new Uint8Array(a),0),c.set(new Uint8Array(s),a.byteLength),c.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,n);case this.KINDS.reply:return this.decodeReply(t,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,n)}},decodePush(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(o,o+n));o=o+n;let l=r.decode(t.slice(o,o+i));o=o+i;let u=r.decode(t.slice(o,o+s));o=o+s;let c=t.slice(o,t.byteLength);return{join_ref:a,ref:null,topic:l,event:u,payload:c}},decodeReply(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(a,a+n));a=a+n;let u=r.decode(t.slice(a,a+i));a=a+i;let c=r.decode(t.slice(a,a+s));a=a+s;let d=r.decode(t.slice(a,a+o));a=a+o;let p=t.slice(a,t.byteLength),m={status:d,response:p};return{join_ref:l,ref:u,topic:c,event:nr.reply,payload:m}},decodeBroadcast(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=this.HEADER_LENGTH+2,o=r.decode(t.slice(s,s+n));s=s+n;let a=r.decode(t.slice(s,s+i));s=s+i;let l=t.slice(s,t.byteLength);return{join_ref:null,ref:null,topic:o,event:a,payload:l}}},Ap=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Av,this.transport=e.transport||Dt.WebSocket||Mn,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=Dt&&Dt.sessionStorage}catch{}this.sessionStore=e.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=Jo.encode.bind(Jo),this.defaultDecoder=Jo.decode.bind(Jo),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Mn?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let n=null;Fn&&Fn.addEventListener&&(Fn.addEventListener("pagehide",i=>{this.conn&&(this.disconnect(),n=this.connectClock)}),Fn.addEventListener("pageshow",i=>{n===this.connectClock&&(n=null,this.connect())}),Fn.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=i=>e.rejoinAfterMs?e.rejoinAfterMs(i):[1e3,2e3,5e3][i-1]||1e4,this.reconnectAfterMs=i=>e.reconnectAfterMs?e.reconnectAfterMs(i):[10,50,100,150,200,250,500,1e3,2e3][i-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(i,s,o)=>{console.log(`${i}: ${s}`,o)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=es(e.params||{}),this.endPoint=`${t}/${Ju.websocket}`,this.vsn=e.vsn||Cv,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Rp(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return Mn}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Xo.appendParams(Xo.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=es(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Mn?this.connectWithFallback(Mn,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(i=>{i.ref===e&&(this.off([n]),t(Date.now()-r))});return!0}transportName(t){switch(t){case Mn:return"LongPoll";default:return t.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${Xu}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,n=!0,i,s,o=this.transportName(t),a=l=>{this.log("transport",`falling back to ${o}...`,l),this.off([i,s]),n=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),s=this.onError(l=>{this.log("transport","error",l),n&&!r&&(clearTimeout(this.fallbackTimer),a(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!n){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Ov,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();let n=this.conn;this.waitForBufferDone(n,()=>{e?n.close(e,r||""):n.close(),this.waitForSocketClosed(n,()=>{this.conn===n&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===$t.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(t),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError(t)}triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(nr.error,t)})}connectionState(){switch(this.conn&&this.conn.readyState){case $t.connecting:return"connecting";case $t.open:return"open";case $t.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new Iv(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:n,ref:i,join_ref:s}=t;this.log("push",`${e} ${r} (${s}, ${i})`,n)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:n,payload:i,ref:s,join_ref:o}=e;if(s&&s===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(i.status==="ok"?"ok":"error",a)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${i.status||""} ${r} ${n} ${s&&"("+s+")"||""}`.trim(),i);for(let a=0;a{try{n(...e)}catch(i){this.log("error",`error in ${t} callback`,i)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};var ts=class t{constructor(e,r){let n=jv(r);this.presence=new Cp(e.getChannel(),n),this.presence.onJoin((i,s,o)=>{let a=t.onJoinPayload(i,s,o);e.getChannel().trigger("presence",a)}),this.presence.onLeave((i,s,o)=>{let a=t.onLeavePayload(i,s,o);e.getChannel().trigger("presence",a)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=Lv(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{let i=e[n];return r[n]=Qo(i),r},{})}static onJoinPayload(e,r,n){let i=Op(r),s=Qo(n);return{event:"join",key:e,currentPresences:i,newPresences:s}}static onLeavePayload(e,r,n){let i=Op(r),s=Qo(n);return{event:"leave",key:e,currentPresences:i,leftPresences:s}}};function Qo(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Lv(t){return JSON.parse(JSON.stringify(t))}function jv(t){return t?.events&&{events:t.events}}function Op(t){return t?.metas?Qo(t):[]}var Qu;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Qu||(Qu={}));var Hn=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new ts(this.channel.channelAdapter,r)}};function Pp(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){let e=t;if(typeof e.code=="number"){let r=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${r}`,{cause:t})}return new Error("channel error: transport failure",{cause:t})}return new Error("channel error: connection lost")}var rs=class{constructor(e,r,n){let i=Dv(n);this.channel=e.getSocket().channel(r,i),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,n){let i;try{i=this.channel.push(e,r,n)}catch{throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>Tp){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload())}return i}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===jt.joined}isJoined(){return this.state===jt.joined}isJoining(){return this.state===jt.joining}isClosed(){return this.state===jt.closed}isLeaving(){return this.state===jt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function Dv(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var $v=/[,()"\\]/,Uv=t=>$v.test(t)||t!==t.trim(),zv=t=>`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,Ip=t=>{let e=t===null?"null":String(t);return Uv(e)?zv(e):e},Bv=t=>t===null?"null":String(t),Mv=(t,e)=>{if(t==="in"){let r=Array.isArray(e)?e:[e];if(r.length===0)throw new Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(r)).map(i=>Ip(i)).join(",")})`}return t==="is"?`is.${Bv(e)}`:`${t}.${Ip(e)}`},Wn=class{constructor(){this.filters=[]}add(e,r,n,i=!1){let s=i?"not.":"";return this.filters.push(`${e}=${s}${Mv(r,n)}`),this}eq(e,r){return this.add(e,"eq",r)}neq(e,r){return this.add(e,"neq",r)}gt(e,r){return this.add(e,"gt",r)}gte(e,r){return this.add(e,"gte",r)}lt(e,r){return this.add(e,"lt",r)}lte(e,r){return this.add(e,"lte",r)}in(e,r){return this.add(e,"in",r)}like(e,r){return this.add(e,"like",r)}ilike(e,r){return this.add(e,"ilike",r)}match(e,r){return this.add(e,"match",r)}imatch(e,r){return this.add(e,"imatch",r)}is(e,r){return this.add(e,"is",r)}isDistinct(e,r){return this.add(e,"isdistinct",r)}not(e,r,n){return this.add(e,r,n,!0)}build(){return this.filters.join(",")}toString(){return this.build()}};var Yu;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Yu||(Yu={}));var Qr;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Qr||(Qr={}));var Ut;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Ut||(Ut={}));var qn=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},n){var i,s;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new rs(this.socket.socketAdapter,e,this.params),this.presence=new Hn(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Ko(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((s=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||s===void 0)&&s.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,r=this.timeout){var n,i,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:o,presence:a,private:l}}=this.params,u=(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(m=>m.filter))!==null&&i!==void 0?i:[],c=!!this.bindings[Qr.PRESENCE]&&this.bindings[Qr.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===!0,d={},p={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(m=>{e?.(Ut.CHANNEL_ERROR,Pp(m))}),this._onClose(()=>e?.(Ut.CLOSED)),this.updateJoinPayload(Object.assign({config:p},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e?.(Ut.SUBSCRIBED);return}this._updatePostgresBindings(m,e)}).receive("error",m=>{this.state=jt.errored;let y=Object.values(m).join(", ")||"error";e?.(Ut.CHANNEL_ERROR,new Error(y,{cause:m}))}).receive("timeout",()=>{e?.(Ut.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var n;let i=this.bindings.postgres_changes,s=(n=i?.length)!==null&&n!==void 0?n:0,o=[];for(let a=0;a{var o,a,l;let u=this.channelAdapter.push(e.type,e,r.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)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,n){let i=new AbortController,s=setTimeout(()=>i.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(s),o}_on(e,r,n){let i=e.toLocaleLowerCase(),s=r?.filter;(s instanceof Wn||typeof s=="object"&&s!==null&&typeof s.build=="function")&&(r=Object.assign(Object.assign({},r),{filter:s.build()}));let o=this.channelAdapter.on(e,n),a={type:i,filter:r,callback:n,ref:o};return this.bindings[i]?this.bindings[i].push(a):this.bindings[i]=[a],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,n)=>{var i,s,o,a,l,u,c;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,n))return!1;let p=(i=this.bindings[d])===null||i===void 0?void 0:i.find(m=>m.ref===e.ref);if(!p)return!0;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in p){let m=p.id,y=(s=p.filter)===null||s===void 0?void 0:s.event;return m&&((o=r.ids)===null||o===void 0?void 0:o.includes(m))&&(y==="*"||y?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let m=(u=(l=p?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((c=r?.event)===null||c===void 0?void 0:c.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===d})}_notThisChannelEvent(e,r){let{close:n,error:i,leave:s,join:o}=Vo;return r&&[n,i,s,o].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,n)=>{if(typeof r=="object"&&"ids"in r){let i=r.data,{schema:s,table:o,commit_timestamp:a,type:l,errors:u}=i;return Object.assign(Object.assign({},{schema:s,table:o,commit_timestamp:a,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(i))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(let r in e.bindings)for(let n of e.bindings[r])this._on(n.type,n.filter,n.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Gu(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Gu(e.columns,e.old_record)),r}};var ns=class{constructor(e,r){this.socket=new Ap(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,n,i=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),i),this.socket.disconnect(()=>{e(),s("ok")},r,n)})}push(e){this.socket.push(e)}log(e,r,n){this.socket.log(e,r,n)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Qi.connecting}isDisconnecting(){return this.socket.connectionState()==Qi.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var Np={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Hv=[1e3,2e3,5e3,1e4],Wv=1e4;function qv(){let t=new Map;return{get length(){return t.size},clear(){t.clear()},getItem(e){return t.has(e)?t.get(e):null},key(e){var r;return(r=Array.from(t.keys())[e])!==null&&r!==void 0?r:null},removeItem(e){t.delete(e)},setItem(e,r){t.set(e,String(r))}}}function Vv(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return qv()}var Kv=`
addEventListener("message", (e) => {
if (e.data.event === "start") {
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
}
});`,Vn=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var n;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new Yi,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=s=>s?(...o)=>s(...o):(...o)=>fetch(...o),!(!((n=r?.params)===null||n===void 0)&&n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let i=this._initializeOptions(r);this.socketAdapter=new ns(e,i),this.httpEndpoint=Ko(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let r=e.message;throw new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),r}async removeAllChannels(){let e=this.channels.map(async n=>{let i=await n.unsubscribe();return n.teardown(),i}),r=await Promise.all(e);return await this.disconnect(),r}log(e,r,n){this.socketAdapter.log(e,r,n)}connectionState(){return this.socketAdapter.connectionState()||Qi.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let n=`realtime:${e}`,i=this.getChannels().find(s=>s.topic===n);if(i)return i;{let s=new qn(`realtime:${e}`,r,this);return this._cancelPendingDisconnect(),this.channels.push(s),s}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e=null){let r,n=!1;if(e)r=e,n=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),r=this.accessTokenValue}else r=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(i=>{let s={access_token:r,version:Sp};r&&i.updateJoinPayload(s),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(Vo.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,n)=>{r!=="disconnected"&&(r=="sent"&&this._setAuthSafely(),e&&e(r,n))}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{let n=new Blob([Kv],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}_initializeOptions(e){var r,n,i,s,o,a,l,u,c,d,p,m;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(n=e?.accessToken)!==null&&n!==void 0?n:null;let y={};y.timeout=(i=e?.timeout)!==null&&i!==void 0?i:Ep,y.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Np.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(o=e?.disconnectOnEmptyChannelsAfterMs)!==null&&o!==void 0?o:2*((a=e?.heartbeatIntervalMs)!==null&&a!==void 0?a:Np.HEARTBEAT_INTERVAL),y.transport=(l=e?.transport)!==null&&l!==void 0?l:qu.getWebSocketConstructor(),y.params=e?.params,y.logger=e?.logger,y.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),y.sessionStorage=(u=e?.sessionStorage)!==null&&u!==void 0?u:Vv(),y.reconnectAfterMs=(c=e?.reconnectAfterMs)!==null&&c!==void 0?c:h=>Hv[h-1]||Wv;let v,b,f=(d=e?.vsn)!==null&&d!==void 0?d:bp;switch(f){case kp:v=(h,g)=>g(JSON.stringify(h)),b=(h,g)=>g(JSON.parse(h));break;case Vu:v=this.serializer.encode.bind(this.serializer),b=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${y.vsn}`)}if(y.vsn=f,y.encode=(p=e?.encode)!==null&&p!==void 0?p:v,y.decode=(m=e?.decode)!==null&&m!==void 0?m:b,y.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,y.params=Object.assign(Object.assign({},y.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,y.autoSendHeartbeat=!this.worker}return y}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}};var is=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Gv(t,e,r){let n=new URL(e,t);if(r)for(let[i,s]of Object.entries(r))s!==void 0&&n.searchParams.set(i,s);return n.toString()}async function Jv(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Xv(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:i,body:s,headers:o}){let a=Gv(t.baseUrl,n,i),l=await Jv(t.auth),u=await e(a,{method:r,headers:{...s?{"Content-Type":"application/json"}:{},...l,...o},body:s?JSON.stringify(s):void 0}),c=await u.text(),d=(u.headers.get("content-type")||"").includes("application/json"),p=d&&c?JSON.parse(c):c;if(!u.ok){let m=d?p:void 0,y=m?.error;throw new is(y?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:y?.type,icebergCode:y?.code,details:m})}return{status:u.status,headers:u.headers,data:p}}}}function Yo(t){return t.join("")}var Qv=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:Yo(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Yo(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Yo(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Yo(t.namespace)}`}),!0}catch(e){if(e instanceof is&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof is&&r.status===409)return;throw r}}};function Kn(t){return t.join("")}var Yv=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Kn(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Kn(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Kn(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Kn(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Kn(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Kn(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof is&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof is&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Lp=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Xv({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new Qv(this.client,e),this.tableOps=new Yv(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};function os(t){"@babel/helpers - typeof";return os=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},os(t)}function Zv(t,e){if(os(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(os(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function e0(t){var e=Zv(t,"string");return os(e)=="symbol"?e:e+""}function t0(t,e,r){return(e=e0(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function jp(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function D(t){for(var e=1;et?(...e)=>t(...e):(...e)=>fetch(...e),i0=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ec=t=>{if(Array.isArray(t))return t.map(r=>ec(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,n])=>{let i=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[i]=ec(n)}),e},s0=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),Dp=t=>{if(typeof t=="object"&&t!==null){let e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){let r=e.error;if(typeof r.message=="string")return r.message}}return JSON.stringify(t)},o0=async(t,e,r,n)=>{if(t!==null&&typeof t=="object"&&"json"in t&&typeof t.json=="function"){let i=t,s=parseInt(String(i.status),10);Number.isFinite(s)||(s=500),i.json().then(o=>{let a=o?.statusCode||o?.code||s+"";e(new Zo(Dp(o),s,a,n))}).catch(()=>{let o=s+"";e(new Zo(i.statusText||`HTTP ${s} error`,s,o,n))})}else e(new Up(Dp(t),t,n))},a0=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!n)return D(D({},i),r);if(i0(n)){var s;let o=e?.headers||{},a;for(let[l,u]of Object.entries(o))l.toLowerCase()==="content-type"&&(a=u);i.headers=ea(o,"Content-Type",(s=a)!==null&&s!==void 0?s:"application/json"),i.body=JSON.stringify(n)}else i.body=n;return e?.duplex&&(i.duplex=e.duplex),D(D({},i),r)};async function ss(t,e,r,n,i,s,o){return new Promise((a,l)=>{t(r,a0(e,n,i,s)).then(u=>{if(!u.ok)throw u;if(n?.noResolveJson)return u;if(o==="vectors"){let c=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!c||!c.includes("application/json"))return{}}return u.json()}).then(u=>a(u)).catch(u=>o0(u,l,n,o))})}function zp(t="storage"){return{get:async(e,r,n,i)=>ss(e,"GET",r,n,i,void 0,t),post:async(e,r,n,i,s)=>ss(e,"POST",r,i,s,n,t),put:async(e,r,n,i,s)=>ss(e,"PUT",r,i,s,n,t),head:async(e,r,n,i)=>ss(e,"HEAD",r,D(D({},n),{},{noResolveJson:!0}),i,void 0,t),remove:async(e,r,n,i,s)=>ss(e,"DELETE",r,i,s,n,t)}}var l0=zp("storage"),{get:as,post:xt,put:tc,head:u0,remove:ls}=l0,et=zp("vectors"),Gn=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=r0(e),this.fetch=n0(r),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=ea(this.headers,t,e),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ra(r))return{data:null,error:r};throw r}}},Bp;Bp=Symbol.toStringTag;var c0=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Bp]="StreamDownloadBuilder",this.promise=null}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ra(e))return{data:null,error:e};throw e}}},Mp;Mp=Symbol.toStringTag;var d0=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Mp]="BlobDownloadBuilder",this.promise=null}asStream(){return new c0(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ra(e))return{data:null,error:e};throw e}}},Zu={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},$p={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},h0=class extends Gn{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,n){var i=this;return i.handleOperation(async()=>{let s,o=D(D({},$p),n),a=D(D({},i.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;if(typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),l&&s.append("metadata",i.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",o.cacheControl),l&&!s.has("metadata")&&s.append("metadata",i.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=i.toBase64(i.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!o.duplex&&(o.duplex="half")),n?.headers)for(let[p,m]of Object.entries(n.headers))a=ea(a,p,m);let u=i._removeEmptyFolders(e),c=i._getFinalPath(u),d=await(t=="PUT"?tc:xt)(i.fetch,`${i.url}/object/${c}`,s,D({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{path:u,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var i=this;let s=i._removeEmptyFolders(t),o=i._getFinalPath(s),a=new URL(i.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),i.handleOperation(async()=>{let l,u=D(D({},$p),n),c=D(D({},i.headers),{"x-upsert":String(u.upsert)}),d=u.metadata;if(typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),d&&l.append("metadata",i.encodeMetadata(d)),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.has("cacheControl")||l.append("cacheControl",u.cacheControl),d&&!l.has("metadata")&&l.append("metadata",i.encodeMetadata(d))):(l=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType,d&&(c["x-metadata"]=i.toBase64(i.encodeMetadata(d))),(typeof ReadableStream<"u"&&l instanceof ReadableStream||l&&typeof l=="object"&&"pipe"in l&&typeof l.pipe=="function")&&!u.duplex&&(u.duplex="half")),n?.headers)for(let[p,m]of Object.entries(n.headers))c=ea(c,p,m);return{path:s,fullPath:(await tc(i.fetch,a.toString(),l,D({headers:c},u?.duplex?{duplex:u.duplex}:{}))).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t),i=D({},r.headers);e?.upsert&&(i["x-upsert"]="true");let s=await xt(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:i}),o=new URL(r.url+s.url),a=o.searchParams.get("token");if(!a)throw new ta("No token returned by API");return{signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await xt(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await xt(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let i=n._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,o=await xt(n.fetch,`${n.url}/object/sign/${i}`,D({expiresIn:e},s?{transform:r.transform}:{}),{headers:n.headers}),a=new URLSearchParams;r?.download&&a.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&a.set("cacheNonce",String(r.cacheNonce));let l=a.toString();return{signedUrl:encodeURI(`${n.url}${o.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{let i=await xt(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),s=new URLSearchParams;r?.download&&s.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&s.set("cacheNonce",String(r.cacheNonce));let o=s.toString();return i.map(a=>D(D({},a),{},{signedUrl:a.signedURL?encodeURI(`${n.url}${a.signedURL}${o?`&${o}`:""}`):null}))})}download(t,e,r){let n=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",i=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(i,e.transform),e?.cacheNonce!=null&&i.set("cacheNonce",String(e.cacheNonce));let s=i.toString(),o=this._getFinalPath(t),a=()=>as(this.fetch,`${this.url}/${n}/${o}${s?`?${s}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new d0(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>ec(await as(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await u0(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(ra(i)){var n;let s=i instanceof Zo?i.status:i instanceof Up?(n=i.originalError)===null||n===void 0?void 0:n.status:void 0;if(s!==void 0&&[400,404].includes(s))return{data:!1,error:i}}throw i}}getPublicUrl(t,e){let r=this._getFinalPath(t),n=new URLSearchParams;e?.download&&n.set("download",e.download===!0?"":e.download),e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce));let i=n.toString(),s=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}`)+(i?`?${i}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await ls(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async purgeCache(t,e,r){var n=this;return n.handleOperation(async()=>{let i=n._getFinalPath(t),s=new URLSearchParams;e?.transformations&&s.set("transformations","true");let o=s.toString();return await ls(n.fetch,`${n.url}/cdn/${i}${o?`?${o}`:""}`,{},{headers:n.headers},r)})}async list(t,e,r){var n=this;return n.handleOperation(async()=>{let i=e?.sortBy?D(D({},Zu.sortBy),e.sortBy):Zu.sortBy,s=D(D(D({},Zu),e),{},{sortBy:i,prefix:t||""});return await xt(n.fetch,`${n.url}/object/list/${n.bucketId}`,s,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let n=D({},t);return await xt(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}},f0="2.110.1",us={"X-Client-Info":`storage-js/${f0}`},p0=class extends Gn{constructor(t,e={},r,n){let i=new URL(t);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));let s=i.href.replace(/\/$/,""),o=D(D({},us),e);super(s,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await as(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await as(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await xt(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await tc(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await xt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await ls(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}async purgeBucketCache(t,e,r){var n=this;return n.handleOperation(async()=>{let i=new URLSearchParams;e?.transformations&&i.set("transformations","true");let s=i.toString();return await ls(n.fetch,`${n.url}/cdn/${t}${s?`?${s}`:""}`,{},{headers:n.headers},r)})}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},g0=class extends Gn{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=D(D({},us),e);super(n,i,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await xt(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let n=r.toString(),i=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await as(e.fetch,i,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await ls(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!s0(t))throw new ta("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new Lp({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(i,s){let o=i[s];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(i,a),error:null}}catch(l){if(n)throw l;return{data:null,error:l}}}}})}},m0=class extends Gn{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=D(D({},us),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await et.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await et.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await et.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await et.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},y0=class extends Gn{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=D(D({},us),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await et.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await et.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await et.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await et.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await et.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},v0=class extends Gn{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=D(D({},us),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await et.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await et.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await et.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await et.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},w0=class extends v0{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new _0(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},_0=class extends m0{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new S0(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},S0=class extends y0{constructor(t,e,r,n,i){super(t,e,i),this.vectorBucketName=r,this.indexName=n}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},Fp=class extends p0{constructor(t,e={},r,n){super(t,e,r,n)}from(t){return new h0(this.url,this.headers,t,this.fetch)}get vectors(){return new w0(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new g0(this.url+"/iceberg",this.headers,this.fetch)}};var na="2.110.1";var zt=30*1e3,Jn=3,ia=Jn*zt,Hp=2*zt,Wp="http://localhost:9999",qp="supabase.auth.token";var Vp={"X-Client-Info":`gotrue-js/${na}`};var cs="X-Supabase-Api-Version",rc={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Kp=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Gp=10*60*1e3;var Or=class extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}};function A(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var sa=class extends Or{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}};function Jp(t){return A(t)&&t.name==="AuthApiError"}var Le=class extends Or{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},pt=class extends Or{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n}},he=class extends pt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function ps(t){return A(t)&&t.name==="AuthSessionMissingError"}var ir=class extends pt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Yr=class extends pt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Zr=class extends pt{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};function Xp(t){return A(t)&&t.name==="AuthImplicitGrantRedirectError"}var ds=class extends pt{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},oa=class extends pt{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}};var Xn=class extends pt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function nc(t){return A(t)&&t.name==="AuthRetryableFetchError"}var hs=class extends pt{constructor(e="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(e,"AuthRefreshDiscardedError",409,void 0)}};function Qp(t){return A(t)&&t.name==="AuthRefreshDiscardedError"}var fs=class extends pt{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}};var Pr=class extends pt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var aa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Yp=`
\r=`.split(""),k0=(()=>{let t=new Array(128);for(let e=0;e=6;){let n=e.queue>>e.queuedBits-6&63;r(aa[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(aa[n]),e.queuedBits-=6}}function eg(t,e,r){let n=k0[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function ic(t){let e=[],r=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=o=>{T0(o,n,r)};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 E0(t,e){for(let r=0;r55295&&n<=56319){let i=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}b0(n,e)}}function T0(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if(!(t>>7-n&1)){e.utf8seq=n;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&&r(e.codepoint)}}function Ir(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};for(let i=0;ie.push(r)),new Uint8Array(e)}function sr(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};return t.forEach(i=>Zp(i,r,n)),Zp(null,r,n),e.join("")}function rg(t){return Math.round(Date.now()/1e3)+t}function ng(){return Symbol("auth-callback")}var Ee=()=>typeof window<"u"&&typeof document<"u",en={tested:!1,writable:!1},la=()=>{if(!Ee())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(en.tested)return en.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),en.tested=!0,en.writable=!0}catch{en.tested=!0,en.writable=!1}return en.writable};function ig(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,s)=>{e[s]=i})}catch{}return r.searchParams.forEach((n,i)=>{e[i]=n}),e}var ua=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),sg=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",tn=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},gt=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return null}},fe=async(t,e)=>{await t.removeItem(e)},gs=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};gs.promiseConstructor=Promise;function ms(t){let e=t.split(".");if(e.length!==3)throw new Pr("Invalid JWT structure");for(let n=0;n{setTimeout(()=>e(null),t)})}function ag(t,e){return new Promise((n,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{let o=await t(s);if(!e(s,null,o)){n(o);return}}catch(o){if(!e(s,o)){i(o);return}}})()})}function x0(t){return("0"+t.toString(16)).substr(-2)}function R0(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length,i="";for(let s=0;s<56;s++)i+=r.charAt(Math.floor(Math.random()*n));return i}return crypto.getRandomValues(e),Array.from(e,x0).join("")}async function C0(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map(s=>String.fromCharCode(s)).join("")}async function A0(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;let r=await C0(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Nr(t,e,r=!1){let n=R0(),i=n;r&&(i+="/recovery"),await tn(t,`${e}-code-verifier`,i);let s=await A0(n);return[s,n===s?"plain":"s256"]}var O0=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function lg(t){let e=t.headers.get(cs);if(!e||!e.match(O0))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function ug(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function cg(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")}}var P0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Bt(t){if(!P0.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function tt(t){if(!t.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function ca(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="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 "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function dg(t,e){return new Proxy(t,{get:(r,n,i)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){let s=n.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,i)}return!e.value&&typeof n=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,n,i)}})}function sc(t){return JSON.parse(JSON.stringify(t))}var rn=t=>{if(typeof t=="object"&&t!==null){let e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(t)},I0=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function hg(t){var e;if(!sg(t))throw new Xn(rn(t),0);if(I0.includes(t.status))throw new Xn(rn(t),t.status);let r;try{r=await t.json()}catch(s){throw new Le(rn(s),s)}let n,i=lg(t);if(i&&i.getTime()>=rc["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new fs(rn(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new he}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((s,o)=>s&&typeof o=="string",!0))throw new fs(rn(r),t.status,r.weak_password.reasons);throw new sa(rn(r),t.status||500,n)}var N0=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r))};async function L(t,e,r,n){var i;let s=Object.assign({},n?.headers);s[cs]||(s[cs]=rc["2024-01-01"].name),n?.jwt&&(s.Authorization=`Bearer ${n.jwt}`);let o=(i=n?.query)!==null&&i!==void 0?i:{};n?.redirectTo&&(o.redirect_to=n.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await L0(t,e,r+a,{headers:s,noResolveJson:n?.noResolveJson},{},n?.body);return n?.xform?n?.xform(l):{data:Object.assign({},l),error:null}}async function L0(t,e,r,n,i,s){let o=N0(e,n,i,s),a;try{a=await t(r,Object.assign({},o))}catch(l){throw console.error(l),new Xn(rn(l),0)}if(a.ok||await hg(a),n?.noResolveJson)return a;try{return await a.json()}catch(l){await hg(l)}}function rt(t){var e;let r=null;j0(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=rg(t.expires_in)));let n=(e=t.user)!==null&&e!==void 0?e:typeof t?.id=="string"?t:null;return{data:{session:r,user:n},error:null}}function oc(t){let e=rt(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((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Mt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function fg(t){return{data:t,error:null}}function pg(t){let{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s}=t,o=Xr(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function ac(t){return t}function j0(t){return!!t.access_token&&!!t.refresh_token&&!!t.expires_in}var da=["global","local","others"];var nn=class{constructor({url:e="",headers:r={},fetch:n,experimental:i}){this.url=e,this.headers=r,this.fetch=ua(n),this.experimental=i??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,r=da[0]){if(da.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${da.join(", ")}`);try{return await L(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(A(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await L(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Mt})}catch(n){if(A(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:r}=e,n=Xr(e,["options"]),i=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(i.new_email=n?.newEmail,delete i.newEmail),await L(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:pg,redirectTo:r?.redirectTo})}catch(r){if(A(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await L(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Mt})}catch(r){if(A(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,n,i,s,o,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await L(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:ac});if(c.error)throw c.error;let d=await c.json(),p=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(y=>{let v=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(y.split(";")[1].split("=")[1]);u[`${b}Page`]=v}),u.total=parseInt(p)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(A(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Bt(e);try{return await L(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Mt})}catch(r){if(A(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Bt(e);try{return await L(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Mt})}catch(n){if(A(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){Bt(e);try{return await L(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Mt})}catch(n){if(A(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){Bt(e.userId);try{let{data:r,error:n}=await L(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:r,error:n}}catch(r){if(A(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Bt(e.userId),Bt(e.id);try{return{data:await L(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,i,s,o,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await L(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:ac});if(c.error)throw c.error;let d=await c.json(),p=(o=c.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(y=>{let v=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(y.split(";")[1].split("=")[1]);u[`${b}Page`]=v}),u.total=parseInt(p)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(A(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await L(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(A(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await L(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(A(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await L(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(A(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await L(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await L(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(A(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await L(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:n=>{var i;return{data:{providers:(i=n?.providers)!==null&&i!==void 0?i:[]},error:null}}})}catch(r){if(A(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await L(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(A(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await L(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(A(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await L(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(A(n))return{data:null,error:n};throw n}}async _deleteCustomProvider(e){try{return await L(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}}async _adminListPasskeys(e){tt(this.experimental),Bt(e.userId);try{return await L(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(A(r))return{data:null,error:r};throw r}}async _adminDeletePasskey(e){tt(this.experimental),Bt(e.userId),Bt(e.passkeyId);try{return await L(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}}};function lc(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var D0={debug:!!(globalThis&&la()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},ha=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};function gg(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function uc(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function mg(t){return parseInt(t,16)}function yg(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function vg(t){var e;let{chainId:r,domain:n,expirationTime:i,issuedAt:s=new Date,nonce:o,notBefore:a,requestId:l,resources:u,scheme:c,uri:d,version:p}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(p!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${p}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let m=uc(t.address),y=c?`${c}://${n}`:n,v=t.statement?`${t.statement}
`:"",b=`${y} wants you to sign in with your Ethereum account:
${m}
${v}`,f=`URI: ${d}
Version: ${p}
Chain ID: ${r}${o?`
Nonce: ${o}`:""}
Issued At: ${s.toISOString()}`;if(i&&(f+=`
Expiration Time: ${i.toISOString()}`),a&&(f+=`
Not Before: ${a.toISOString()}`),l&&(f+=`
Request ID: ${l}`),u){let h=`
Resources:`;for(let g of u){if(!g||typeof g!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${g}`);h+=`
- ${g}`}f+=h}return`${b}
${f}`}var ue=class extends Error{constructor({message:e,code:r,cause:n,name:i}){var s;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(s=i??(n instanceof Error?n.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}},sn=class extends ue{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function wg({error:t,options:e}){var r,n,i;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ue({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new ue({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new ue({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=s.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new ue({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new ue({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new ue({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new ue({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new ue({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(cc(o)){if(s.rp.id!==o)return new ue({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new ue({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new ue({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function _g({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ue({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new ue({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let n=window.location.hostname;if(cc(n)){if(r.rpId!==n)return new ue({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new ue({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var dc=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},ga=new dc;function hc(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:n}=t,i=Xr(t,["challenge","user","excludeCredentials"]),s=Ir(e).buffer,o=Object.assign(Object.assign({},r),{id:Ir(r.id).buffer}),a=Object.assign(Object.assign({},i),{challenge:s,user:o});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let l=0;l0){s.allowCredentials=new Array(r.length);for(let o=0;oi!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(let i of t)if(i)for(let s in i){let o=i[s];if(o!==void 0)if(Array.isArray(o))n[s]=o;else if(r(o))n[s]=o;else if(e(o)){let a=n[s];e(a)?n[s]=fa(a,o):n[s]=fa(o)}else n[s]=o}return n}function z0(t,e){return fa($0,t,e||{})}function B0(t,e){return fa(U0,t,e||{})}var pa=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:n,signal:i},s){var o;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let u=i??ga.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){let d=n;if(d)c.name=`${c.id}:${d}`;else{let m=(await this.client.getUser()).data.user,y=((o=m?.user_metadata)===null||o===void 0?void 0:o.name)||m?.email||m?.id||"User";c.name=`${c.id}:${y}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{let c=z0(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:p}=await mc({publicKey:c,signal:u});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:p}}case"request":{let c=B0(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:p}=await yc(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:p}}}}catch(a){return A(a)?{data:null,error:a}:{data:null,error:new Le("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return{data:null,error:new Or("rpId is required for WebAuthn authentication")};try{if(!ys())return{data:null,error:new Le("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:i},{request:s});if(!o)return{data:null,error:a};let{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:n,credential_response:l.credential_response}})}catch(o){return A(o)?{data:null,error:o}:{data:null,error:new Le("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return{data:null,error:new Or("rpId is required for WebAuthn registration")};try{if(!ys())return{data:null,error:new Le("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(c=>{var d;return(d=c.data)===null||d===void 0?void 0:d.all.find(p=>p.factor_type==="webauthn"&&p.friendly_name===e&&p.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c?.id}):void 0),{data:null,error:a};let{data:l,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:i},{create:s});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:n,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(o){return A(o)?{data:null,error:o}:{data:null,error:new Le("Unexpected error in register",o)}}}};gg();var M0={url:Wp,storageKey:qp,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Vp,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Qn={},ma=class t{get jwks(){var e,r;return(r=(e=Qn[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Qn[this.storageKey]=Object.assign(Object.assign({},Qn[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Qn[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Qn[this.storageKey]=Object.assign(Object.assign({},Qn[this.storageKey]),{cachedAt:e})}constructor(e){var r,n,i;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let s=Object.assign(Object.assign({},M0),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&Ee()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.experimental=(n=s.experimental)!==null&&n!==void 0?n:{},this.admin=new nn({url:s.url,headers:s.headers,fetch:s.fetch,experimental:this.experimental}),this.url=s.url,this.headers=s.headers,this.fetch=ua(s.fetch),this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock!=null&&(this.lock=s.lock),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new pa(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(s.storage?this.storage=s.storage:la()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=lc(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=lc(this.memoryStorage)),Ee()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}s.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${na}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){var e;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let r=await this.initializePromise,n=(e=this._pendingInitNotifications)!==null&&e!==void 0?e:[];this._pendingInitNotifications=null;for(let i of n)await this._notifyAllSubscribers(i.event,i.session,i.broadcast);return r}async _initialize(){var e;try{let r={},n="none";if(Ee()&&(r=ig(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),Ee()&&this.detectSessionInUrl&&n!=="none"){let{data:i,error:s}=await this._getSessionFromURL(r,n);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),Xp(s)){let l=(e=s.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:s}}return{error:s}}let{session:o,redirectType:a}=i;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(r){return A(r)?this._returnResult({error:r}):this._returnResult({error:new Le("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,i;try{let s=await L(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:rt}),{data:o,error:a}=s;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(A(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,n,i;try{let s;if("email"in e){let{email:c,password:d,options:p}=e,m=null,y=null;this.flowType==="pkce"&&([m,y]=await Nr(this.storage,this.storageKey)),s=await L(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p?.emailRedirectTo,body:{email:c,password:d,data:(r=p?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:m,code_challenge_method:y},xform:rt})}else if("phone"in e){let{phone:c,password:d,options:p}=e;s=await L(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(n=p?.data)!==null&&n!==void 0?n:{},channel:(i=p?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:rt})}else throw new Yr("You must provide either an email or phone number and a password");let{data:o,error:a}=s;if(a||!o)return await fe(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(await fe(this.storage,`${this.storageKey}-code-verifier`),A(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:o,options:a}=e;r=await L(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:oc})}else if("phone"in e){let{phone:s,password:o,options:a}=e;r=await L(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:oc})}else throw new Yr("You must provide either an email or phone number and a password");let{data:n,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!n||!n.session||!n.user){let s=new ir;return this._returnResult({data:{user:null,session:null},error:s})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:i})}catch(r){if(A(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,i,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e)):this._exchangeCodeForSession(e)}async signInWithWeb3(e){let{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,n,i,s,o,a,l,u,c,d,p;let m,y;if("message"in e)m=e.message,y=e.signature;else{let{chain:v,wallet:b,statement:f,options:h}=e,g;if(Ee())if(typeof b=="object")g=b;else{let H=window;if("ethereum"in H&&typeof H.ethereum=="object"&&"request"in H.ethereum&&typeof H.ethereum.request=="function")g=H.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof b!="object"||!h?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");g=b}let _=new URL((r=h?.url)!==null&&r!==void 0?r:window.location.href),k=await g.request({method:"eth_requestAccounts"}).then(H=>H).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!k||k.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let w=uc(k[0]),S=(n=h?.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!S){let H=await g.request({method:"eth_chainId"});S=mg(H)}let P={domain:_.host,address:w,statement:f,uri:_.href,version:"1",chainId:S,nonce:(i=h?.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(o=(s=h?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=h?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=h?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=h?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=h?.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=vg(P),y=await g.request({method:"personal_sign",params:[yg(m),w]})}try{let{data:v,error:b}=await L(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:y},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:rt});if(b)throw b;if(!v||!v.session||!v.user){let f=new ir;return this._returnResult({data:{user:null,session:null},error:f})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:b})}catch(v){if(A(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(e){var r,n,i,s,o,a,l,u,c,d,p,m;let y,v;if("message"in e)y=e.message,v=e.signature;else{let{chain:b,wallet:f,statement:h,options:g}=e,_;if(Ee())if(typeof f=="object")_=f;else{let w=window;if("solana"in w&&typeof w.solana=="object"&&("signIn"in w.solana&&typeof w.solana.signIn=="function"||"signMessage"in w.solana&&typeof w.solana.signMessage=="function"))_=w.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof f!="object"||!g?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=f}let k=new URL((r=g?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in _&&_.signIn){let w=await _.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},g?.signInWithSolana),{version:"1",domain:k.host,uri:k.href}),h?{statement:h}:null)),S;if(Array.isArray(w)&&w[0]&&typeof w[0]=="object")S=w[0];else if(w&&typeof w=="object"&&"signedMessage"in w&&"signature"in w)S=w;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in S&&"signature"in S&&(typeof S.signedMessage=="string"||S.signedMessage instanceof Uint8Array)&&S.signature instanceof Uint8Array)y=typeof S.signedMessage=="string"?S.signedMessage:new TextDecoder().decode(S.signedMessage),v=S.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in _)||typeof _.signMessage!="function"||!("publicKey"in _)||typeof _!="object"||!_.publicKey||!("toBase58"in _.publicKey)||typeof _.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${k.host} wants you to sign in with your Solana account:`,_.publicKey.toBase58(),...h?["",h,""]:[""],"Version: 1",`URI: ${k.href}`,`Issued At: ${(i=(n=g?.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((s=g?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${g.signInWithSolana.notBefore}`]:[],...!((o=g?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${g.signInWithSolana.expirationTime}`]:[],...!((a=g?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${g.signInWithSolana.chainId}`]:[],...!((l=g?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${g.signInWithSolana.nonce}`]:[],...!((u=g?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${g.signInWithSolana.requestId}`]:[],...!((d=(c=g?.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||d===void 0)&&d.length?["Resources",...g.signInWithSolana.resources.map(S=>`- ${S}`)]:[]].join(`
`);let w=await _.signMessage(new TextEncoder().encode(y),"utf8");if(!w||!(w instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=w}}try{let{data:b,error:f}=await L(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:sr(v)},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:rt});if(f)throw f;if(!b||!b.session||!b.user){let h=new ir;return this._returnResult({data:{user:null,session:null},error:h})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:f})}catch(b){if(A(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async _exchangeCodeForSession(e){let r=await gt(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new oa;let{data:s,error:o}=await L(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:rt});if(await fe(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!s||!s.session||!s.user){let a=new ir;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers(i==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:i??null}),error:o})}catch(s){if(await fe(this.storage,`${this.storageKey}-code-verifier`),A(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:n,token:i,access_token:s,nonce:o}=e,a=await L(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:s,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:rt}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){let c=new ir;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(A(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,s,o;try{if("email"in e){let{email:a,options:l}=e,u=null,c=null;this.flowType==="pkce"&&([u,c]=await Nr(this.storage,this.storageKey));let{error:d}=await L(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:u,error:c}=await L(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l?.data)!==null&&i!==void 0?i:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:c})}throw new Yr("You must provide either an email or phone number.")}catch(a){if(await fe(this.storage,`${this.storageKey}-code-verifier`),A(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,n;try{let i,s;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,error:a}=await L(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:i,xform:rt});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,u=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(A(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,s,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await Nr(this.storage,this.storageKey));let u=await L(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:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e?.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:fg});return!((s=u.data)===null||s===void 0)&&s.url&&Ee()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(await fe(this.storage,`${this.storageKey}-code-verifier`),A(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new he;let{error:i}=await L(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(A(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:n,type:i,options:s}=e,o=null,a=null;this.flowType==="pkce"&&([o,a]=await Nr(this.storage,this.storageKey));let{error:l}=await L(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken},code_challenge:o,code_challenge_method:a},redirectTo:s?.emailRedirectTo});return l&&await fe(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l})}else if("phone"in e){let{phone:n,type:i,options:s}=e,{data:o,error:a}=await L(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new Yr("You must provide either an email or phone number and a type")}catch(r){if(await fe(this.storage,`${this.storageKey}-code-verifier`),A(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e)):await this._useSession(async e=>e)}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await n}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{let r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await gt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()Date.now())){let a=await gt(this.storage,this.storageKey);if(a&&a.refresh_token===e.refresh_token)return this._returnResult({data:{session:e},error:null})}return this._returnResult({data:{session:null},error:s})}return this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r;return this.lock!=null?r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):r=await this._getUser(),r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await L(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Mt}):await this._useSession(async r=>{var n,i,s;let{data:o,error:a}=r;if(a)throw a;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new he}:await L(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&s!==void 0?s:void 0,xform:Mt})})}catch(r){if(A(r))return ps(r)&&(await this._removeSession(),await fe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r)):await this._updateUser(e,r)}async _updateUser(e,r={}){try{return await this._useSession(async n=>{let{data:i,error:s}=n;if(s)throw s;if(!i.session)throw new he;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Nr(this.storage,this.storageKey));let{data:u,error:c}=await L(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:Mt});if(c)throw c;return o.user=u.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await fe(this.storage,`${this.storageKey}-code-verifier`),A(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e)):await this._setSession(e)}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new he;let r=Date.now()/1e3,n=r,i=!0,s=null,{payload:o}=ms(e.access_token);if(o.exp&&(n=o.exp,i=n<=r),i){let{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};s=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(A(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e)):await this._refreshSession(e)}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!e?.refresh_token)throw new he;let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(A(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var n;try{if(!Ee())throw new Zr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Zr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new ds("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Zr("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new ds("No code detected.");let{data:g,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;let k=new URL(window.location.href);return k.searchParams.delete("code"),window.history.replaceState(window.history.state,"",k.toString()),{data:{session:g.session,redirectType:(n=g.redirectType)!==null&&n!==void 0?n:null},error:null}}let{provider_token:i,provider_refresh_token:s,access_token:o,refresh_token:a,expires_in:l,expires_at:u,token_type:c}=e;if(!o||!l||!a||!c)throw new Zr("No session defined in URL");let d=Math.round(Date.now()/1e3),p=parseInt(l),m=d+p;u&&(m=parseInt(u));let y=m-d;y*1e3<=zt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${y}s, should have been closer to ${p}s`);let v=m-p;d-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,m,d):d-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",v,m,d);let{data:b,error:f}=await this._getUser(o);if(f)throw f;let h={provider_token:i,provider_refresh_token:s,access_token:o,expires_in:p,expires_at:m,refresh_token:a,token_type:c,user:b.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:h,redirectType:e.type},error:null})}catch(i){if(A(i))return this._returnResult({data:{session:null,redirectType:null},error:i});throw i}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){let r=await gt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e)):await this._signOut(e)}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;let{data:i,error:s}=r;if(s&&!ps(s))return this._returnResult({error:s});let o=(n=i.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(Jp(a)&&(a.status===404||a.status===401||a.status===403)||ps(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await fe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=ng(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)}):await this._emitInitialSession(r)))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{let{data:{session:s},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),ps(s)?console.warn(s):console.error(s)}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await Nr(this.storage,this.storageKey,!0));try{return await L(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await fe(this.storage,`${this.storageKey}-code-verifier`),A(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:n,error:i}=await this._useSession(async s=>{var o,a,l,u,c;let{data:d,error:p}=s;if(p)throw p;let m=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 L(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(i)throw i;return Ee()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url},error:null})}catch(n){if(A(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{let{error:i,data:{session:s}}=r;if(i)throw i;let{options:o,provider:a,token:l,access_token:u,nonce:c}=e,d=await L(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=s?.access_token)!==null&&n!==void 0?n:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:rt}),{data:p,error:m}=d;return m?this._returnResult({data:{user:null,session:null},error:m}):!p||!p.session||!p.user?this._returnResult({data:{user:null,session:null},error:new ir}):(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("USER_UPDATED",p.session)),this._returnResult({data:p,error:m}))}catch(i){if(await fe(this.storage,`${this.storageKey}-code-verifier`),A(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)throw o;return await L(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=s.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r="#_refreshAccessToken()";this._debug(r,"begin");try{let n=Date.now();return await ag(async i=>(i>0&&await og(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await L(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:rt})),(i,s)=>{let o=200*Math.pow(2,i);return s&&nc(s)&&Date.now()+o-nDate.now())?this._debug(i,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:o,expiresAt:Date.now()+Hp},(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,r,n=!0){if(this._pendingInitNotifications!==null&&n){this._pendingInitNotifications.push({event:e,session:r,broadcast:n});return}let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){s.push(l)}});if(await Promise.all(o),s.length>0){for(let a=0;athis._autoRefreshTokenTick(),zt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)===null||e===void 0||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((n.expires_at*1e3-e)/zt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${zt}ms, refresh threshold is ${Jn} ticks`),i<=Jn&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof ha)this._debug("auto refresh token tick lock not available");else throw e}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let e=Date.now();try{await this._useSession(async r=>{let{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((n.expires_at*1e3-e)/zt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${zt}ms, refresh threshold is ${Jn} ticks`),i<=Jn&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ee()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;if(this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!e)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()});else{if(document.visibilityState!=="visible"){this._debug(r,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){let i=[`provider=${encodeURIComponent(r)}`];if(n?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[s,o]=await Nr(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString())}if(n?.queryParams){let s=new URLSearchParams(n.queryParams);i.push(s.toString())}return n?.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;let{data:i,error:s}=r;return s?this._returnResult({data:null,error:s}):await L(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:u}=await L(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&l.type==="totp"&&(!((i=l?.totp)===null||i===void 0)&&i.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){let r=async()=>{try{return await this._useSession(async n=>{var i;let{data:s,error:o}=n;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?pc(e.webauthn.credential_response):gc(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:u}=await L(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(i=s?.session)===null||i===void 0?void 0:i.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:u}))})}catch(n){if(A(n))return this._returnResult({data:null,error:n});throw n}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challenge(e){let r=async()=>{try{return await this._useSession(async n=>{var i;let{data:s,error:o}=n;if(o)return this._returnResult({data:null,error:o});let a=await L(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(i=s?.session)===null||i===void 0?void 0:i.access_token});if(a.error)return a;let{data:l}=a;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:hc(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:fc(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(n){if(A(n))return this._returnResult({data:null,error:n});throw n}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challengeAndVerify(e){let{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};let i={all:[],phone:[],totp:[],webauthn:[]};for(let s of(e=r?.factors)!==null&&e!==void 0?e:[])i.all.push(s),s.status==="verified"&&i[s.factor_type].push(s);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,i,s;if(e)try{let{payload:m}=ms(e),y=null;m.aal&&(y=m.aal);let v=y,{data:{user:b},error:f}=await this.getUser(e);if(f)return this._returnResult({data:null,error:f});((n=(r=b?.factors)===null||r===void 0?void 0:r.filter(_=>_.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(v="aal2");let g=m.amr||[];return{data:{currentLevel:y,nextLevel:v,currentAuthenticationMethods:g},error:null}}catch(m){if(A(m))return this._returnResult({data:null,error:m});throw m}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=ms(o.access_token),u=null;l.aal&&(u=l.aal);let c=u;((s=(i=o.user.factors)===null||i===void 0?void 0:i.filter(m=>m.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let p=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:p},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?await L(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new he})})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new he});let o=await L(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&Ee()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(A(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new he});let o=await L(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&Ee()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(A(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await L(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new he})})}catch(e){if(A(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?(await L(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new he})})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(a=>a.kid===e);if(n)return n;let i=Date.now();if(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+Gp>i)return n;let{data:s,error:o}=await L(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=i,n=s.keys.find(a=>a.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){let{data:m,error:y}=await this.getSession();if(y||!m.session)return this._returnResult({data:null,error:y});n=m.session.access_token}let{header:i,payload:s,signature:o,raw:{header:a,payload:l}}=ms(n);if(!r?.allowExpired)try{ug(s.exp)}catch(m){throw new Pr(m instanceof Error?m.message:"JWT validation failed")}let u=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!u){let{error:m}=await this.getUser(n);if(m)throw m;return{data:{claims:s,header:i,signature:o},error:null}}let c=cg(i.alg),d=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,d,o,tg(`${a}.${l}`)))throw new Pr("Invalid JWT signature");return{data:{claims:s,header:i,signature:o},error:null}}catch(n){if(A(n))return this._returnResult({data:null,error:n});throw n}}async signInWithPasskey(e){var r,n,i;tt(this.experimental);try{if(!ys())return this._returnResult({data:null,error:new Le("Browser does not support WebAuthn",null)});let{data:s,error:o}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}});if(o||!s)return this._returnResult({data:null,error:o});let a=fc(s.options),l=(i=(n=e?.options)===null||n===void 0?void 0:n.signal)!==null&&i!==void 0?i:ga.createNewAbortSignal(),{data:u,error:c}=await yc({publicKey:a,signal:l});if(c||!u)return this._returnResult({data:null,error:c??new Le("WebAuthn ceremony failed",null)});let d=gc(u);return this._verifyPasskeyAuthentication({challengeId:s.challenge_id,credential:d})}catch(s){if(A(s))return this._returnResult({data:null,error:s});throw s}}async registerPasskey(e){var r,n;tt(this.experimental);try{if(!ys())return this._returnResult({data:null,error:new Le("Browser does not support WebAuthn",null)});let{data:i,error:s}=await this._startPasskeyRegistration();if(s||!i)return this._returnResult({data:null,error:s});let o=hc(i.options),a=(n=(r=e?.options)===null||r===void 0?void 0:r.signal)!==null&&n!==void 0?n:ga.createNewAbortSignal(),{data:l,error:u}=await mc({publicKey:o,signal:a});if(u||!l)return this._returnResult({data:null,error:u??new Le("WebAuthn ceremony failed",null)});let c=pc(l);return this._verifyPasskeyRegistration({challengeId:i.challenge_id,credential:c})}catch(i){if(A(i))return this._returnResult({data:null,error:i});throw i}}async _startPasskeyRegistration(){tt(this.experimental);try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new he});let{data:i,error:s}=await L(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:i,error:null})})}catch(e){if(A(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){tt(this.experimental);try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new he});let{data:s,error:o}=await L(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:n.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:s,error:null})})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;tt(this.experimental);try{let{data:n,error:i}=await L(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e?.options)===null||r===void 0?void 0:r.captchaToken}}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})}catch(n){if(A(n))return this._returnResult({data:null,error:n});throw n}}async _verifyPasskeyAuthentication(e){tt(this.experimental);try{let{data:r,error:n}=await L(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:rt});return n?this._returnResult({data:null,error:n}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){tt(this.experimental);try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new he});let{data:i,error:s}=await L(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})});return s?this._returnResult({data:null,error:s}):this._returnResult({data:i,error:null})})}catch(e){if(A(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){tt(this.experimental);try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new he});let{data:s,error:o}=await L(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:s,error:null})})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){tt(this.experimental);try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new he});let{error:s}=await L(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,noResolveJson:!0});return s?this._returnResult({data:null,error:s}):this._returnResult({data:null,error:null})})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}};ma.nextInstanceID={};var vc=ma;var F0=vc,wc=F0;var H0="2.110.1",vs="",wa;typeof Deno<"u"?(vs="deno",wa=(ya=Deno.version)===null||ya===void 0?void 0:ya.deno):typeof document<"u"?vs="web":typeof navigator<"u"&&navigator.product==="ReactNative"?vs="react-native":(vs="node",wa=typeof process<"u"?(va=process.version)===null||va===void 0?void 0:va.replace(/^v/,""):void 0);var ya,va,bg=[`runtime=${vs}`];wa&&bg.push(`runtime-version=${wa}`);var W0={"X-Client-Info":`supabase-js/${H0}; ${bg.join("; ")}`},q0={headers:W0},V0={schema:"public"},K0={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},G0={},J0={enabled:!1,respectSamplingDecision:!0};function X0(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(c){try{u(n.next(c))}catch(d){o(d)}}function l(c){try{u(n.throw(c))}catch(d){o(d)}}function u(c){c.done?s(c.value):i(c.value).then(a,l)}u((n=n.apply(t,e||[])).next())})}var _c=null,Q0="@opentelemetry/api";function Y0(){return _c===null&&(_c=import(Q0).catch(()=>null)),_c}function Z0(){return X0(this,void 0,void 0,function*(){try{let t=yield Y0();if(!t||!t.propagation||!t.context)return null;let e={};t.propagation.inject(t.context.active(),e);let r=e.traceparent;return r?{traceparent:r,tracestate:e.tracestate,baggage:e.baggage}:null}catch{return null}})}function ew(t){if(!t||typeof t!="string")return null;let e=t.split("-");if(e.length!==4)return null;let[r,n,i,s]=e;if(r.length!==2||n.length!==32||i.length!==16||s.length!==2)return null;let o=/^[0-9a-f]+$/i;return!o.test(r)||!o.test(n)||!o.test(i)||!o.test(s)||n==="00000000000000000000000000000000"||i==="0000000000000000"?null:{version:r,traceId:n,parentId:i,traceFlags:s,isSampled:(parseInt(s,16)&1)===1}}function tw(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(let n of e)try{if(typeof n=="string"){if(rw(r.hostname,n))return!0}else if(n instanceof RegExp){if(n.test(r.hostname))return!0}else if(typeof n=="function"&&n(r))return!0}catch{continue}return!1}function rw(t,e){if(e===t)return!0;if(e.startsWith("*.")){let r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function nw(t){let e=[];try{let r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function ws(t){"@babel/helpers - typeof";return ws=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ws(t)}function iw(t,e){if(ws(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(ws(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function sw(t){var e=iw(t,"string");return ws(e)=="symbol"?e:e+""}function ow(t,e,r){return(e=sw(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Sg(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function pe(t){for(var e=1;et?(...e)=>t(...e):(...e)=>fetch(...e),lw=()=>Headers,uw=(t,e,r,n,i)=>{let s=aw(n),o=lw(),a=i?.enabled===!0,l=i?.respectSamplingDecision!==!1,u=a?nw(e):null;return async(c,d)=>{var p;let m=(p=await r())!==null&&p!==void 0?p:t,y=new o(d?.headers);if(y.has("apikey")||y.set("apikey",t),y.has("Authorization")||y.set("Authorization",`Bearer ${m}`),u){let v=await cw(c,u,l);v&&(v.traceparent&&!y.has("traceparent")&&y.set("traceparent",v.traceparent),v.tracestate&&!y.has("tracestate")&&y.set("tracestate",v.tracestate),v.baggage&&!y.has("baggage")&&y.set("baggage",v.baggage))}return s(c,pe(pe({},d),{},{headers:y}))}};async function cw(t,e,r){if(!tw(typeof t=="string"||t instanceof URL?t:t.url,e))return null;let n=await Z0();if(!n||!n.traceparent)return null;if(r){let i=ew(n.traceparent);if(i&&!i.isSampled)return null}return n}function kg(t){return typeof t=="boolean"?{enabled:t}:t}function dw(t){return t.endsWith("/")?t:t+"/"}function hw(t,e){var r,n,i,s,o,a;let{db:l,auth:u,realtime:c,global:d}=t,{db:p,auth:m,realtime:y,global:v}=e,b=kg(t.tracePropagation),f=kg(e.tracePropagation),h={db:pe(pe({},p),l),auth:pe(pe({},m),u),realtime:pe(pe({},y),c),storage:{},global:pe(pe(pe({},v),d),{},{headers:pe(pe({},(r=v?.headers)!==null&&r!==void 0?r:{}),(n=d?.headers)!==null&&n!==void 0?n:{})}),tracePropagation:{enabled:(i=(s=b?.enabled)!==null&&s!==void 0?s:f?.enabled)!==null&&i!==void 0?i:!1,respectSamplingDecision:(o=(a=b?.respectSamplingDecision)!==null&&a!==void 0?a:f?.respectSamplingDecision)!==null&&o!==void 0?o:!0},accessToken:async()=>""};return t.accessToken?h.accessToken=t.accessToken:delete h.accessToken,h}function fw(t){let e=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(dw(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var pw=class extends wc{constructor(t){super(t)}},gw=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;let s=fw(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let o=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:V0,realtime:G0,auth:pe(pe({},K0),{},{storageKey:o}),global:q0,tracePropagation:J0},l=hw(r??{},a);if(this.settings=l,this.storageKey=(n=l.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=l.global.headers)!==null&&i!==void 0?i:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=uw(e,t,this._getAccessToken.bind(this),l.global.fetch,l.tracePropagation),this.realtime=this._initRealtimeClient(pe({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(c=>this.realtime.setAuth(c)).catch(c=>console.warn("Failed to set initial Realtime auth token:",c)),this.rest=new vp(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new Fp(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new Ji(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:n}=await t.auth.getSession();return(e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,storageKey:s,flowType:o,lock:a,debug:l,throwOnError:u,experimental:c,lockAcquireTimeout:d,skipAutoInitialize:p},m,y){let v={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new pw({url:this.authUrl.href,headers:pe(pe({},v),m),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:a,debug:l,throwOnError:u,experimental:c,fetch:y,lockAcquireTimeout:d,skipAutoInitialize:p,hasCustomAuthorizationHeader:Object.keys(this.headers).some(b=>b.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Vn(this.realtimeUrl.href,pe(pe({},t),{},{params:pe(pe({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},Eg=(t,e,r)=>new gw(t,e,r);function mw(){if(typeof window<"u")return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=20:!1}mw()&&console.warn("\u26A0\uFE0F Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");var yw="https://lmdicjspxzwozktjuwni.supabase.co",vw="sb_publishable_8YmITtDywS7STZ5go6Tdng_HKt2QKT5",j=Eg(yw,vw);var mt=q(ie()),Cg=({onLogin:t})=>{let[e,r]=(0,Ft.useState)(""),[n,i]=(0,Ft.useState)(""),[s,o]=(0,Ft.useState)(!1),[a,l]=(0,Ft.useState)("");(0,Ft.useEffect)(()=>{j.from("shops").select("name").limit(1).single().then(({data:y})=>{y&&l(y.name)})},[]);let u=(0,Ft.useCallback)(async y=>{o(!0),i("");try{let{data:v,error:b}=await j.from("staff").select("*, shops(*)").eq("pin",y).eq("is_active",!0).maybeSingle();if(b)throw b;if(!v){i("PIN\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093"),r(""),o(!1);return}let f=v.shops,{shops:h,...g}=v;t(g,f)}catch{i("\u30ED\u30B0\u30A4\u30F3\u306B\u5931\u6557\u3057\u307E\u3057\u305F"),r("")}o(!1)},[t]),c=(0,Ft.useCallback)(y=>{i("");let v=e+y;r(v),v.length===Fu&&u(v)},[e,u]),d=()=>{r(y=>y.slice(0,-1)),i("")},p=Array.from({length:Fu},(y,v)=>(0,mt.jsx)("div",{style:{width:18,height:18,borderRadius:"50%",border:`2px solid ${J}`,background:v(0,mt.jsx)("button",{onClick:v,disabled:s,style:{width:72,height:72,borderRadius:"50%",border:`1px solid ${C}`,background:b,color:me,fontSize:24,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:y},y);return(0,mt.jsxs)("div",{style:{minHeight:"100dvh",background:Wo,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:24},children:[(0,mt.jsx)("div",{style:{fontSize:48,marginBottom:8},children:"\u{1F43E}"}),(0,mt.jsx)("h1",{style:{color:z,fontSize:28,fontWeight:700,marginBottom:4},children:"PawPOS"}),(0,mt.jsx)("p",{style:{color:me,fontSize:14,marginBottom:24},children:a||"\u30C9\u30C3\u30B0\u30B5\u30ED\u30F3\u5C02\u7528POS\u30EC\u30B8"}),(0,mt.jsx)("div",{style:{display:"flex",gap:12,marginBottom:16},children:p}),n&&(0,mt.jsx)("p",{style:{color:dt,fontSize:14,marginBottom:12},children:n}),s&&(0,mt.jsx)("p",{style:{color:J,fontSize:14,marginBottom:12},children:"\u30ED\u30B0\u30A4\u30F3\u4E2D\u2026"}),(0,mt.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:12,marginTop:8},children:[["1","2","3","4","5","6","7","8","9"].map(y=>m(y,()=>c(y))),m("\u232B",d,rr),m("0",()=>c("0")),m("C",()=>{r(""),i("")},rr)]})]})};var Yn=q($e());var ye=q(ie()),Sa=({staff:t,shop:e,onNavigate:r})=>{let[n,i]=(0,Yn.useState)([]),[s,o]=(0,Yn.useState)(0),[a,l]=(0,Yn.useState)(0),u=new Date().toISOString().slice(0,10);(0,Yn.useEffect)(()=>{j.from("appointments").select("*, pet:pets(name, breed), customer:customers(name), staff:staff(name)").eq("shop_id",e.id).eq("date",u).order("start_time").then(({data:d})=>{d&&i(d)}),j.from("transactions").select("total").eq("shop_id",e.id).eq("status","\u5B8C\u4E86").gte("paid_at",u+"T00:00:00").lte("paid_at",u+"T23:59:59").then(({data:d})=>{d&&o(d.reduce((p,m)=>p+(m.total||0),0))}),j.from("customers").select("id",{count:"exact",head:!0}).eq("shop_id",e.id).then(({count:d})=>{d!=null&&l(d)})},[e.id,u]);let c=(d,p,m,y)=>(0,ye.jsxs)("div",{onClick:y,style:{background:R,borderRadius:12,padding:16,border:`1px solid ${C}`,cursor:y?"pointer":"default",display:"flex",alignItems:"center",gap:12},children:[(0,ye.jsx)("span",{style:{fontSize:28},children:d}),(0,ye.jsxs)("div",{children:[(0,ye.jsx)("div",{style:{fontSize:12,color:O},children:p}),(0,ye.jsx)("div",{style:{fontSize:20,fontWeight:700,color:me},children:m})]})]});return(0,ye.jsxs)("div",{style:{padding:16},children:[(0,ye.jsxs)("div",{style:{marginBottom:16},children:[(0,ye.jsxs)("h2",{style:{color:z,fontSize:20,fontWeight:700},children:["\u304A\u306F\u3088\u3046\u3054\u3056\u3044\u307E\u3059\u3001",t.name,"\u3055\u3093 \u{1F43E}"]}),(0,ye.jsxs)("p",{style:{color:O,fontSize:13},children:[e.name," \u2500 ",u]})]}),(0,ye.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(2,1fr)",gap:12,marginBottom:20},children:[c("\u{1F4C5}","\u4ECA\u65E5\u306E\u4E88\u7D04",`${n.length}\u4EF6`,()=>r("appointments")),c("\u{1F4B0}","\u4ECA\u65E5\u306E\u58F2\u4E0A",`\xA5${s.toLocaleString()}`,()=>r("reports")),c("\u{1F464}","\u9867\u5BA2\u6570",`${a}\u4EBA`,()=>r("customers")),c("\u{1F4CB}","\u30B9\u30C6\u30FC\u30BF\u30B9","\u78BA\u8A8D\u3059\u308B",()=>r("status-board"))]}),(0,ye.jsx)("h3",{style:{color:z,fontSize:16,fontWeight:600,marginBottom:8},children:"\u{1F4C5} \u4ECA\u65E5\u306E\u4E88\u7D04"}),n.length===0?(0,ye.jsx)("div",{style:{background:R,borderRadius:12,padding:32,textAlign:"center",color:O,border:`1px solid ${C}`},children:"\u4ECA\u65E5\u306E\u4E88\u7D04\u306F\u3042\u308A\u307E\u305B\u3093"}):(0,ye.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:n.map(d=>(0,ye.jsxs)("div",{style:{background:R,borderRadius:10,padding:12,border:`1px solid ${C}`,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,ye.jsxs)("div",{children:[(0,ye.jsxs)("div",{style:{fontWeight:600,fontSize:15},children:[d.start_time?.slice(0,5)," ",d.pet?.name||"\u2500",(0,ye.jsx)("span",{style:{fontSize:12,color:O,marginLeft:6},children:d.pet?.breed})]}),(0,ye.jsxs)("div",{style:{fontSize:12,color:O},children:["\u98FC\u3044\u4E3B: ",d.customer?.name||"\u2500"," \uFF0F \u62C5\u5F53: ",d.staff?.name||"\u2500"]})]}),(0,ye.jsx)("span",{style:{fontSize:11,padding:"3px 8px",borderRadius:20,background:Ar[d.status]||"#ccc",color:R,fontWeight:600,whiteSpace:"nowrap"},children:d.status})]},d.id))})]})};var je=q($e());var $=q(ie()),Ag=({shop:t,staff:e})=>{let[r,n]=(0,je.useState)([]),[i,s]=(0,je.useState)(new Date().toISOString().slice(0,10)),[o,a]=(0,je.useState)([]),[l,u]=(0,je.useState)([]),[c,d]=(0,je.useState)([]),[p,m]=(0,je.useState)([]),[y,v]=(0,je.useState)({}),[b,f]=(0,je.useState)(null),[h,g]=(0,je.useState)(!1),[_,k]=(0,je.useState)(""),w=T=>{k(T),setTimeout(()=>k(""),Ne)},S=(0,je.useCallback)(async()=>{let{data:T}=await j.from("appointments").select("*, pet:pets(name, breed), customer:customers(name), staff:staff(name)").eq("shop_id",t.id).eq("date",i).order("start_time");T&&n(T)},[t.id,i]);(0,je.useEffect)(()=>{S()},[S]),(0,je.useEffect)(()=>{j.from("pets").select("id, name, customer_id, breed").eq("shop_id",t.id).then(({data:T})=>{T&&a(T)}),j.from("customers").select("id, name").eq("shop_id",t.id).then(({data:T})=>{T&&u(T)}),j.from("staff").select("id, name").eq("shop_id",t.id).eq("is_active",!0).then(({data:T})=>{T&&d(T)}),j.from("services").select("id, name, base_price").eq("shop_id",t.id).eq("is_active",!0).then(({data:T})=>{T&&m(T)})},[t.id]);let P=()=>{v({date:i,start_time:"10:00",end_time:"",status:"\u4E88\u7D04\u6E08",pet_id:"",customer_id:"",staff_id:e.id,services:[],notes:"",total_amount:0}),f(null),g(!0)},H=T=>{v({...T}),f(T.id),g(!0)},x=async()=>{if(!y.pet_id||!y.start_time){w("\u26A0\uFE0F \u30DA\u30C3\u30C8\u3068\u958B\u59CB\u6642\u9593\u306F\u5FC5\u9808\u3067\u3059");return}let T={shop_id:t.id,pet_id:y.pet_id,customer_id:y.customer_id,staff_id:y.staff_id||null,date:y.date,start_time:y.start_time,end_time:y.end_time||null,status:y.status,services:y.services||[],total_amount:y.total_amount||0,notes:y.notes||""};b?(await j.from("appointments").update(T).eq("id",b),w("\u2705 \u66F4\u65B0\u3057\u307E\u3057\u305F")):(await j.from("appointments").insert(T),w("\u2705 \u4E88\u7D04\u3092\u767B\u9332\u3057\u307E\u3057\u305F")),g(!1),S()},X=async T=>{await j.from("appointments").delete().eq("id",T),w("\u{1F5D1} \u524A\u9664\u3057\u307E\u3057\u305F"),g(!1),S()},ar=T=>{let ce=o.find(_s=>_s.id===T);v(_s=>({..._s,pet_id:T,customer_id:ce?.customer_id||_s.customer_id}))};return(0,$.jsxs)("div",{style:{padding:16},children:[(0,$.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[(0,$.jsx)("h2",{style:{color:z,fontSize:20,fontWeight:700},children:"\u{1F4C5} \u4E88\u7D04\u7BA1\u7406"}),(0,$.jsx)("button",{onClick:P,style:{height:I,padding:"0 16px",background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer"},children:"+ \u65B0\u898F"})]}),(0,$.jsx)("input",{type:"date",value:i,onChange:T=>s(T.target.value),style:{width:"100%",height:I,padding:"0 12px",marginBottom:12,border:`1px solid ${C}`,borderRadius:8,fontSize:15}}),r.length===0?(0,$.jsx)("div",{style:{background:R,borderRadius:12,padding:32,textAlign:"center",color:O,border:`1px solid ${C}`},children:"\u3053\u306E\u65E5\u306E\u4E88\u7D04\u306F\u3042\u308A\u307E\u305B\u3093"}):(0,$.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:r.map(T=>(0,$.jsxs)("div",{onClick:()=>H(T),style:{background:R,borderRadius:10,padding:12,border:`1px solid ${C}`,cursor:"pointer",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,$.jsxs)("div",{children:[(0,$.jsxs)("div",{style:{fontWeight:600,fontSize:15},children:[T.start_time?.slice(0,5)," ",T.pet?.name||"\u2500",(0,$.jsx)("span",{style:{fontSize:12,color:O,marginLeft:6},children:T.pet?.breed})]}),(0,$.jsxs)("div",{style:{fontSize:12,color:O},children:[T.customer?.name||"\u2500"," \uFF0F \u62C5\u5F53: ",T.staff?.name||"\u2500",T.total_amount?` \uFF0F \xA5${T.total_amount.toLocaleString()}`:""]})]}),(0,$.jsx)("span",{style:{padding:"3px 8px",borderRadius:20,fontSize:11,fontWeight:600,background:Ar[T.status]||"#ccc",color:R},children:T.status})]},T.id))}),h&&(0,$.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:()=>g(!1),children:(0,$.jsxs)("div",{onClick:T=>T.stopPropagation(),style:{background:R,borderRadius:16,padding:20,width:ht,maxWidth:ft,maxHeight:"85vh",overflowY:"auto"},children:[(0,$.jsx)("h3",{style:{color:z,marginBottom:12},children:b?"\u4E88\u7D04\u7DE8\u96C6":"\u65B0\u898F\u4E88\u7D04"}),(0,$.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,$.jsx)("span",{style:{fontSize:13,color:O},children:"\u30DA\u30C3\u30C8 *"}),(0,$.jsxs)("select",{value:y.pet_id||"",onChange:T=>ar(T.target.value),style:{width:"100%",height:I,border:`1px solid ${C}`,borderRadius:8,fontSize:15},children:[(0,$.jsx)("option",{value:"",children:"\u9078\u629E"}),o.map(T=>(0,$.jsxs)("option",{value:T.id,children:[T.name," (",T.breed,")"]},T.id))]})]}),(0,$.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,$.jsx)("span",{style:{fontSize:13,color:O},children:"\u98FC\u3044\u4E3B"}),(0,$.jsxs)("select",{value:y.customer_id||"",onChange:T=>v(ce=>({...ce,customer_id:T.target.value})),style:{width:"100%",height:I,border:`1px solid ${C}`,borderRadius:8,fontSize:15},children:[(0,$.jsx)("option",{value:"",children:"\u9078\u629E"}),l.map(T=>(0,$.jsx)("option",{value:T.id,children:T.name},T.id))]})]}),(0,$.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,$.jsx)("span",{style:{fontSize:13,color:O},children:"\u62C5\u5F53\u30B9\u30BF\u30C3\u30D5"}),(0,$.jsxs)("select",{value:y.staff_id||"",onChange:T=>v(ce=>({...ce,staff_id:T.target.value})),style:{width:"100%",height:I,border:`1px solid ${C}`,borderRadius:8,fontSize:15},children:[(0,$.jsx)("option",{value:"",children:"\u672A\u5B9A"}),c.map(T=>(0,$.jsx)("option",{value:T.id,children:T.name},T.id))]})]}),(0,$.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:10},children:[(0,$.jsxs)("label",{children:[(0,$.jsx)("span",{style:{fontSize:13,color:O},children:"\u65E5\u4ED8"}),(0,$.jsx)("input",{type:"date",value:y.date||"",onChange:T=>v(ce=>({...ce,date:T.target.value})),style:{width:"100%",height:I,padding:"0 8px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]}),(0,$.jsxs)("label",{children:[(0,$.jsx)("span",{style:{fontSize:13,color:O},children:"\u958B\u59CB *"}),(0,$.jsx)("input",{type:"time",value:y.start_time||"",onChange:T=>v(ce=>({...ce,start_time:T.target.value})),style:{width:"100%",height:I,padding:"0 8px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]})]}),b&&(0,$.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,$.jsx)("span",{style:{fontSize:13,color:O},children:"\u30B9\u30C6\u30FC\u30BF\u30B9"}),(0,$.jsx)("select",{value:y.status||"\u4E88\u7D04\u6E08",onChange:T=>v(ce=>({...ce,status:T.target.value})),style:{width:"100%",height:I,border:`1px solid ${C}`,borderRadius:8,fontSize:15},children:np.map(T=>(0,$.jsx)("option",{value:T,children:T},T))})]}),(0,$.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,$.jsx)("span",{style:{fontSize:13,color:O},children:"\u30E1\u30E2"}),(0,$.jsx)("textarea",{value:y.notes||"",onChange:T=>v(ce=>({...ce,notes:T.target.value})),rows:2,style:{width:"100%",padding:10,border:`1px solid ${C}`,borderRadius:8,fontSize:15,resize:"vertical"}})]}),(0,$.jsx)("button",{onClick:x,style:{width:"100%",height:I,background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer",marginBottom:8},children:b?"\u66F4\u65B0":"\u767B\u9332"}),b&&(0,$.jsx)("button",{onClick:()=>X(b),style:{width:"100%",height:I,background:dt,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer",marginBottom:8},children:"\u524A\u9664"}),(0,$.jsx)("button",{onClick:()=>g(!1),style:{width:"100%",height:I,background:"#eee",color:me,border:"none",borderRadius:8,cursor:"pointer"},children:"\u30AD\u30E3\u30F3\u30BB\u30EB"})]})}),_&&(0,$.jsx)("div",{style:{position:"fixed",bottom:80,left:"50%",transform:"translateX(-50%)",background:"#333",color:R,padding:"10px 24px",borderRadius:20,fontSize:14,fontWeight:600,zIndex:9999},children:_})]})};var on=q($e());var Ke=q(ie()),Og=({shop:t})=>{let[e,r]=(0,on.useState)([]),[n,i]=(0,on.useState)(null),s=new Date().toISOString().slice(0,10),o=(0,on.useCallback)(async()=>{let{data:u}=await j.from("appointments").select("*, pet:pets(name, breed, photo_url), customer:customers(name, phone), staff:staff(name)").eq("shop_id",t.id).eq("date",s).not("status","in",'("\u30AD\u30E3\u30F3\u30BB\u30EB","\u30CE\u30FC\u30B7\u30E7\u30FC","\u5F15\u6E21\u6E08")').order("start_time");u&&r(u)},[t.id,s]);(0,on.useEffect)(()=>{o();let u=setInterval(o,15e3);return()=>clearInterval(u)},[o]);let a=async(u,c)=>{i(u),await j.from("appointments").update({status:c}).eq("id",u),await o(),i(null)},l=u=>{let c=["\u4E88\u7D04\u6E08","\u6765\u5E97","\u65BD\u8853\u4E2D","\u30B7\u30E3\u30F3\u30D7\u30FC\u4E2D","\u30AB\u30C3\u30C8\u4E2D","\u30C9\u30E9\u30A4\u4E2D","\u4ED5\u4E0A\u3052\u4E2D","\u5B8C\u4E86","\u304A\u8FCE\u3048\u5F85\u3061","\u5F15\u6E21\u6E08"],d=c.indexOf(u);return d>=0&&d{let c=l(u.status),d=n===u.id;return(0,Ke.jsxs)("div",{style:{background:R,borderRadius:12,padding:14,border:`2px solid ${Ar[u.status]||"#ccc"}`,opacity:d?.6:1},children:[(0,Ke.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8},children:[(0,Ke.jsxs)("div",{children:[(0,Ke.jsx)("span",{style:{fontWeight:700,fontSize:16},children:u.pet?.name||"\u2500"}),(0,Ke.jsxs)("span",{style:{fontSize:12,color:O,marginLeft:6},children:[u.pet?.breed," \uFF0F ",u.customer?.name]})]}),(0,Ke.jsx)("span",{style:{padding:"4px 10px",borderRadius:20,fontSize:12,fontWeight:700,background:Ar[u.status]||"#ccc",color:R},children:u.status})]}),(0,Ke.jsxs)("div",{style:{fontSize:13,color:O,marginBottom:10},children:["\u23F0 ",u.start_time?.slice(0,5),u.end_time?`\u301C${u.end_time.slice(0,5)}`:"","\u{1F464} ",u.staff?.name||"\u672A\u5B9A"]}),c&&(0,Ke.jsxs)("button",{onClick:()=>a(u.id,c),disabled:d,style:{width:"100%",height:I,background:Ar[c]||J,color:R,border:"none",borderRadius:8,fontWeight:600,fontSize:14,cursor:"pointer"},children:["\u25B6 ",c," \u306B\u3059\u308B"]})]},u.id)})})]})};var Rt=q($e());var B=q(ie()),Pg=({shop:t,staff:e})=>{let[r,n]=(0,Rt.useState)([]),[i,s]=(0,Rt.useState)([]),[o,a]=(0,Rt.useState)([]),[l,u]=(0,Rt.useState)(""),[c,d]=(0,Rt.useState)("\u73FE\u91D1"),[p,m]=(0,Rt.useState)(0),[y,v]=(0,Rt.useState)(!1),[b,f]=(0,Rt.useState)(""),h=x=>{f(x),setTimeout(()=>f(""),Ne)};(0,Rt.useEffect)(()=>{j.from("services").select("*").eq("shop_id",t.id).eq("is_active",!0).order("sort_order").then(({data:x})=>{x&&n(x)}),j.from("customers").select("id, name").eq("shop_id",t.id).order("name").then(({data:x})=>{x&&a(x)})},[t.id]);let g=x=>{s(X=>X.find(T=>T.service_id===x.id)?X.map(T=>T.service_id===x.id?{...T,qty:T.qty+1}:T):[...X,{service_id:x.id,name:x.name,price:x.base_price,qty:1}])},_=(x,X)=>{s(ar=>ar.map(T=>T.service_id===x?{...T,qty:Math.max(0,T.qty+X)}:T).filter(T=>T.qty>0))},k=i.reduce((x,X)=>x+X.price*X.qty,0),w=Math.floor((k-p)*(t.tax_rate/100)),S=k-p+w,P=async()=>{if(i.length===0){h("\u26A0\uFE0F \u30AB\u30FC\u30C8\u304C\u7A7A\u3067\u3059");return}let x=`R${Date.now().toString().slice(-8)}`,{data:X,error:ar}=await j.from("transactions").insert({shop_id:t.id,customer_id:l||null,staff_id:e.id,subtotal:k,tax:w,discount:p,total:S,payment_method:c,status:"\u5B8C\u4E86",receipt_number:x}).select().single();if(ar||!X){h("\u274C \u4F1A\u8A08\u306B\u5931\u6557\u3057\u307E\u3057\u305F");return}let T=i.map(ce=>({transaction_id:X.id,service_id:ce.service_id,name:ce.name,quantity:ce.qty,unit_price:ce.price,subtotal:ce.price*ce.qty}));await j.from("transaction_items").insert(T),l&&(await j.rpc("",{}).catch(()=>{}),await j.from("customers").update({visit_count:o.find(ce=>ce.id===l)?.visit_count+1||1,last_visit_date:new Date().toISOString().slice(0,10)}).eq("id",l).catch(()=>{})),h(`\u2705 \u4F1A\u8A08\u5B8C\u4E86 \xA5${S.toLocaleString()} (${x})`),s([]),m(0),v(!1)},H=[...new Set(r.map(x=>x.category))];return(0,B.jsxs)("div",{style:{padding:16,paddingBottom:160},children:[(0,B.jsx)("h2",{style:{color:z,fontSize:20,fontWeight:700,marginBottom:12},children:"\u{1F4B0} \u30EC\u30B8"}),(0,B.jsxs)("select",{value:l,onChange:x=>u(x.target.value),style:{width:"100%",height:I,marginBottom:12,border:`1px solid ${C}`,borderRadius:8,fontSize:15,padding:"0 10px"},children:[(0,B.jsx)("option",{value:"",children:"\u9867\u5BA2\u3092\u9078\u629E\uFF08\u4EFB\u610F\uFF09"}),o.map(x=>(0,B.jsx)("option",{value:x.id,children:x.name},x.id))]}),H.map(x=>(0,B.jsxs)("div",{style:{marginBottom:16},children:[(0,B.jsxs)("h4",{style:{color:z,fontSize:14,marginBottom:6},children:[qi[x]||"\u{1F4E6}"," ",x]}),(0,B.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(2,1fr)",gap:8},children:r.filter(X=>X.category===x).map(X=>(0,B.jsxs)("button",{onClick:()=>g(X),style:{background:R,border:`1px solid ${C}`,borderRadius:10,padding:10,cursor:"pointer",textAlign:"left"},children:[(0,B.jsx)("div",{style:{fontWeight:600,fontSize:14},children:X.name}),(0,B.jsxs)("div",{style:{color:z,fontWeight:700,fontSize:15},children:["\xA5",X.base_price.toLocaleString()]})]},X.id))})]},x)),r.length===0&&(0,B.jsx)("div",{style:{background:R,borderRadius:12,padding:32,textAlign:"center",color:O,border:`1px solid ${C}`},children:"\u30E1\u30CB\u30E5\u30FC\u304C\u767B\u9332\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u5148\u306B\u300C\u30E1\u30CB\u30E5\u30FC\u300D\u304B\u3089\u8FFD\u52A0\u3057\u3066\u304F\u3060\u3055\u3044\u3002"}),i.length>0&&(0,B.jsxs)("div",{style:{position:"fixed",bottom:68,left:0,right:0,background:R,borderTop:`2px solid ${J}`,padding:"12px 16px",zIndex:100,boxShadow:"0 -2px 10px rgba(0,0,0,.1)"},children:[i.map(x=>(0,B.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4,fontSize:14},children:[(0,B.jsx)("span",{children:x.name}),(0,B.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,B.jsx)("button",{onClick:()=>_(x.service_id,-1),style:{width:28,height:28,borderRadius:"50%",border:`1px solid ${C}`,background:R,cursor:"pointer"},children:"\u2212"}),(0,B.jsx)("span",{style:{fontWeight:600},children:x.qty}),(0,B.jsx)("button",{onClick:()=>_(x.service_id,1),style:{width:28,height:28,borderRadius:"50%",border:`1px solid ${C}`,background:R,cursor:"pointer"},children:"+"}),(0,B.jsxs)("span",{style:{fontWeight:600,width:70,textAlign:"right"},children:["\xA5",(x.price*x.qty).toLocaleString()]})]})]},x.service_id)),(0,B.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",borderTop:`1px solid ${C}`,paddingTop:8,marginTop:8},children:[(0,B.jsxs)("span",{style:{fontWeight:700,fontSize:18},children:["\u5408\u8A08 \xA5",S.toLocaleString()]}),(0,B.jsx)("button",{onClick:()=>v(!0),style:{height:I,padding:"0 24px",background:Mu,color:R,border:"none",borderRadius:8,fontWeight:700,fontSize:16,cursor:"pointer"},children:"\u4F1A\u8A08"})]})]}),y&&(0,B.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:()=>v(!1),children:(0,B.jsxs)("div",{onClick:x=>x.stopPropagation(),style:{background:R,borderRadius:16,padding:24,width:"90vw",maxWidth:400},children:[(0,B.jsx)("h3",{style:{color:z,marginBottom:16,textAlign:"center"},children:"\u{1F4B3} \u304A\u652F\u6255\u3044"}),(0,B.jsxs)("div",{style:{textAlign:"center",marginBottom:16},children:[(0,B.jsx)("div",{style:{fontSize:14,color:O},children:"\u304A\u4F1A\u8A08\u91D1\u984D"}),(0,B.jsxs)("div",{style:{fontSize:32,fontWeight:700,color:z},children:["\xA5",S.toLocaleString()]}),(0,B.jsxs)("div",{style:{fontSize:12,color:O},children:["\uFF08\u7A0E \xA5",w.toLocaleString()," \u8FBC\u307F\uFF09"]})]}),(0,B.jsxs)("label",{style:{display:"block",marginBottom:12},children:[(0,B.jsx)("span",{style:{fontSize:13,color:O},children:"\u5024\u5F15\u304D"}),(0,B.jsx)("input",{type:"number",value:p||"",onChange:x=>m(parseInt(x.target.value)||0),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]}),(0,B.jsxs)("div",{style:{marginBottom:16},children:[(0,B.jsx)("span",{style:{fontSize:13,color:O},children:"\u652F\u6255\u3044\u65B9\u6CD5"}),(0,B.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:8,marginTop:6},children:ip.map(x=>(0,B.jsxs)("button",{onClick:()=>d(x),style:{padding:"8px 4px",borderRadius:8,fontSize:12,fontWeight:600,border:c===x?`2px solid ${J}`:`1px solid ${C}`,background:c===x?rr:R,cursor:"pointer"},children:[sp[x]," ",x]},x))})]}),(0,B.jsx)("button",{onClick:P,style:{width:"100%",height:52,background:Mu,color:R,border:"none",borderRadius:10,fontWeight:700,fontSize:18,cursor:"pointer",marginBottom:8},children:"\u2705 \u6C7A\u6E08\u5B8C\u4E86"}),(0,B.jsx)("button",{onClick:()=>v(!1),style:{width:"100%",height:I,background:"#eee",color:me,border:"none",borderRadius:8,cursor:"pointer"},children:"\u30AD\u30E3\u30F3\u30BB\u30EB"})]})}),b&&(0,B.jsx)("div",{style:{position:"fixed",bottom:80,left:"50%",transform:"translateX(-50%)",background:"#333",color:R,padding:"10px 24px",borderRadius:20,fontSize:14,fontWeight:600,zIndex:9999},children:b})]})};var Ct=q($e());var te=q(ie()),Ig={name:"",furigana:"",phone:"",email:"",address:"",line_id:"",notes:""},Ng=({shop:t})=>{let[e,r]=(0,Ct.useState)([]),[n,i]=(0,Ct.useState)(""),[s,o]=(0,Ct.useState)(Ig),[a,l]=(0,Ct.useState)(null),[u,c]=(0,Ct.useState)(!1),[d,p]=(0,Ct.useState)(""),m=k=>{p(k),setTimeout(()=>p(""),Ne)},y=(0,Ct.useCallback)(async()=>{let{data:k}=await j.from("customers").select("*").eq("shop_id",t.id).order("created_at",{ascending:!1});k&&r(k)},[t.id]);(0,Ct.useEffect)(()=>{y()},[y]);let v=e.filter(k=>!n||k.name.includes(n)||k.furigana?.includes(n)||k.phone?.includes(n)),b=()=>{o(Ig),l(null),c(!0)},f=k=>{o({...k}),l(k.id),c(!0)},h=async()=>{if(!s.name?.trim()){m("\u26A0\uFE0F \u540D\u524D\u306F\u5FC5\u9808\u3067\u3059");return}a?(await j.from("customers").update({...s,updated_at:new Date().toISOString()}).eq("id",a),m("\u2705 \u66F4\u65B0\u3057\u307E\u3057\u305F")):(await j.from("customers").insert({...s,shop_id:t.id}),m("\u2705 \u767B\u9332\u3057\u307E\u3057\u305F")),c(!1),y()},g=async k=>{await j.from("customers").delete().eq("id",k),m("\u{1F5D1} \u524A\u9664\u3057\u307E\u3057\u305F"),c(!1),y()},_=(k,w,S="text")=>(0,te.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,te.jsx)("span",{style:{fontSize:13,color:O},children:k}),(0,te.jsx)("input",{type:S,value:s[w]||"",onChange:P=>o(H=>({...H,[w]:P.target.value})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]},w);return(0,te.jsxs)("div",{style:{padding:16},children:[(0,te.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[(0,te.jsx)("h2",{style:{color:z,fontSize:20,fontWeight:700},children:"\u{1F464} \u9867\u5BA2\u7BA1\u7406"}),(0,te.jsx)("button",{onClick:b,style:{height:I,padding:"0 16px",background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer"},children:"+ \u65B0\u898F"})]}),(0,te.jsx)("input",{placeholder:"\u{1F50D} \u540D\u524D\u30FB\u3075\u308A\u304C\u306A\u30FB\u96FB\u8A71\u756A\u53F7\u3067\u691C\u7D22",value:n,onChange:k=>i(k.target.value),style:{width:"100%",height:I,padding:"0 12px",marginBottom:12,border:`1px solid ${C}`,borderRadius:8,fontSize:15}}),v.length===0?(0,te.jsx)("div",{style:{background:R,borderRadius:12,padding:32,textAlign:"center",color:O,border:`1px solid ${C}`},children:"\u9867\u5BA2\u30C7\u30FC\u30BF\u304C\u3042\u308A\u307E\u305B\u3093"}):(0,te.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:v.map(k=>(0,te.jsxs)("div",{onClick:()=>f(k),style:{background:R,borderRadius:10,padding:12,border:`1px solid ${C}`,cursor:"pointer"},children:[(0,te.jsxs)("div",{style:{fontWeight:600,fontSize:15},children:[k.name,(0,te.jsx)("span",{style:{fontSize:12,color:O,marginLeft:8},children:k.furigana})]}),(0,te.jsxs)("div",{style:{fontSize:12,color:O},children:["\u{1F4DE} ",k.phone||"\u2500"," \uFF0F \u6765\u5E97 ",k.visit_count,"\u56DE \uFF0F \u6700\u7D42 ",k.last_visit_date||"\u2500"]})]},k.id))}),u&&(0,te.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:()=>c(!1),children:(0,te.jsxs)("div",{onClick:k=>k.stopPropagation(),style:{background:R,borderRadius:16,padding:20,width:ht,maxWidth:ft,maxHeight:"85vh",overflowY:"auto"},children:[(0,te.jsx)("h3",{style:{color:z,marginBottom:12},children:a?"\u9867\u5BA2\u7DE8\u96C6":"\u9867\u5BA2\u767B\u9332"}),_("\u540D\u524D *","name"),_("\u3075\u308A\u304C\u306A","furigana"),_("\u96FB\u8A71\u756A\u53F7","phone","tel"),_("\u30E1\u30FC\u30EB","email","email"),_("\u4F4F\u6240","address"),_("LINE ID","line_id"),(0,te.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,te.jsx)("span",{style:{fontSize:13,color:O},children:"\u30E1\u30E2"}),(0,te.jsx)("textarea",{value:s.notes||"",onChange:k=>o(w=>({...w,notes:k.target.value})),rows:3,style:{width:"100%",padding:10,border:`1px solid ${C}`,borderRadius:8,fontSize:15,resize:"vertical"}})]}),(0,te.jsx)("button",{onClick:h,style:{width:"100%",height:I,background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer",marginBottom:8},children:a?"\u66F4\u65B0":"\u767B\u9332"}),a&&(0,te.jsx)("button",{onClick:()=>g(a),style:{width:"100%",height:I,background:dt,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer",marginBottom:8},children:"\u524A\u9664"}),(0,te.jsx)("button",{onClick:()=>c(!1),style:{width:"100%",height:I,background:"#eee",color:me,border:"none",borderRadius:8,cursor:"pointer"},children:"\u30AD\u30E3\u30F3\u30BB\u30EB"})]})}),d&&(0,te.jsx)("div",{style:{position:"fixed",bottom:80,left:"50%",transform:"translateX(-50%)",background:"#333",color:R,padding:"10px 24px",borderRadius:20,fontSize:14,fontWeight:600,zIndex:9999},children:d})]})};var yt=q($e());var U=q(ie()),Lg={name:"",breed:"\u30C8\u30A4\u30D7\u30FC\u30C9\u30EB",birth_date:"",gender:"\u30AA\u30B9",weight:void 0,color:"",allergies:"",temperament:"",notes:""},jg=({shop:t})=>{let[e,r]=(0,yt.useState)([]),[n,i]=(0,yt.useState)([]),[s,o]=(0,yt.useState)(""),[a,l]=(0,yt.useState)({...Lg}),[u,c]=(0,yt.useState)(null),[d,p]=(0,yt.useState)(!1),[m,y]=(0,yt.useState)(""),v=w=>{y(w),setTimeout(()=>y(""),Ne)},b=(0,yt.useCallback)(async()=>{let{data:w}=await j.from("pets").select("*, customer:customers(name)").eq("shop_id",t.id).order("created_at",{ascending:!1});w&&r(w);let{data:S}=await j.from("customers").select("id, name").eq("shop_id",t.id).order("name");S&&i(S)},[t.id]);(0,yt.useEffect)(()=>{b()},[b]);let f=e.filter(w=>!s||w.name.includes(s)||w.breed.includes(s)||w.customer?.name?.includes(s)),h=()=>{l({...Lg,customer_id:n[0]?.id||""}),c(null),p(!0)},g=w=>{l({...w}),c(w.id),p(!0)},_=async()=>{if(!a.name?.trim()||!a.breed){v("\u26A0\uFE0F \u540D\u524D\u3068\u72AC\u7A2E\u306F\u5FC5\u9808\u3067\u3059");return}if(!a.customer_id){v("\u26A0\uFE0F \u98FC\u3044\u4E3B\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044");return}let w={...a,shop_id:t.id};delete w.customer,delete w.id,delete w.created_at,delete w.updated_at,u?(await j.from("pets").update(w).eq("id",u),v("\u2705 \u66F4\u65B0\u3057\u307E\u3057\u305F")):(await j.from("pets").insert(w),v("\u2705 \u767B\u9332\u3057\u307E\u3057\u305F")),p(!1),b()},k=async w=>{await j.from("pets").delete().eq("id",w),v("\u{1F5D1} \u524A\u9664\u3057\u307E\u3057\u305F"),p(!1),b()};return(0,U.jsxs)("div",{style:{padding:16},children:[(0,U.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[(0,U.jsx)("h2",{style:{color:z,fontSize:20,fontWeight:700},children:"\u{1F415} \u30DA\u30C3\u30C8\u7BA1\u7406"}),(0,U.jsx)("button",{onClick:h,style:{height:I,padding:"0 16px",background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer"},children:"+ \u65B0\u898F"})]}),(0,U.jsx)("input",{placeholder:"\u{1F50D} \u540D\u524D\u30FB\u72AC\u7A2E\u30FB\u98FC\u3044\u4E3B\u3067\u691C\u7D22",value:s,onChange:w=>o(w.target.value),style:{width:"100%",height:I,padding:"0 12px",marginBottom:12,border:`1px solid ${C}`,borderRadius:8,fontSize:15}}),f.length===0?(0,U.jsx)("div",{style:{background:R,borderRadius:12,padding:32,textAlign:"center",color:O,border:`1px solid ${C}`},children:"\u30DA\u30C3\u30C8\u30C7\u30FC\u30BF\u304C\u3042\u308A\u307E\u305B\u3093"}):(0,U.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:f.map(w=>(0,U.jsxs)("div",{onClick:()=>g(w),style:{background:R,borderRadius:10,padding:12,border:`1px solid ${C}`,cursor:"pointer",display:"flex",alignItems:"center",gap:10},children:[(0,U.jsx)("span",{style:{fontSize:28},children:"\u{1F415}"}),(0,U.jsxs)("div",{children:[(0,U.jsxs)("div",{style:{fontWeight:600,fontSize:15},children:[w.name,(0,U.jsxs)("span",{style:{fontSize:12,color:O,marginLeft:6},children:[w.breed," / ",w.gender]})]}),(0,U.jsxs)("div",{style:{fontSize:12,color:O},children:["\u98FC\u3044\u4E3B: ",w.customer?.name||"\u2500"," \uFF0F ",w.weight?`${w.weight}kg`:"\u4F53\u91CD\u672A\u8A2D\u5B9A"]})]})]},w.id))}),d&&(0,U.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:()=>p(!1),children:(0,U.jsxs)("div",{onClick:w=>w.stopPropagation(),style:{background:R,borderRadius:16,padding:20,width:ht,maxWidth:ft,maxHeight:"85vh",overflowY:"auto"},children:[(0,U.jsx)("h3",{style:{color:z,marginBottom:12},children:u?"\u30DA\u30C3\u30C8\u7DE8\u96C6":"\u30DA\u30C3\u30C8\u767B\u9332"}),(0,U.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,U.jsx)("span",{style:{fontSize:13,color:O},children:"\u98FC\u3044\u4E3B *"}),(0,U.jsxs)("select",{value:a.customer_id||"",onChange:w=>l(S=>({...S,customer_id:w.target.value})),style:{width:"100%",height:I,border:`1px solid ${C}`,borderRadius:8,fontSize:15},children:[(0,U.jsx)("option",{value:"",children:"\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044"}),n.map(w=>(0,U.jsx)("option",{value:w.id,children:w.name},w.id))]})]}),(0,U.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,U.jsx)("span",{style:{fontSize:13,color:O},children:"\u540D\u524D *"}),(0,U.jsx)("input",{value:a.name||"",onChange:w=>l(S=>({...S,name:w.target.value})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]}),(0,U.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,U.jsx)("span",{style:{fontSize:13,color:O},children:"\u72AC\u7A2E *"}),(0,U.jsx)("select",{value:a.breed||"",onChange:w=>l(S=>({...S,breed:w.target.value})),style:{width:"100%",height:I,border:`1px solid ${C}`,borderRadius:8,fontSize:15},children:ap.map(w=>(0,U.jsx)("option",{value:w,children:w},w))})]}),(0,U.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,U.jsx)("span",{style:{fontSize:13,color:O},children:"\u6027\u5225"}),(0,U.jsx)("select",{value:a.gender||"\u30AA\u30B9",onChange:w=>l(S=>({...S,gender:w.target.value})),style:{width:"100%",height:I,border:`1px solid ${C}`,borderRadius:8,fontSize:15},children:lp.map(w=>(0,U.jsx)("option",{value:w,children:w},w))})]}),(0,U.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,U.jsx)("span",{style:{fontSize:13,color:O},children:"\u8A95\u751F\u65E5"}),(0,U.jsx)("input",{type:"date",value:a.birth_date||"",onChange:w=>l(S=>({...S,birth_date:w.target.value})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]}),(0,U.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,U.jsx)("span",{style:{fontSize:13,color:O},children:"\u4F53\u91CD (kg)"}),(0,U.jsx)("input",{type:"number",step:"0.1",value:a.weight||"",onChange:w=>l(S=>({...S,weight:w.target.value?parseFloat(w.target.value):void 0})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]}),(0,U.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,U.jsx)("span",{style:{fontSize:13,color:O},children:"\u30A2\u30EC\u30EB\u30AE\u30FC"}),(0,U.jsx)("input",{value:a.allergies||"",onChange:w=>l(S=>({...S,allergies:w.target.value})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]}),(0,U.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,U.jsx)("span",{style:{fontSize:13,color:O},children:"\u30E1\u30E2"}),(0,U.jsx)("textarea",{value:a.notes||"",onChange:w=>l(S=>({...S,notes:w.target.value})),rows:3,style:{width:"100%",padding:10,border:`1px solid ${C}`,borderRadius:8,fontSize:15,resize:"vertical"}})]}),(0,U.jsx)("button",{onClick:_,style:{width:"100%",height:I,background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer",marginBottom:8},children:u?"\u66F4\u65B0":"\u767B\u9332"}),u&&(0,U.jsx)("button",{onClick:()=>k(u),style:{width:"100%",height:I,background:dt,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer",marginBottom:8},children:"\u524A\u9664"}),(0,U.jsx)("button",{onClick:()=>p(!1),style:{width:"100%",height:I,background:"#eee",color:me,border:"none",borderRadius:8,cursor:"pointer"},children:"\u30AD\u30E3\u30F3\u30BB\u30EB"})]})}),m&&(0,U.jsx)("div",{style:{position:"fixed",bottom:80,left:"50%",transform:"translateX(-50%)",background:"#333",color:R,padding:"10px 24px",borderRadius:20,fontSize:14,fontWeight:600,zIndex:9999},children:m})]})};var nt=q($e());var W=q(ie()),Dg=({shop:t})=>{let[e,r]=(0,nt.useState)([]),[n,i]=(0,nt.useState)(""),[s,o]=(0,nt.useState)({}),[a,l]=(0,nt.useState)(null),[u,c]=(0,nt.useState)(!1),[d,p]=(0,nt.useState)([]),[m,y]=(0,nt.useState)([]),[v,b]=(0,nt.useState)(""),f=S=>{b(S),setTimeout(()=>b(""),Ne)},h=(0,nt.useCallback)(async()=>{let{data:S}=await j.from("grooming_records").select("*, pet:pets(name, breed), staff:staff(name)").order("created_at",{ascending:!1}).limit(100);S&&r(S);let{data:P}=await j.from("pets").select("id, name, breed").eq("shop_id",t.id);P&&p(P);let{data:H}=await j.from("staff").select("id, name").eq("shop_id",t.id).eq("is_active",!0);H&&y(H)},[t.id]);(0,nt.useEffect)(()=>{h()},[h]);let g=e.filter(S=>!n||S.pet?.name?.includes(n)||S.cut_style?.includes(n)),_=()=>{o({pet_id:"",staff_id:"",cut_style:"",blade_length:"",shampoo_used:"",skin_condition:"",notes:"",next_recommended_date:""}),l(null),c(!0)},k=S=>{o({...S}),l(S.id),c(!0)},w=async()=>{if(!s.pet_id){f("\u26A0\uFE0F \u30DA\u30C3\u30C8\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044");return}let S={pet_id:s.pet_id,staff_id:s.staff_id||null,cut_style:s.cut_style||null,blade_length:s.blade_length||null,shampoo_used:s.shampoo_used||null,skin_condition:s.skin_condition||null,notes:s.notes||null,next_recommended_date:s.next_recommended_date||null};a?(await j.from("grooming_records").update(S).eq("id",a),f("\u2705 \u66F4\u65B0\u3057\u307E\u3057\u305F")):(await j.from("grooming_records").insert(S),f("\u2705 \u8A18\u9332\u3057\u307E\u3057\u305F")),c(!1),h()};return(0,W.jsxs)("div",{style:{padding:16},children:[(0,W.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[(0,W.jsx)("h2",{style:{color:z,fontSize:20,fontWeight:700},children:"\u{1F4F8} \u65BD\u8853\u30AB\u30EB\u30C6"}),(0,W.jsx)("button",{onClick:_,style:{height:I,padding:"0 16px",background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer"},children:"+ \u65B0\u898F"})]}),(0,W.jsx)("input",{placeholder:"\u{1F50D} \u30DA\u30C3\u30C8\u540D\u30FB\u30B9\u30BF\u30A4\u30EB\u3067\u691C\u7D22",value:n,onChange:S=>i(S.target.value),style:{width:"100%",height:I,padding:"0 12px",marginBottom:12,border:`1px solid ${C}`,borderRadius:8,fontSize:15}}),g.length===0?(0,W.jsx)("div",{style:{background:R,borderRadius:12,padding:32,textAlign:"center",color:O,border:`1px solid ${C}`},children:"\u65BD\u8853\u8A18\u9332\u304C\u3042\u308A\u307E\u305B\u3093"}):(0,W.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:g.map(S=>(0,W.jsxs)("div",{onClick:()=>k(S),style:{background:R,borderRadius:10,padding:12,border:`1px solid ${C}`,cursor:"pointer"},children:[(0,W.jsxs)("div",{style:{fontWeight:600,fontSize:15},children:["\u{1F415} ",S.pet?.name,(0,W.jsx)("span",{style:{fontSize:12,color:O,marginLeft:6},children:S.pet?.breed})]}),(0,W.jsxs)("div",{style:{fontSize:12,color:O},children:["\u2702\uFE0F ",S.cut_style||"\u2500"," \uFF0F \u{1F9F4} ",S.shampoo_used||"\u2500"," \uFF0F \u62C5\u5F53: ",S.staff?.name||"\u2500"]}),(0,W.jsxs)("div",{style:{fontSize:11,color:O},children:[new Date(S.created_at).toLocaleDateString("ja-JP"),S.next_recommended_date&&` \uFF0F \u6B21\u56DE\u63A8\u5968: ${S.next_recommended_date}`]})]},S.id))}),u&&(0,W.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:()=>c(!1),children:(0,W.jsxs)("div",{onClick:S=>S.stopPropagation(),style:{background:R,borderRadius:16,padding:20,width:ht,maxWidth:ft,maxHeight:"85vh",overflowY:"auto"},children:[(0,W.jsx)("h3",{style:{color:z,marginBottom:12},children:a?"\u30AB\u30EB\u30C6\u7DE8\u96C6":"\u65B0\u898F\u30AB\u30EB\u30C6"}),(0,W.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,W.jsx)("span",{style:{fontSize:13,color:O},children:"\u30DA\u30C3\u30C8 *"}),(0,W.jsxs)("select",{value:s.pet_id||"",onChange:S=>o(P=>({...P,pet_id:S.target.value})),style:{width:"100%",height:I,border:`1px solid ${C}`,borderRadius:8,fontSize:15},children:[(0,W.jsx)("option",{value:"",children:"\u9078\u629E"}),d.map(S=>(0,W.jsxs)("option",{value:S.id,children:[S.name," (",S.breed,")"]},S.id))]})]}),(0,W.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,W.jsx)("span",{style:{fontSize:13,color:O},children:"\u62C5\u5F53\u30B9\u30BF\u30C3\u30D5"}),(0,W.jsxs)("select",{value:s.staff_id||"",onChange:S=>o(P=>({...P,staff_id:S.target.value})),style:{width:"100%",height:I,border:`1px solid ${C}`,borderRadius:8,fontSize:15},children:[(0,W.jsx)("option",{value:"",children:"\u9078\u629E"}),m.map(S=>(0,W.jsx)("option",{value:S.id,children:S.name},S.id))]})]}),[["\u30AB\u30C3\u30C8\u30B9\u30BF\u30A4\u30EB","cut_style"],["\u30D0\u30EA\u30AB\u30F3\u306E\u9577\u3055","blade_length"],["\u4F7F\u7528\u30B7\u30E3\u30F3\u30D7\u30FC","shampoo_used"],["\u76AE\u819A\u306E\u72B6\u614B","skin_condition"]].map(([S,P])=>(0,W.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,W.jsx)("span",{style:{fontSize:13,color:O},children:S}),(0,W.jsx)("input",{value:s[P]||"",onChange:H=>o(x=>({...x,[P]:H.target.value})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]},P)),(0,W.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,W.jsx)("span",{style:{fontSize:13,color:O},children:"\u6B21\u56DE\u63A8\u5968\u65E5"}),(0,W.jsx)("input",{type:"date",value:s.next_recommended_date||"",onChange:S=>o(P=>({...P,next_recommended_date:S.target.value})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]}),(0,W.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,W.jsx)("span",{style:{fontSize:13,color:O},children:"\u30E1\u30E2"}),(0,W.jsx)("textarea",{value:s.notes||"",onChange:S=>o(P=>({...P,notes:S.target.value})),rows:2,style:{width:"100%",padding:10,border:`1px solid ${C}`,borderRadius:8,fontSize:15,resize:"vertical"}})]}),(0,W.jsx)("button",{onClick:w,style:{width:"100%",height:I,background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer",marginBottom:8},children:a?"\u66F4\u65B0":"\u8A18\u9332"}),(0,W.jsx)("button",{onClick:()=>c(!1),style:{width:"100%",height:I,background:"#eee",color:me,border:"none",borderRadius:8,cursor:"pointer"},children:"\u30AD\u30E3\u30F3\u30BB\u30EB"})]})}),v&&(0,W.jsx)("div",{style:{position:"fixed",bottom:80,left:"50%",transform:"translateX(-50%)",background:"#333",color:R,padding:"10px 24px",borderRadius:20,fontSize:14,fontWeight:600,zIndex:9999},children:v})]})};var Ht=q($e());var M=q(ie()),$g={name:"",category:"\u30C8\u30EA\u30DF\u30F3\u30B0",base_price:0,duration_min:60,description:"",is_active:!0,sort_order:0},Ug=({shop:t,isOwner:e})=>{let[r,n]=(0,Ht.useState)([]),[i,s]=(0,Ht.useState)({...$g}),[o,a]=(0,Ht.useState)(null),[l,u]=(0,Ht.useState)(!1),[c,d]=(0,Ht.useState)(""),p=g=>{d(g),setTimeout(()=>d(""),Ne)},m=(0,Ht.useCallback)(async()=>{let{data:g}=await j.from("services").select("*").eq("shop_id",t.id).order("sort_order");g&&n(g)},[t.id]);(0,Ht.useEffect)(()=>{m()},[m]);let y=()=>{s({...$g}),a(null),u(!0)},v=g=>{s({...g}),a(g.id),u(!0)},b=async()=>{if(!i.name?.trim()){p("\u26A0\uFE0F \u30E1\u30CB\u30E5\u30FC\u540D\u306F\u5FC5\u9808\u3067\u3059");return}if(!i.base_price){p("\u26A0\uFE0F \u4FA1\u683C\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044");return}let g={shop_id:t.id,name:i.name,category:i.category,base_price:parseInt(i.base_price),duration_min:parseInt(i.duration_min)||60,description:i.description||"",is_active:i.is_active,sort_order:parseInt(i.sort_order)||0};o?(await j.from("services").update(g).eq("id",o),p("\u2705 \u66F4\u65B0\u3057\u307E\u3057\u305F")):(await j.from("services").insert(g),p("\u2705 \u767B\u9332\u3057\u307E\u3057\u305F")),u(!1),m()},f=async g=>{await j.from("services").delete().eq("id",g),p("\u{1F5D1} \u524A\u9664\u3057\u307E\u3057\u305F"),u(!1),m()},h=[...new Set(r.map(g=>g.category))];return(0,M.jsxs)("div",{style:{padding:16},children:[(0,M.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[(0,M.jsx)("h2",{style:{color:z,fontSize:20,fontWeight:700},children:"\u2702\uFE0F \u30E1\u30CB\u30E5\u30FC\u7BA1\u7406"}),e&&(0,M.jsx)("button",{onClick:y,style:{height:I,padding:"0 16px",background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer"},children:"+ \u65B0\u898F"})]}),r.length===0?(0,M.jsx)("div",{style:{background:R,borderRadius:12,padding:32,textAlign:"center",color:O,border:`1px solid ${C}`},children:"\u30E1\u30CB\u30E5\u30FC\u304C\u767B\u9332\u3055\u308C\u3066\u3044\u307E\u305B\u3093"}):h.map(g=>(0,M.jsxs)("div",{style:{marginBottom:16},children:[(0,M.jsxs)("h4",{style:{color:z,fontSize:14,marginBottom:6},children:[qi[g]||"\u{1F4E6}"," ",g]}),(0,M.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:r.filter(_=>_.category===g).map(_=>(0,M.jsxs)("div",{onClick:()=>e&&v(_),style:{background:R,borderRadius:10,padding:12,border:`1px solid ${C}`,cursor:e?"pointer":"default",display:"flex",justifyContent:"space-between",alignItems:"center",opacity:_.is_active?1:.5},children:[(0,M.jsxs)("div",{children:[(0,M.jsx)("div",{style:{fontWeight:600,fontSize:15},children:_.name}),(0,M.jsxs)("div",{style:{fontSize:12,color:O},children:["\u23F1 ",_.duration_min,"\u5206 ",!_.is_active&&"\uFF08\u975E\u516C\u958B\uFF09"]})]}),(0,M.jsxs)("div",{style:{fontWeight:700,color:z,fontSize:16},children:["\xA5",_.base_price.toLocaleString()]})]},_.id))})]},g)),l&&(0,M.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:()=>u(!1),children:(0,M.jsxs)("div",{onClick:g=>g.stopPropagation(),style:{background:R,borderRadius:16,padding:20,width:ht,maxWidth:ft,maxHeight:"85vh",overflowY:"auto"},children:[(0,M.jsx)("h3",{style:{color:z,marginBottom:12},children:o?"\u30E1\u30CB\u30E5\u30FC\u7DE8\u96C6":"\u30E1\u30CB\u30E5\u30FC\u8FFD\u52A0"}),(0,M.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,M.jsx)("span",{style:{fontSize:13,color:O},children:"\u30E1\u30CB\u30E5\u30FC\u540D *"}),(0,M.jsx)("input",{value:i.name||"",onChange:g=>s(_=>({..._,name:g.target.value})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]}),(0,M.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,M.jsx)("span",{style:{fontSize:13,color:O},children:"\u30AB\u30C6\u30B4\u30EA"}),(0,M.jsx)("select",{value:i.category||"\u30C8\u30EA\u30DF\u30F3\u30B0",onChange:g=>s(_=>({..._,category:g.target.value})),style:{width:"100%",height:I,border:`1px solid ${C}`,borderRadius:8,fontSize:15},children:op.map(g=>(0,M.jsxs)("option",{value:g,children:[qi[g]," ",g]},g))})]}),(0,M.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:10},children:[(0,M.jsxs)("label",{children:[(0,M.jsx)("span",{style:{fontSize:13,color:O},children:"\u4FA1\u683C (\u5186) *"}),(0,M.jsx)("input",{type:"number",value:i.base_price||"",onChange:g=>s(_=>({..._,base_price:g.target.value})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]}),(0,M.jsxs)("label",{children:[(0,M.jsx)("span",{style:{fontSize:13,color:O},children:"\u6240\u8981\u6642\u9593 (\u5206)"}),(0,M.jsx)("input",{type:"number",value:i.duration_min||"",onChange:g=>s(_=>({..._,duration_min:g.target.value})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]})]}),(0,M.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,M.jsx)("span",{style:{fontSize:13,color:O},children:"\u8AAC\u660E"}),(0,M.jsx)("textarea",{value:i.description||"",onChange:g=>s(_=>({..._,description:g.target.value})),rows:2,style:{width:"100%",padding:10,border:`1px solid ${C}`,borderRadius:8,fontSize:15,resize:"vertical"}})]}),(0,M.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:14},children:[(0,M.jsx)("input",{type:"checkbox",checked:i.is_active??!0,onChange:g=>s(_=>({..._,is_active:g.target.checked}))}),(0,M.jsx)("span",{style:{fontSize:14},children:"\u516C\u958B\u3059\u308B"})]}),(0,M.jsx)("button",{onClick:b,style:{width:"100%",height:I,background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer",marginBottom:8},children:o?"\u66F4\u65B0":"\u767B\u9332"}),o&&(0,M.jsx)("button",{onClick:()=>f(o),style:{width:"100%",height:I,background:dt,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer",marginBottom:8},children:"\u524A\u9664"}),(0,M.jsx)("button",{onClick:()=>u(!1),style:{width:"100%",height:I,background:"#eee",color:me,border:"none",borderRadius:8,cursor:"pointer"},children:"\u30AD\u30E3\u30F3\u30BB\u30EB"})]})}),c&&(0,M.jsx)("div",{style:{position:"fixed",bottom:80,left:"50%",transform:"translateX(-50%)",background:"#333",color:R,padding:"10px 24px",borderRadius:20,fontSize:14,fontWeight:600,zIndex:9999},children:c})]})};var or=q($e());var we=q(ie()),zg=({shop:t,staff:e})=>{let[r,n]=(0,or.useState)(new Date().toISOString().slice(0,10)),[i,s]=(0,or.useState)(null),[o,a]=(0,or.useState)([]),[l,u]=(0,or.useState)(""),c=y=>{u(y),setTimeout(()=>u(""),Ne)},d=(0,or.useCallback)(async()=>{let{data:y}=await j.from("transactions").select("*").eq("shop_id",t.id).eq("status","\u5B8C\u4E86").gte("paid_at",r+"T00:00:00").lte("paid_at",r+"T23:59:59"),v=y||[];a(v);let b={total_sales:v.reduce((f,h)=>f+h.total,0),total_customers:v.length,cash_sales:v.filter(f=>f.payment_method==="\u73FE\u91D1").reduce((f,h)=>f+h.total,0),card_sales:v.filter(f=>f.payment_method==="\u30AF\u30EC\u30B8\u30C3\u30C8").reduce((f,h)=>f+h.total,0),e_money_sales:v.filter(f=>f.payment_method==="\u96FB\u5B50\u30DE\u30CD\u30FC").reduce((f,h)=>f+h.total,0),qr_sales:v.filter(f=>f.payment_method==="QR\u6C7A\u6E08").reduce((f,h)=>f+h.total,0)};s(b)},[t.id,r]);(0,or.useEffect)(()=>{d()},[d]);let p=async()=>{if(!i)return;let y={shop_id:t.id,report_date:r,...i,created_by:e.id},{error:v}=await j.from("daily_reports").upsert(y,{onConflict:"shop_id,report_date"});if(v){c("\u274C \u4FDD\u5B58\u306B\u5931\u6557\u3057\u307E\u3057\u305F");return}c("\u2705 \u65E5\u5831\u3092\u4FDD\u5B58\u3057\u307E\u3057\u305F")},m=(y,v,b)=>(0,we.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"10px 0",borderBottom:`1px solid ${C}`},children:[(0,we.jsxs)("span",{style:{fontSize:14},children:[b," ",y]}),(0,we.jsxs)("span",{style:{fontWeight:700,fontSize:16},children:["\xA5",v.toLocaleString()]})]});return(0,we.jsxs)("div",{style:{padding:16},children:[(0,we.jsx)("h2",{style:{color:z,fontSize:20,fontWeight:700,marginBottom:12},children:"\u{1F4CA} \u65E5\u5831"}),(0,we.jsx)("input",{type:"date",value:r,onChange:y=>n(y.target.value),style:{width:"100%",height:I,padding:"0 12px",marginBottom:16,border:`1px solid ${C}`,borderRadius:8,fontSize:15}}),i&&(0,we.jsxs)("div",{style:{background:R,borderRadius:12,padding:16,border:`1px solid ${C}`,marginBottom:16},children:[(0,we.jsxs)("div",{style:{textAlign:"center",padding:"12px 0",marginBottom:12,borderBottom:`2px solid ${J}`},children:[(0,we.jsx)("div",{style:{fontSize:13,color:O},children:"\u58F2\u4E0A\u5408\u8A08"}),(0,we.jsxs)("div",{style:{fontSize:32,fontWeight:700,color:z},children:["\xA5",i.total_sales.toLocaleString()]}),(0,we.jsxs)("div",{style:{fontSize:13,color:O},children:["\u4F1A\u8A08 ",i.total_customers,"\u4EF6"]})]}),m("\u73FE\u91D1",i.cash_sales,"\u{1F4B4}"),m("\u30AF\u30EC\u30B8\u30C3\u30C8",i.card_sales,"\u{1F4B3}"),m("\u96FB\u5B50\u30DE\u30CD\u30FC",i.e_money_sales,"\u{1F4F1}"),m("QR\u6C7A\u6E08",i.qr_sales,"\u{1F4F7}"),(0,we.jsx)("button",{onClick:p,style:{width:"100%",height:I,background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer",marginTop:16},children:"\u{1F4DD} \u65E5\u5831\u3092\u4FDD\u5B58"})]}),o.length>0&&(0,we.jsxs)("div",{children:[(0,we.jsx)("h3",{style:{color:z,fontSize:16,fontWeight:600,marginBottom:8},children:"\u53D6\u5F15\u4E00\u89A7"}),o.map(y=>(0,we.jsxs)("div",{style:{background:R,borderRadius:8,padding:10,marginBottom:6,border:`1px solid ${C}`,fontSize:13,display:"flex",justifyContent:"space-between"},children:[(0,we.jsxs)("span",{children:[new Date(y.paid_at).toLocaleTimeString("ja-JP",{hour:"2-digit",minute:"2-digit"})," ",y.payment_method]}),(0,we.jsxs)("span",{style:{fontWeight:600},children:["\xA5",y.total.toLocaleString()]})]},y.id))]}),l&&(0,we.jsx)("div",{style:{position:"fixed",bottom:80,left:"50%",transform:"translateX(-50%)",background:"#333",color:R,padding:"10px 24px",borderRadius:20,fontSize:14,fontWeight:600,zIndex:9999},children:l})]})};var Wt=q($e());var F=q(ie()),Bg={name:"",role:"staff",pin:"",email:"",phone:"",commission_rate:0,is_active:!0},Mg=({shop:t})=>{let[e,r]=(0,Wt.useState)([]),[n,i]=(0,Wt.useState)({...Bg}),[s,o]=(0,Wt.useState)(null),[a,l]=(0,Wt.useState)(!1),[u,c]=(0,Wt.useState)(""),d=f=>{c(f),setTimeout(()=>c(""),Ne)},p=(0,Wt.useCallback)(async()=>{let{data:f}=await j.from("staff").select("*").eq("shop_id",t.id).order("created_at");f&&r(f)},[t.id]);(0,Wt.useEffect)(()=>{p()},[p]);let m=()=>{i({...Bg}),o(null),l(!0)},y=f=>{i({...f}),o(f.id),l(!0)},v=async()=>{if(!n.name?.trim()){d("\u26A0\uFE0F \u540D\u524D\u306F\u5FC5\u9808\u3067\u3059");return}if(!n.pin||n.pin.length!==6){d("\u26A0\uFE0F PIN\u306F6\u6841\u3067\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044");return}let f={shop_id:t.id,name:n.name,role:n.role,pin:n.pin,email:n.email||null,phone:n.phone||null,commission_rate:parseFloat(n.commission_rate)||0,is_active:n.is_active??!0};s?(await j.from("staff").update(f).eq("id",s),d("\u2705 \u66F4\u65B0\u3057\u307E\u3057\u305F")):(await j.from("staff").insert(f),d("\u2705 \u767B\u9332\u3057\u307E\u3057\u305F")),l(!1),p()},b=async f=>{await j.from("staff").delete().eq("id",f),d("\u{1F5D1} \u524A\u9664\u3057\u307E\u3057\u305F"),l(!1),p()};return(0,F.jsxs)("div",{style:{padding:16},children:[(0,F.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:12},children:[(0,F.jsx)("h2",{style:{color:z,fontSize:20,fontWeight:700},children:"\u{1F465} \u30B9\u30BF\u30C3\u30D5\u7BA1\u7406"}),(0,F.jsx)("button",{onClick:m,style:{height:I,padding:"0 16px",background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer"},children:"+ \u65B0\u898F"})]}),e.length===0?(0,F.jsx)("div",{style:{background:R,borderRadius:12,padding:32,textAlign:"center",color:O,border:`1px solid ${C}`},children:"\u30B9\u30BF\u30C3\u30D5\u304C\u767B\u9332\u3055\u308C\u3066\u3044\u307E\u305B\u3093"}):(0,F.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:e.map(f=>(0,F.jsxs)("div",{onClick:()=>y(f),style:{background:R,borderRadius:10,padding:12,border:`1px solid ${C}`,cursor:"pointer",display:"flex",justifyContent:"space-between",alignItems:"center",opacity:f.is_active?1:.5},children:[(0,F.jsxs)("div",{children:[(0,F.jsxs)("div",{style:{fontWeight:600,fontSize:15},children:[f.name,(0,F.jsx)("span",{style:{marginLeft:8,fontSize:11,padding:"2px 8px",borderRadius:10,background:f.role==="owner"?J:rr,color:f.role==="owner"?R:z},children:Vi[f.role]})]}),(0,F.jsxs)("div",{style:{fontSize:12,color:O},children:["\u6B69\u5408 ",f.commission_rate,"% ",!f.is_active&&"\uFF08\u7121\u52B9\uFF09"]})]}),(0,F.jsx)("span",{style:{fontSize:12,color:O},children:"PIN: \u2022\u2022\u2022\u2022\u2022\u2022"})]},f.id))}),a&&(0,F.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,.4)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:()=>l(!1),children:(0,F.jsxs)("div",{onClick:f=>f.stopPropagation(),style:{background:R,borderRadius:16,padding:20,width:ht,maxWidth:ft,maxHeight:"85vh",overflowY:"auto"},children:[(0,F.jsx)("h3",{style:{color:z,marginBottom:12},children:s?"\u30B9\u30BF\u30C3\u30D5\u7DE8\u96C6":"\u30B9\u30BF\u30C3\u30D5\u767B\u9332"}),(0,F.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,F.jsx)("span",{style:{fontSize:13,color:O},children:"\u540D\u524D *"}),(0,F.jsx)("input",{value:n.name||"",onChange:f=>i(h=>({...h,name:f.target.value})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]}),(0,F.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,F.jsx)("span",{style:{fontSize:13,color:O},children:"PIN\uFF086\u6841\uFF09*"}),(0,F.jsx)("input",{type:"text",maxLength:6,value:n.pin||"",onChange:f=>i(h=>({...h,pin:f.target.value.replace(/\D/g,"").slice(0,6)})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15,letterSpacing:8}})]}),(0,F.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,F.jsx)("span",{style:{fontSize:13,color:O},children:"\u30ED\u30FC\u30EB"}),(0,F.jsx)("select",{value:n.role||"staff",onChange:f=>i(h=>({...h,role:f.target.value})),style:{width:"100%",height:I,border:`1px solid ${C}`,borderRadius:8,fontSize:15},children:up.map(f=>(0,F.jsx)("option",{value:f,children:Vi[f]},f))})]}),(0,F.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,F.jsx)("span",{style:{fontSize:13,color:O},children:"\u6B69\u5408\u7387 (%)"}),(0,F.jsx)("input",{type:"number",step:"1",value:n.commission_rate??0,onChange:f=>i(h=>({...h,commission_rate:f.target.value})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]}),(0,F.jsxs)("label",{style:{display:"block",marginBottom:10},children:[(0,F.jsx)("span",{style:{fontSize:13,color:O},children:"\u30E1\u30FC\u30EB"}),(0,F.jsx)("input",{type:"email",value:n.email||"",onChange:f=>i(h=>({...h,email:f.target.value})),style:{width:"100%",height:I,padding:"0 10px",border:`1px solid ${C}`,borderRadius:8,fontSize:15}})]}),(0,F.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:14},children:[(0,F.jsx)("input",{type:"checkbox",checked:n.is_active??!0,onChange:f=>i(h=>({...h,is_active:f.target.checked}))}),(0,F.jsx)("span",{style:{fontSize:14},children:"\u30A2\u30AF\u30C6\u30A3\u30D6"})]}),(0,F.jsx)("button",{onClick:v,style:{width:"100%",height:I,background:J,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer",marginBottom:8},children:s?"\u66F4\u65B0":"\u767B\u9332"}),s&&(0,F.jsx)("button",{onClick:()=>b(s),style:{width:"100%",height:I,background:dt,color:R,border:"none",borderRadius:8,fontWeight:600,cursor:"pointer",marginBottom:8},children:"\u524A\u9664"}),(0,F.jsx)("button",{onClick:()=>l(!1),style:{width:"100%",height:I,background:"#eee",color:me,border:"none",borderRadius:8,cursor:"pointer"},children:"\u30AD\u30E3\u30F3\u30BB\u30EB"})]})}),u&&(0,F.jsx)("div",{style:{position:"fixed",bottom:80,left:"50%",transform:"translateX(-50%)",background:"#333",color:R,padding:"10px 24px",borderRadius:20,fontSize:14,fontWeight:600,zIndex:9999},children:u})]})};var K=q(ie()),Tw=()=>{let[t,e]=(0,Lr.useState)(null),[r,n]=(0,Lr.useState)(null),[i,s]=(0,Lr.useState)("dashboard"),[o,a]=(0,Lr.useState)(!1),l=(0,Lr.useCallback)((v,b)=>{e(v),n(b),s("dashboard")},[]),u=(0,Lr.useCallback)(v=>{s(v),a(!1)},[]),c=()=>{e(null),n(null),s("dashboard"),a(!1)};if(!t||!r)return(0,K.jsx)(Cg,{onLogin:l});let d=t.role==="owner"||t.role==="manager",p=cp.filter(v=>v.key!=="staff"||d),m=p.slice(0,5),y=()=>{switch(i){case"dashboard":return(0,K.jsx)(Sa,{staff:t,shop:r,onNavigate:u});case"appointments":return(0,K.jsx)(Ag,{shop:r,staff:t});case"status-board":return(0,K.jsx)(Og,{shop:r});case"pos":return(0,K.jsx)(Pg,{shop:r,staff:t});case"customers":return(0,K.jsx)(Ng,{shop:r});case"pets":return(0,K.jsx)(jg,{shop:r});case"records":return(0,K.jsx)(Dg,{shop:r});case"services":return(0,K.jsx)(Ug,{shop:r,isOwner:d});case"reports":return(0,K.jsx)(zg,{shop:r,staff:t});case"staff":return d?(0,K.jsx)(Mg,{shop:r}):(0,K.jsx)(Sa,{staff:t,shop:r,onNavigate:u});default:return(0,K.jsx)(Sa,{staff:t,shop:r,onNavigate:u})}};return(0,K.jsxs)("div",{style:{minHeight:"100dvh",background:Wo,paddingBottom:68},children:[(0,K.jsxs)("header",{style:{position:"sticky",top:0,zIndex:50,background:R,borderBottom:`1px solid ${C}`,display:"flex",justifyContent:"space-between",alignItems:"center",padding:"0 16px",height:52},children:[(0,K.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,K.jsx)("span",{style:{fontSize:22},children:"\u{1F43E}"}),(0,K.jsx)("span",{style:{fontWeight:700,color:z,fontSize:17},children:"PawPOS"})]}),(0,K.jsx)("button",{onClick:()=>a(!o),style:{background:"none",border:"none",fontSize:22,cursor:"pointer",padding:4},children:"\u2630"})]}),o&&(0,K.jsx)("div",{style:{position:"fixed",inset:0,zIndex:200},onClick:()=>a(!1),children:(0,K.jsxs)("div",{style:{position:"absolute",top:0,right:0,width:260,height:"100%",background:R,boxShadow:"-2px 0 10px rgba(0,0,0,.1)",padding:20,overflowY:"auto"},onClick:v=>v.stopPropagation(),children:[(0,K.jsxs)("div",{style:{marginBottom:20,paddingBottom:14,borderBottom:`1px solid ${C}`},children:[(0,K.jsx)("div",{style:{fontWeight:700,fontSize:16},children:t.name}),(0,K.jsxs)("div",{style:{fontSize:12,color:O},children:[Vi[t.role]," \u2500 ",r.name]})]}),p.map(v=>(0,K.jsxs)("button",{onClick:()=>u(v.key),style:{display:"block",width:"100%",textAlign:"left",padding:"10px 12px",marginBottom:4,borderRadius:8,border:"none",fontSize:15,cursor:"pointer",background:i===v.key?rr:"transparent",color:i===v.key?z:me,fontWeight:i===v.key?700:400},children:[v.icon," ",v.label]},v.key)),(0,K.jsx)("hr",{style:{border:"none",borderTop:`1px solid ${C}`,margin:"12px 0"}}),(0,K.jsx)("button",{onClick:c,style:{display:"block",width:"100%",textAlign:"left",padding:"10px 12px",border:"none",borderRadius:8,fontSize:15,cursor:"pointer",background:"transparent",color:"#e74c3c"},children:"\u{1F6AA} \u30ED\u30B0\u30A2\u30A6\u30C8"})]})}),(0,K.jsx)("main",{children:y()}),(0,K.jsx)("nav",{style:{position:"fixed",bottom:0,left:0,right:0,height:64,background:R,borderTop:`1px solid ${C}`,display:"flex",justifyContent:"space-around",alignItems:"center",zIndex:100},children:m.map(v=>(0,K.jsxs)("button",{onClick:()=>u(v.key),style:{display:"flex",flexDirection:"column",alignItems:"center",background:"none",border:"none",cursor:"pointer",color:i===v.key?z:O,fontSize:10,gap:2,padding:"4px 8px"},children:[(0,K.jsx)("span",{style:{fontSize:22},children:v.icon}),(0,K.jsx)("span",{style:{fontWeight:i===v.key?700:400},children:v.label})]},v.key))})]})};(0,Fg.createRoot)(document.getElementById("root")).render((0,K.jsx)(Tw,{}));
/*! Bundled license information:
react/cjs/react.production.min.js:
(**
* @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.
*)
scheduler/cjs/scheduler.production.min.js:
(**
* @license React
* scheduler.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.
*)
react-dom/cjs/react-dom.production.min.js:
(**
* @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.
*)
react/cjs/react-jsx-runtime.production.min.js:
(**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
*/