@utsp/runtime-server 0.17.4 → 0.18.0-nightly.20260204225152.3333dbc
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -22,7 +22,7 @@ var ob=Object.defineProperty;var ab=(r,e,t)=>e in r?ob(r,e,{enumerable:!0,config
|
|
|
22
22
|
*
|
|
23
23
|
* This source code is licensed under the MIT license found in the
|
|
24
24
|
* LICENSE file in the root directory of this source tree.
|
|
25
|
-
*/(function(r){function e(_,j){var G=_.length;_.push(j);e:for(;0<G;){var ee=G-1>>>1,q=_[ee];if(0<i(q,j))_[ee]=j,_[G]=q,G=ee;else break e}}function t(_){return _.length===0?null:_[0]}function n(_){if(_.length===0)return null;var j=_[0],G=_.pop();if(G!==j){_[0]=G;e:for(var ee=0,q=_.length,K=q>>>1;ee<K;){var oe=2*(ee+1)-1,ve=_[oe],ge=oe+1,Ce=_[ge];if(0>i(ve,G))ge<q&&0>i(Ce,ve)?(_[ee]=Ce,_[ge]=G,ee=ge):(_[ee]=ve,_[oe]=G,ee=oe);else if(ge<q&&0>i(Ce,G))_[ee]=Ce,_[ge]=G,ee=ge;else break e}}return j}function i(_,j){var G=_.sortIndex-j.sortIndex;return G!==0?G:_.id-j.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;r.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();r.unstable_now=function(){return o.now()-a}}var l=[],u=[],c=1,d=null,h=3,f=!1,p=!1,m=!1,S=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,g=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(_){for(var j=t(u);j!==null;){if(j.callback===null)n(u);else if(j.startTime<=_)n(u),j.sortIndex=j.expirationTime,e(l,j);else break;j=t(u)}}function C(_){if(m=!1,y(_),!p)if(t(l)!==null)p=!0,X(x);else{var j=t(u);j!==null&&T(C,j.startTime-_)}}function x(_,j){p=!1,m&&(m=!1,w(A),A=-1),f=!0;var G=h;try{for(y(j),d=t(l);d!==null&&(!(d.expirationTime>j)||_&&!z());){var ee=d.callback;if(typeof ee=="function"){d.callback=null,h=d.priorityLevel;var q=ee(d.expirationTime<=j);j=r.unstable_now(),typeof q=="function"?d.callback=q:d===t(l)&&n(l),y(j)}else n(l);d=t(l)}if(d!==null)var K=!0;else{var oe=t(u);oe!==null&&T(C,oe.startTime-j),K=!1}return K}finally{d=null,h=G,f=!1}}var I=!1,E=null,A=-1,R=5,F=-1;function z(){return!(r.unstable_now()-F<R)}function P(){if(E!==null){var _=r.unstable_now();F=_;var j=!0;try{j=E(!0,_)}finally{j?
|
|
25
|
+
*/(function(r){function e(_,j){var G=_.length;_.push(j);e:for(;0<G;){var ee=G-1>>>1,q=_[ee];if(0<i(q,j))_[ee]=j,_[G]=q,G=ee;else break e}}function t(_){return _.length===0?null:_[0]}function n(_){if(_.length===0)return null;var j=_[0],G=_.pop();if(G!==j){_[0]=G;e:for(var ee=0,q=_.length,K=q>>>1;ee<K;){var oe=2*(ee+1)-1,ve=_[oe],ge=oe+1,Ce=_[ge];if(0>i(ve,G))ge<q&&0>i(Ce,ve)?(_[ee]=Ce,_[ge]=G,ee=ge):(_[ee]=ve,_[oe]=G,ee=oe);else if(ge<q&&0>i(Ce,G))_[ee]=Ce,_[ge]=G,ee=ge;else break e}}return j}function i(_,j){var G=_.sortIndex-j.sortIndex;return G!==0?G:_.id-j.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;r.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();r.unstable_now=function(){return o.now()-a}}var l=[],u=[],c=1,d=null,h=3,f=!1,p=!1,m=!1,S=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,g=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(_){for(var j=t(u);j!==null;){if(j.callback===null)n(u);else if(j.startTime<=_)n(u),j.sortIndex=j.expirationTime,e(l,j);else break;j=t(u)}}function C(_){if(m=!1,y(_),!p)if(t(l)!==null)p=!0,X(x);else{var j=t(u);j!==null&&T(C,j.startTime-_)}}function x(_,j){p=!1,m&&(m=!1,w(A),A=-1),f=!0;var G=h;try{for(y(j),d=t(l);d!==null&&(!(d.expirationTime>j)||_&&!z());){var ee=d.callback;if(typeof ee=="function"){d.callback=null,h=d.priorityLevel;var q=ee(d.expirationTime<=j);j=r.unstable_now(),typeof q=="function"?d.callback=q:d===t(l)&&n(l),y(j)}else n(l);d=t(l)}if(d!==null)var K=!0;else{var oe=t(u);oe!==null&&T(C,oe.startTime-j),K=!1}return K}finally{d=null,h=G,f=!1}}var I=!1,E=null,A=-1,R=5,F=-1;function z(){return!(r.unstable_now()-F<R)}function P(){if(E!==null){var _=r.unstable_now();F=_;var j=!0;try{j=E(!0,_)}finally{j?D():(I=!1,E=null)}}else I=!1}var D;if(typeof g=="function")D=function(){g(P)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,V=L.port2;L.port1.onmessage=P,D=function(){V.postMessage(null)}}else D=function(){S(P,0)};function X(_){E=_,I||(I=!0,D())}function T(_,j){A=S(function(){_(r.unstable_now())},j)}r.unstable_IdlePriority=5,r.unstable_ImmediatePriority=1,r.unstable_LowPriority=4,r.unstable_NormalPriority=3,r.unstable_Profiling=null,r.unstable_UserBlockingPriority=2,r.unstable_cancelCallback=function(_){_.callback=null},r.unstable_continueExecution=function(){p||f||(p=!0,X(x))},r.unstable_forceFrameRate=function(_){0>_||125<_?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):R=0<_?Math.floor(1e3/_):5},r.unstable_getCurrentPriorityLevel=function(){return h},r.unstable_getFirstCallbackNode=function(){return t(l)},r.unstable_next=function(_){switch(h){case 1:case 2:case 3:var j=3;break;default:j=h}var G=h;h=j;try{return _()}finally{h=G}},r.unstable_pauseExecution=function(){},r.unstable_requestPaint=function(){},r.unstable_runWithPriority=function(_,j){switch(_){case 1:case 2:case 3:case 4:case 5:break;default:_=3}var G=h;h=_;try{return j()}finally{h=G}},r.unstable_scheduleCallback=function(_,j,G){var ee=r.unstable_now();switch(typeof G=="object"&&G!==null?(G=G.delay,G=typeof G=="number"&&0<G?ee+G:ee):G=ee,_){case 1:var q=-1;break;case 2:q=250;break;case 5:q=1073741823;break;case 4:q=1e4;break;default:q=5e3}return q=G+q,_={id:c++,callback:j,priorityLevel:_,startTime:G,expirationTime:q,sortIndex:-1},G>ee?(_.sortIndex=G,e(u,_),t(l)===null&&_===t(u)&&(m?(w(A),A=-1):m=!0,T(C,G-ee))):(_.sortIndex=q,e(l,_),p||f||(p=!0,X(x))),_},r.unstable_shouldYield=z,r.unstable_wrapCallback=function(_){var j=h;return function(){var G=h;h=j;try{return _.apply(this,arguments)}finally{h=G}}}})(Iy);xy.exports=Iy;var Ab=xy.exports;/**
|
|
26
26
|
* @license React
|
|
27
27
|
* react-dom.production.min.js
|
|
28
28
|
*
|
|
@@ -34,24 +34,24 @@ var ob=Object.defineProperty;var ab=(r,e,t)=>e in r?ob(r,e,{enumerable:!0,config
|
|
|
34
34
|
`+dc+r}var hc=!1;function fc(r,e){if(!r||hc)return"";hc=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(e)if(e=function(){throw Error()},Object.defineProperty(e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(e,[])}catch(u){var n=u}Reflect.construct(r,[],e)}else{try{e.call()}catch(u){n=u}r.call(e.prototype)}else{try{throw Error()}catch(u){n=u}r()}}catch(u){if(u&&n&&typeof u.stack=="string"){for(var i=u.stack.split(`
|
|
35
35
|
`),s=n.stack.split(`
|
|
36
36
|
`),o=i.length-1,a=s.length-1;1<=o&&0<=a&&i[o]!==s[a];)a--;for(;1<=o&&0<=a;o--,a--)if(i[o]!==s[a]){if(o!==1||a!==1)do if(o--,a--,0>a||i[o]!==s[a]){var l=`
|
|
37
|
-
`+i[o].replace(" at new "," at ");return r.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",r.displayName)),l}while(1<=o&&0<=a);break}}}finally{hc=!1,Error.prepareStackTrace=t}return(r=r?r.displayName||r.name:"")?No(r):""}function Db(r){switch(r.tag){case 5:return No(r.type);case 16:return No("Lazy");case 13:return No("Suspense");case 19:return No("SuspenseList");case 0:case 2:case 15:return r=fc(r.type,!1),r;case 11:return r=fc(r.type.render,!1),r;case 1:return r=fc(r.type,!0),r;default:return""}}function od(r){if(r==null)return null;if(typeof r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case Bs:return"Fragment";case Ps:return"Portal";case nd:return"Profiler";case Ph:return"StrictMode";case id:return"Suspense";case sd:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case My:return(r.displayName||"Context")+".Consumer";case Ey:return(r._context.displayName||"Context")+".Provider";case Bh:var e=r.render;return r=r.displayName,r||(r=e.displayName||e.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case zh:return e=r.displayName||null,e!==null?e:od(r.type)||"Memo";case pi:e=r._payload,r=r._init;try{return od(r(e))}catch{}}return null}function Ob(r){var e=r.type;switch(r.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 r=e.render,r=r.displayName||r.name||"",e.displayName||(r!==""?"ForwardRef("+r+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return od(e);case 8:return e===Ph?"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 Pi(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function Ay(r){var e=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function Fb(r){var e=Ay(r)?"checked":"value",t=Object.getOwnPropertyDescriptor(r.constructor.prototype,e),n=""+r[e];if(!r.hasOwnProperty(e)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var i=t.get,s=t.set;return Object.defineProperty(r,e,{configurable:!0,get:function(){return i.call(this)},set:function(o){n=""+o,s.call(this,o)}}),Object.defineProperty(r,e,{enumerable:t.enumerable}),{getValue:function(){return n},setValue:function(o){n=""+o},stopTracking:function(){r._valueTracker=null,delete r[e]}}}}function Ga(r){r._valueTracker||(r._valueTracker=Fb(r))}function Ty(r){if(!r)return!1;var e=r._valueTracker;if(!e)return!0;var t=e.getValue(),n="";return r&&(n=Ay(r)?r.checked?"true":"false":r.value),r=n,r!==t?(e.setValue(r),!0):!1}function Dl(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}function ad(r,e){var t=e.checked;return It({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??r._wrapperState.initialChecked})}function Rp(r,e){var t=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;t=Pi(e.value!=null?e.value:t),r._wrapperState={initialChecked:n,initialValue:t,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function Ry(r,e){e=e.checked,e!=null&&Rh(r,"checked",e,!1)}function ld(r,e){Ry(r,e);var t=Pi(e.value),n=e.type;if(t!=null)n==="number"?(t===0&&r.value===""||r.value!=t)&&(r.value=""+t):r.value!==""+t&&(r.value=""+t);else if(n==="submit"||n==="reset"){r.removeAttribute("value");return}e.hasOwnProperty("value")?ud(r,e.type,t):e.hasOwnProperty("defaultValue")&&ud(r,e.type,Pi(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(r.defaultChecked=!!e.defaultChecked)}function Pp(r,e,t){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=""+r._wrapperState.initialValue,t||e===r.value||(r.value=e),r.defaultValue=e}t=r.name,t!==""&&(r.name=""),r.defaultChecked=!!r._wrapperState.initialChecked,t!==""&&(r.name=t)}function ud(r,e,t){(e!=="number"||Dl(r.ownerDocument)!==r)&&(t==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+t&&(r.defaultValue=""+t))}var Vo=Array.isArray;function Ws(r,e,t,n){if(r=r.options,e){e={};for(var i=0;i<t.length;i++)e["$"+t[i]]=!0;for(t=0;t<r.length;t++)i=e.hasOwnProperty("$"+r[t].value),r[t].selected!==i&&(r[t].selected=i),i&&n&&(r[t].defaultSelected=!0)}else{for(t=""+Pi(t),e=null,i=0;i<r.length;i++){if(r[i].value===t){r[i].selected=!0,n&&(r[i].defaultSelected=!0);return}e!==null||r[i].disabled||(e=r[i])}e!==null&&(e.selected=!0)}}function cd(r,e){if(e.dangerouslySetInnerHTML!=null)throw Error(te(91));return It({},e,{value:void 0,defaultValue:void 0,children:""+r._wrapperState.initialValue})}function Bp(r,e){var t=e.value;if(t==null){if(t=e.children,e=e.defaultValue,t!=null){if(e!=null)throw Error(te(92));if(Vo(t)){if(1<t.length)throw Error(te(93));t=t[0]}e=t}e==null&&(e=""),t=e}r._wrapperState={initialValue:Pi(t)}}function Py(r,e){var t=Pi(e.value),n=Pi(e.defaultValue);t!=null&&(t=""+t,t!==r.value&&(r.value=t),e.defaultValue==null&&r.defaultValue!==t&&(r.defaultValue=t)),n!=null&&(r.defaultValue=""+n)}function zp(r){var e=r.textContent;e===r._wrapperState.initialValue&&e!==""&&e!==null&&(r.value=e)}function By(r){switch(r){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function dd(r,e){return r==null||r==="http://www.w3.org/1999/xhtml"?By(e):r==="http://www.w3.org/2000/svg"&&e==="foreignObject"?"http://www.w3.org/1999/xhtml":r}var Xa,zy=function(r){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(e,t,n,i){MSApp.execUnsafeLocalFunction(function(){return r(e,t,n,i)})}:r}(function(r,e){if(r.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in r)r.innerHTML=e;else{for(Xa=Xa||document.createElement("div"),Xa.innerHTML="<svg>"+e.valueOf().toString()+"</svg>",e=Xa.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;e.firstChild;)r.appendChild(e.firstChild)}});function fa(r,e){if(e){var t=r.firstChild;if(t&&t===r.lastChild&&t.nodeType===3){t.nodeValue=e;return}}r.textContent=e}var qo={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},Lb=["Webkit","ms","Moz","O"];Object.keys(qo).forEach(function(r){Lb.forEach(function(e){e=e+r.charAt(0).toUpperCase()+r.substring(1),qo[e]=qo[r]})});function Dy(r,e,t){return e==null||typeof e=="boolean"||e===""?"":t||typeof e!="number"||e===0||qo.hasOwnProperty(r)&&qo[r]?(""+e).trim():e+"px"}function Oy(r,e){r=r.style;for(var t in e)if(e.hasOwnProperty(t)){var n=t.indexOf("--")===0,i=Dy(t,e[t],n);t==="float"&&(t="cssFloat"),n?r.setProperty(t,i):r[t]=i}}var _b=It({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 hd(r,e){if(e){if(_b[r]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(te(137,r));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(te(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(te(61))}if(e.style!=null&&typeof e.style!="object")throw Error(te(62))}}function fd(r,e){if(r.indexOf("-")===-1)return typeof e.is=="string";switch(r){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 pd=null;function Dh(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var gd=null,Gs=null,Xs=null;function Dp(r){if(r=za(r)){if(typeof gd!="function")throw Error(te(280));var e=r.stateNode;e&&(e=yu(e),gd(r.stateNode,r.type,e))}}function Fy(r){Gs?Xs?Xs.push(r):Xs=[r]:Gs=r}function Ly(){if(Gs){var r=Gs,e=Xs;if(Xs=Gs=null,Dp(r),e)for(r=0;r<e.length;r++)Dp(e[r])}}function _y(r,e){return r(e)}function $y(){}var pc=!1;function Ny(r,e,t){if(pc)return r(e,t);pc=!0;try{return _y(r,e,t)}finally{pc=!1,(Gs!==null||Xs!==null)&&($y(),Ly())}}function pa(r,e){var t=r.stateNode;if(t===null)return null;var n=yu(t);if(n===null)return null;t=n[e];e:switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(n=!n.disabled)||(r=r.type,n=!(r==="button"||r==="input"||r==="select"||r==="textarea")),r=!n;break e;default:r=!1}if(r)return null;if(t&&typeof t!="function")throw Error(te(231,e,typeof t));return t}var md=!1;if(ri)try{var Ao={};Object.defineProperty(Ao,"passive",{get:function(){md=!0}}),window.addEventListener("test",Ao,Ao),window.removeEventListener("test",Ao,Ao)}catch{md=!1}function $b(r,e,t,n,i,s,o,a,l){var u=Array.prototype.slice.call(arguments,3);try{e.apply(t,u)}catch(c){this.onError(c)}}var Qo=!1,Ol=null,Fl=!1,yd=null,Nb={onError:function(r){Qo=!0,Ol=r}};function Vb(r,e,t,n,i,s,o,a,l){Qo=!1,Ol=null,$b.apply(Nb,arguments)}function Hb(r,e,t,n,i,s,o,a,l){if(Vb.apply(this,arguments),Qo){if(Qo){var u=Ol;Qo=!1,Ol=null}else throw Error(te(198));Fl||(Fl=!0,yd=u)}}function fs(r){var e=r,t=r;if(r.alternate)for(;e.return;)e=e.return;else{r=e;do e=r,e.flags&4098&&(t=e.return),r=e.return;while(r)}return e.tag===3?t:null}function Vy(r){if(r.tag===13){var e=r.memoizedState;if(e===null&&(r=r.alternate,r!==null&&(e=r.memoizedState)),e!==null)return e.dehydrated}return null}function Op(r){if(fs(r)!==r)throw Error(te(188))}function jb(r){var e=r.alternate;if(!e){if(e=fs(r),e===null)throw Error(te(188));return e!==r?null:r}for(var t=r,n=e;;){var i=t.return;if(i===null)break;var s=i.alternate;if(s===null){if(n=i.return,n!==null){t=n;continue}break}if(i.child===s.child){for(s=i.child;s;){if(s===t)return Op(i),r;if(s===n)return Op(i),e;s=s.sibling}throw Error(te(188))}if(t.return!==n.return)t=i,n=s;else{for(var o=!1,a=i.child;a;){if(a===t){o=!0,t=i,n=s;break}if(a===n){o=!0,n=i,t=s;break}a=a.sibling}if(!o){for(a=s.child;a;){if(a===t){o=!0,t=s,n=i;break}if(a===n){o=!0,n=s,t=i;break}a=a.sibling}if(!o)throw Error(te(189))}}if(t.alternate!==n)throw Error(te(190))}if(t.tag!==3)throw Error(te(188));return t.stateNode.current===t?r:e}function Hy(r){return r=jb(r),r!==null?jy(r):null}function jy(r){if(r.tag===5||r.tag===6)return r;for(r=r.child;r!==null;){var e=jy(r);if(e!==null)return e;r=r.sibling}return null}var Yy=Jr.unstable_scheduleCallback,Fp=Jr.unstable_cancelCallback,Yb=Jr.unstable_shouldYield,Wb=Jr.unstable_requestPaint,Rt=Jr.unstable_now,Gb=Jr.unstable_getCurrentPriorityLevel,Oh=Jr.unstable_ImmediatePriority,Wy=Jr.unstable_UserBlockingPriority,Ll=Jr.unstable_NormalPriority,Xb=Jr.unstable_LowPriority,Gy=Jr.unstable_IdlePriority,fu=null,Vn=null;function Kb(r){if(Vn&&typeof Vn.onCommitFiberRoot=="function")try{Vn.onCommitFiberRoot(fu,r,void 0,(r.current.flags&128)===128)}catch{}}var Mn=Math.clz32?Math.clz32:Qb,Zb=Math.log,qb=Math.LN2;function Qb(r){return r>>>=0,r===0?32:31-(Zb(r)/qb|0)|0}var Ka=64,Za=4194304;function Ho(r){switch(r&-r){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 r&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return r&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return r}}function _l(r,e){var t=r.pendingLanes;if(t===0)return 0;var n=0,i=r.suspendedLanes,s=r.pingedLanes,o=t&268435455;if(o!==0){var a=o&~i;a!==0?n=Ho(a):(s&=o,s!==0&&(n=Ho(s)))}else o=t&~i,o!==0?n=Ho(o):s!==0&&(n=Ho(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|=t&16),e=r.entangledLanes,e!==0)for(r=r.entanglements,e&=n;0<e;)t=31-Mn(e),i=1<<t,n|=r[t],e&=~i;return n}function Jb(r,e){switch(r){case 1:case 2:case 4:return e+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function e2(r,e){for(var t=r.suspendedLanes,n=r.pingedLanes,i=r.expirationTimes,s=r.pendingLanes;0<s;){var o=31-Mn(s),a=1<<o,l=i[o];l===-1?(!(a&t)||a&n)&&(i[o]=Jb(a,e)):l<=e&&(r.expiredLanes|=a),s&=~a}}function vd(r){return r=r.pendingLanes&-1073741825,r!==0?r:r&1073741824?1073741824:0}function Xy(){var r=Ka;return Ka<<=1,!(Ka&4194240)&&(Ka=64),r}function gc(r){for(var e=[],t=0;31>t;t++)e.push(r);return e}function Pa(r,e,t){r.pendingLanes|=e,e!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,e=31-Mn(e),r[e]=t}function t2(r,e){var t=r.pendingLanes&~e;r.pendingLanes=e,r.suspendedLanes=0,r.pingedLanes=0,r.expiredLanes&=e,r.mutableReadLanes&=e,r.entangledLanes&=e,e=r.entanglements;var n=r.eventTimes;for(r=r.expirationTimes;0<t;){var i=31-Mn(t),s=1<<i;e[i]=0,n[i]=-1,r[i]=-1,t&=~s}}function Fh(r,e){var t=r.entangledLanes|=e;for(r=r.entanglements;t;){var n=31-Mn(t),i=1<<n;i&e|r[n]&e&&(r[n]|=e),t&=~i}}var Xe=0;function Ky(r){return r&=-r,1<r?4<r?r&268435455?16:536870912:4:1}var Zy,Lh,qy,Qy,Jy,wd=!1,qa=[],bi=null,Si=null,xi=null,ga=new Map,ma=new Map,yi=[],r2="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function Lp(r,e){switch(r){case"focusin":case"focusout":bi=null;break;case"dragenter":case"dragleave":Si=null;break;case"mouseover":case"mouseout":xi=null;break;case"pointerover":case"pointerout":ga.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":ma.delete(e.pointerId)}}function To(r,e,t,n,i,s){return r===null||r.nativeEvent!==s?(r={blockedOn:e,domEventName:t,eventSystemFlags:n,nativeEvent:s,targetContainers:[i]},e!==null&&(e=za(e),e!==null&&Lh(e)),r):(r.eventSystemFlags|=n,e=r.targetContainers,i!==null&&e.indexOf(i)===-1&&e.push(i),r)}function n2(r,e,t,n,i){switch(e){case"focusin":return bi=To(bi,r,e,t,n,i),!0;case"dragenter":return Si=To(Si,r,e,t,n,i),!0;case"mouseover":return xi=To(xi,r,e,t,n,i),!0;case"pointerover":var s=i.pointerId;return ga.set(s,To(ga.get(s)||null,r,e,t,n,i)),!0;case"gotpointercapture":return s=i.pointerId,ma.set(s,To(ma.get(s)||null,r,e,t,n,i)),!0}return!1}function e0(r){var e=es(r.target);if(e!==null){var t=fs(e);if(t!==null){if(e=t.tag,e===13){if(e=Vy(t),e!==null){r.blockedOn=e,Jy(r.priority,function(){qy(t)});return}}else if(e===3&&t.stateNode.current.memoizedState.isDehydrated){r.blockedOn=t.tag===3?t.stateNode.containerInfo:null;return}}}r.blockedOn=null}function bl(r){if(r.blockedOn!==null)return!1;for(var e=r.targetContainers;0<e.length;){var t=Cd(r.domEventName,r.eventSystemFlags,e[0],r.nativeEvent);if(t===null){t=r.nativeEvent;var n=new t.constructor(t.type,t);pd=n,t.target.dispatchEvent(n),pd=null}else return e=za(t),e!==null&&Lh(e),r.blockedOn=t,!1;e.shift()}return!0}function _p(r,e,t){bl(r)&&t.delete(e)}function i2(){wd=!1,bi!==null&&bl(bi)&&(bi=null),Si!==null&&bl(Si)&&(Si=null),xi!==null&&bl(xi)&&(xi=null),ga.forEach(_p),ma.forEach(_p)}function Ro(r,e){r.blockedOn===e&&(r.blockedOn=null,wd||(wd=!0,Jr.unstable_scheduleCallback(Jr.unstable_NormalPriority,i2)))}function ya(r){function e(i){return Ro(i,r)}if(0<qa.length){Ro(qa[0],r);for(var t=1;t<qa.length;t++){var n=qa[t];n.blockedOn===r&&(n.blockedOn=null)}}for(bi!==null&&Ro(bi,r),Si!==null&&Ro(Si,r),xi!==null&&Ro(xi,r),ga.forEach(e),ma.forEach(e),t=0;t<yi.length;t++)n=yi[t],n.blockedOn===r&&(n.blockedOn=null);for(;0<yi.length&&(t=yi[0],t.blockedOn===null);)e0(t),t.blockedOn===null&&yi.shift()}var Ks=oi.ReactCurrentBatchConfig,$l=!0;function s2(r,e,t,n){var i=Xe,s=Ks.transition;Ks.transition=null;try{Xe=1,_h(r,e,t,n)}finally{Xe=i,Ks.transition=s}}function o2(r,e,t,n){var i=Xe,s=Ks.transition;Ks.transition=null;try{Xe=4,_h(r,e,t,n)}finally{Xe=i,Ks.transition=s}}function _h(r,e,t,n){if($l){var i=Cd(r,e,t,n);if(i===null)kc(r,e,n,Nl,t),Lp(r,n);else if(n2(i,r,e,t,n))n.stopPropagation();else if(Lp(r,n),e&4&&-1<r2.indexOf(r)){for(;i!==null;){var s=za(i);if(s!==null&&Zy(s),s=Cd(r,e,t,n),s===null&&kc(r,e,n,Nl,t),s===i)break;i=s}i!==null&&n.stopPropagation()}else kc(r,e,n,null,t)}}var Nl=null;function Cd(r,e,t,n){if(Nl=null,r=Dh(n),r=es(r),r!==null)if(e=fs(r),e===null)r=null;else if(t=e.tag,t===13){if(r=Vy(e),r!==null)return r;r=null}else if(t===3){if(e.stateNode.current.memoizedState.isDehydrated)return e.tag===3?e.stateNode.containerInfo:null;r=null}else e!==r&&(r=null);return Nl=r,null}function t0(r){switch(r){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(Gb()){case Oh:return 1;case Wy:return 4;case Ll:case Xb:return 16;case Gy:return 536870912;default:return 16}default:return 16}}var wi=null,$h=null,Sl=null;function r0(){if(Sl)return Sl;var r,e=$h,t=e.length,n,i="value"in wi?wi.value:wi.textContent,s=i.length;for(r=0;r<t&&e[r]===i[r];r++);var o=t-r;for(n=1;n<=o&&e[t-n]===i[s-n];n++);return Sl=i.slice(r,1<n?1-n:void 0)}function xl(r){var e=r.keyCode;return"charCode"in r?(r=r.charCode,r===0&&e===13&&(r=13)):r=e,r===10&&(r=13),32<=r||r===13?r:0}function Qa(){return!0}function $p(){return!1}function tn(r){function e(t,n,i,s,o){this._reactName=t,this._targetInst=i,this.type=n,this.nativeEvent=s,this.target=o,this.currentTarget=null;for(var a in r)r.hasOwnProperty(a)&&(t=r[a],this[a]=t?t(s):s[a]);return this.isDefaultPrevented=(s.defaultPrevented!=null?s.defaultPrevented:s.returnValue===!1)?Qa:$p,this.isPropagationStopped=$p,this}return It(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var t=this.nativeEvent;t&&(t.preventDefault?t.preventDefault():typeof t.returnValue!="unknown"&&(t.returnValue=!1),this.isDefaultPrevented=Qa)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=Qa)},persist:function(){},isPersistent:Qa}),e}var po={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Nh=tn(po),Ba=It({},po,{view:0,detail:0}),a2=tn(Ba),mc,yc,Po,pu=It({},Ba,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Vh,button:0,buttons:0,relatedTarget:function(r){return r.relatedTarget===void 0?r.fromElement===r.srcElement?r.toElement:r.fromElement:r.relatedTarget},movementX:function(r){return"movementX"in r?r.movementX:(r!==Po&&(Po&&r.type==="mousemove"?(mc=r.screenX-Po.screenX,yc=r.screenY-Po.screenY):yc=mc=0,Po=r),mc)},movementY:function(r){return"movementY"in r?r.movementY:yc}}),Np=tn(pu),l2=It({},pu,{dataTransfer:0}),u2=tn(l2),c2=It({},Ba,{relatedTarget:0}),vc=tn(c2),d2=It({},po,{animationName:0,elapsedTime:0,pseudoElement:0}),h2=tn(d2),f2=It({},po,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),p2=tn(f2),g2=It({},po,{data:0}),Vp=tn(g2),m2={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},y2={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},v2={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function w2(r){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(r):(r=v2[r])?!!e[r]:!1}function Vh(){return w2}var C2=It({},Ba,{key:function(r){if(r.key){var e=m2[r.key]||r.key;if(e!=="Unidentified")return e}return r.type==="keypress"?(r=xl(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?y2[r.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Vh,charCode:function(r){return r.type==="keypress"?xl(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?xl(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),b2=tn(C2),S2=It({},pu,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Hp=tn(S2),x2=It({},Ba,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Vh}),I2=tn(x2),k2=It({},po,{propertyName:0,elapsedTime:0,pseudoElement:0}),E2=tn(k2),M2=It({},pu,{deltaX:function(r){return"deltaX"in r?r.deltaX:"wheelDeltaX"in r?-r.wheelDeltaX:0},deltaY:function(r){return"deltaY"in r?r.deltaY:"wheelDeltaY"in r?-r.wheelDeltaY:"wheelDelta"in r?-r.wheelDelta:0},deltaZ:0,deltaMode:0}),U2=tn(M2),A2=[9,13,27,32],Hh=ri&&"CompositionEvent"in window,Jo=null;ri&&"documentMode"in document&&(Jo=document.documentMode);var T2=ri&&"TextEvent"in window&&!Jo,n0=ri&&(!Hh||Jo&&8<Jo&&11>=Jo),jp=" ",Yp=!1;function i0(r,e){switch(r){case"keyup":return A2.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function s0(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var zs=!1;function R2(r,e){switch(r){case"compositionend":return s0(e);case"keypress":return e.which!==32?null:(Yp=!0,jp);case"textInput":return r=e.data,r===jp&&Yp?null:r;default:return null}}function P2(r,e){if(zs)return r==="compositionend"||!Hh&&i0(r,e)?(r=r0(),Sl=$h=wi=null,zs=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1<e.char.length)return e.char;if(e.which)return String.fromCharCode(e.which)}return null;case"compositionend":return n0&&e.locale!=="ko"?null:e.data;default:return null}}var B2={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Wp(r){var e=r&&r.nodeName&&r.nodeName.toLowerCase();return e==="input"?!!B2[r.type]:e==="textarea"}function o0(r,e,t,n){Fy(n),e=Vl(e,"onChange"),0<e.length&&(t=new Nh("onChange","change",null,t,n),r.push({event:t,listeners:e}))}var ea=null,va=null;function z2(r){y0(r,0)}function gu(r){var e=Fs(r);if(Ty(e))return r}function D2(r,e){if(r==="change")return e}var a0=!1;if(ri){var wc;if(ri){var Cc="oninput"in document;if(!Cc){var Gp=document.createElement("div");Gp.setAttribute("oninput","return;"),Cc=typeof Gp.oninput=="function"}wc=Cc}else wc=!1;a0=wc&&(!document.documentMode||9<document.documentMode)}function Xp(){ea&&(ea.detachEvent("onpropertychange",l0),va=ea=null)}function l0(r){if(r.propertyName==="value"&&gu(va)){var e=[];o0(e,va,r,Dh(r)),Ny(z2,e)}}function O2(r,e,t){r==="focusin"?(Xp(),ea=e,va=t,ea.attachEvent("onpropertychange",l0)):r==="focusout"&&Xp()}function F2(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return gu(va)}function L2(r,e){if(r==="click")return gu(e)}function _2(r,e){if(r==="input"||r==="change")return gu(e)}function $2(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var An=typeof Object.is=="function"?Object.is:$2;function wa(r,e){if(An(r,e))return!0;if(typeof r!="object"||r===null||typeof e!="object"||e===null)return!1;var t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;for(n=0;n<t.length;n++){var i=t[n];if(!rd.call(e,i)||!An(r[i],e[i]))return!1}return!0}function Kp(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function Zp(r,e){var t=Kp(r);r=0;for(var n;t;){if(t.nodeType===3){if(n=r+t.textContent.length,r<=e&&n>=e)return{node:t,offset:e-r};r=n}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=Kp(t)}}function u0(r,e){return r&&e?r===e?!0:r&&r.nodeType===3?!1:e&&e.nodeType===3?u0(r,e.parentNode):"contains"in r?r.contains(e):r.compareDocumentPosition?!!(r.compareDocumentPosition(e)&16):!1:!1}function c0(){for(var r=window,e=Dl();e instanceof r.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)r=e.contentWindow;else break;e=Dl(r.document)}return e}function jh(r){var e=r&&r.nodeName&&r.nodeName.toLowerCase();return e&&(e==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||e==="textarea"||r.contentEditable==="true")}function N2(r){var e=c0(),t=r.focusedElem,n=r.selectionRange;if(e!==t&&t&&t.ownerDocument&&u0(t.ownerDocument.documentElement,t)){if(n!==null&&jh(t)){if(e=n.start,r=n.end,r===void 0&&(r=e),"selectionStart"in t)t.selectionStart=e,t.selectionEnd=Math.min(r,t.value.length);else if(r=(e=t.ownerDocument||document)&&e.defaultView||window,r.getSelection){r=r.getSelection();var i=t.textContent.length,s=Math.min(n.start,i);n=n.end===void 0?s:Math.min(n.end,i),!r.extend&&s>n&&(i=n,n=s,s=i),i=Zp(t,s);var o=Zp(t,n);i&&o&&(r.rangeCount!==1||r.anchorNode!==i.node||r.anchorOffset!==i.offset||r.focusNode!==o.node||r.focusOffset!==o.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),r.removeAllRanges(),s>n?(r.addRange(e),r.extend(o.node,o.offset)):(e.setEnd(o.node,o.offset),r.addRange(e)))}}for(e=[],r=t;r=r.parentNode;)r.nodeType===1&&e.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t<e.length;t++)r=e[t],r.element.scrollLeft=r.left,r.element.scrollTop=r.top}}var V2=ri&&"documentMode"in document&&11>=document.documentMode,Ds=null,bd=null,ta=null,Sd=!1;function qp(r,e,t){var n=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;Sd||Ds==null||Ds!==Dl(n)||(n=Ds,"selectionStart"in n&&jh(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}),ta&&wa(ta,n)||(ta=n,n=Vl(bd,"onSelect"),0<n.length&&(e=new Nh("onSelect","select",null,e,t),r.push({event:e,listeners:n}),e.target=Ds)))}function Ja(r,e){var t={};return t[r.toLowerCase()]=e.toLowerCase(),t["Webkit"+r]="webkit"+e,t["Moz"+r]="moz"+e,t}var Os={animationend:Ja("Animation","AnimationEnd"),animationiteration:Ja("Animation","AnimationIteration"),animationstart:Ja("Animation","AnimationStart"),transitionend:Ja("Transition","TransitionEnd")},bc={},d0={};ri&&(d0=document.createElement("div").style,"AnimationEvent"in window||(delete Os.animationend.animation,delete Os.animationiteration.animation,delete Os.animationstart.animation),"TransitionEvent"in window||delete Os.transitionend.transition);function mu(r){if(bc[r])return bc[r];if(!Os[r])return r;var e=Os[r],t;for(t in e)if(e.hasOwnProperty(t)&&t in d0)return bc[r]=e[t];return r}var h0=mu("animationend"),f0=mu("animationiteration"),p0=mu("animationstart"),g0=mu("transitionend"),m0=new Map,Qp="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Di(r,e){m0.set(r,e),hs(e,[r])}for(var Sc=0;Sc<Qp.length;Sc++){var xc=Qp[Sc],H2=xc.toLowerCase(),j2=xc[0].toUpperCase()+xc.slice(1);Di(H2,"on"+j2)}Di(h0,"onAnimationEnd");Di(f0,"onAnimationIteration");Di(p0,"onAnimationStart");Di("dblclick","onDoubleClick");Di("focusin","onFocus");Di("focusout","onBlur");Di(g0,"onTransitionEnd");eo("onMouseEnter",["mouseout","mouseover"]);eo("onMouseLeave",["mouseout","mouseover"]);eo("onPointerEnter",["pointerout","pointerover"]);eo("onPointerLeave",["pointerout","pointerover"]);hs("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));hs("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));hs("onBeforeInput",["compositionend","keypress","textInput","paste"]);hs("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));hs("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));hs("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var jo="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Y2=new Set("cancel close invalid load scroll toggle".split(" ").concat(jo));function Jp(r,e,t){var n=r.type||"unknown-event";r.currentTarget=t,Hb(n,e,void 0,r),r.currentTarget=null}function y0(r,e){e=(e&4)!==0;for(var t=0;t<r.length;t++){var n=r[t],i=n.event;n=n.listeners;e:{var s=void 0;if(e)for(var o=n.length-1;0<=o;o--){var a=n[o],l=a.instance,u=a.currentTarget;if(a=a.listener,l!==s&&i.isPropagationStopped())break e;Jp(i,a,u),s=l}else for(o=0;o<n.length;o++){if(a=n[o],l=a.instance,u=a.currentTarget,a=a.listener,l!==s&&i.isPropagationStopped())break e;Jp(i,a,u),s=l}}}if(Fl)throw r=yd,Fl=!1,yd=null,r}function at(r,e){var t=e[Md];t===void 0&&(t=e[Md]=new Set);var n=r+"__bubble";t.has(n)||(v0(e,r,2,!1),t.add(n))}function Ic(r,e,t){var n=0;e&&(n|=4),v0(t,r,n,e)}var el="_reactListening"+Math.random().toString(36).slice(2);function Ca(r){if(!r[el]){r[el]=!0,ky.forEach(function(t){t!=="selectionchange"&&(Y2.has(t)||Ic(t,!1,r),Ic(t,!0,r))});var e=r.nodeType===9?r:r.ownerDocument;e===null||e[el]||(e[el]=!0,Ic("selectionchange",!1,e))}}function v0(r,e,t,n){switch(t0(e)){case 1:var i=s2;break;case 4:i=o2;break;default:i=_h}t=i.bind(null,e,t,r),i=void 0,!md||e!=="touchstart"&&e!=="touchmove"&&e!=="wheel"||(i=!0),n?i!==void 0?r.addEventListener(e,t,{capture:!0,passive:i}):r.addEventListener(e,t,!0):i!==void 0?r.addEventListener(e,t,{passive:i}):r.addEventListener(e,t,!1)}function kc(r,e,t,n,i){var s=n;if(!(e&1)&&!(e&2)&&n!==null)e:for(;;){if(n===null)return;var o=n.tag;if(o===3||o===4){var a=n.stateNode.containerInfo;if(a===i||a.nodeType===8&&a.parentNode===i)break;if(o===4)for(o=n.return;o!==null;){var l=o.tag;if((l===3||l===4)&&(l=o.stateNode.containerInfo,l===i||l.nodeType===8&&l.parentNode===i))return;o=o.return}for(;a!==null;){if(o=es(a),o===null)return;if(l=o.tag,l===5||l===6){n=s=o;continue e}a=a.parentNode}}n=n.return}Ny(function(){var u=s,c=Dh(t),d=[];e:{var h=m0.get(r);if(h!==void 0){var f=Nh,p=r;switch(r){case"keypress":if(xl(t)===0)break e;case"keydown":case"keyup":f=b2;break;case"focusin":p="focus",f=vc;break;case"focusout":p="blur",f=vc;break;case"beforeblur":case"afterblur":f=vc;break;case"click":if(t.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":f=Np;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":f=u2;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":f=I2;break;case h0:case f0:case p0:f=h2;break;case g0:f=E2;break;case"scroll":f=a2;break;case"wheel":f=U2;break;case"copy":case"cut":case"paste":f=p2;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":f=Hp}var m=(e&4)!==0,S=!m&&r==="scroll",w=m?h!==null?h+"Capture":null:h;m=[];for(var g=u,y;g!==null;){y=g;var C=y.stateNode;if(y.tag===5&&C!==null&&(y=C,w!==null&&(C=pa(g,w),C!=null&&m.push(ba(g,C,y)))),S)break;g=g.return}0<m.length&&(h=new f(h,p,null,t,c),d.push({event:h,listeners:m}))}}if(!(e&7)){e:{if(h=r==="mouseover"||r==="pointerover",f=r==="mouseout"||r==="pointerout",h&&t!==pd&&(p=t.relatedTarget||t.fromElement)&&(es(p)||p[ni]))break e;if((f||h)&&(h=c.window===c?c:(h=c.ownerDocument)?h.defaultView||h.parentWindow:window,f?(p=t.relatedTarget||t.toElement,f=u,p=p?es(p):null,p!==null&&(S=fs(p),p!==S||p.tag!==5&&p.tag!==6)&&(p=null)):(f=null,p=u),f!==p)){if(m=Np,C="onMouseLeave",w="onMouseEnter",g="mouse",(r==="pointerout"||r==="pointerover")&&(m=Hp,C="onPointerLeave",w="onPointerEnter",g="pointer"),S=f==null?h:Fs(f),y=p==null?h:Fs(p),h=new m(C,g+"leave",f,t,c),h.target=S,h.relatedTarget=y,C=null,es(c)===u&&(m=new m(w,g+"enter",p,t,c),m.target=y,m.relatedTarget=S,C=m),S=C,f&&p)t:{for(m=f,w=p,g=0,y=m;y;y=Es(y))g++;for(y=0,C=w;C;C=Es(C))y++;for(;0<g-y;)m=Es(m),g--;for(;0<y-g;)w=Es(w),y--;for(;g--;){if(m===w||w!==null&&m===w.alternate)break t;m=Es(m),w=Es(w)}m=null}else m=null;f!==null&&eg(d,h,f,m,!1),p!==null&&S!==null&&eg(d,S,p,m,!0)}}e:{if(h=u?Fs(u):window,f=h.nodeName&&h.nodeName.toLowerCase(),f==="select"||f==="input"&&h.type==="file")var x=D2;else if(Wp(h))if(a0)x=_2;else{x=F2;var I=O2}else(f=h.nodeName)&&f.toLowerCase()==="input"&&(h.type==="checkbox"||h.type==="radio")&&(x=L2);if(x&&(x=x(r,u))){o0(d,x,t,c);break e}I&&I(r,h,u),r==="focusout"&&(I=h._wrapperState)&&I.controlled&&h.type==="number"&&ud(h,"number",h.value)}switch(I=u?Fs(u):window,r){case"focusin":(Wp(I)||I.contentEditable==="true")&&(Ds=I,bd=u,ta=null);break;case"focusout":ta=bd=Ds=null;break;case"mousedown":Sd=!0;break;case"contextmenu":case"mouseup":case"dragend":Sd=!1,qp(d,t,c);break;case"selectionchange":if(V2)break;case"keydown":case"keyup":qp(d,t,c)}var E;if(Hh)e:{switch(r){case"compositionstart":var A="onCompositionStart";break e;case"compositionend":A="onCompositionEnd";break e;case"compositionupdate":A="onCompositionUpdate";break e}A=void 0}else zs?i0(r,t)&&(A="onCompositionEnd"):r==="keydown"&&t.keyCode===229&&(A="onCompositionStart");A&&(n0&&t.locale!=="ko"&&(zs||A!=="onCompositionStart"?A==="onCompositionEnd"&&zs&&(E=r0()):(wi=c,$h="value"in wi?wi.value:wi.textContent,zs=!0)),I=Vl(u,A),0<I.length&&(A=new Vp(A,r,null,t,c),d.push({event:A,listeners:I}),E?A.data=E:(E=s0(t),E!==null&&(A.data=E)))),(E=T2?R2(r,t):P2(r,t))&&(u=Vl(u,"onBeforeInput"),0<u.length&&(c=new Vp("onBeforeInput","beforeinput",null,t,c),d.push({event:c,listeners:u}),c.data=E))}y0(d,e)})}function ba(r,e,t){return{instance:r,listener:e,currentTarget:t}}function Vl(r,e){for(var t=e+"Capture",n=[];r!==null;){var i=r,s=i.stateNode;i.tag===5&&s!==null&&(i=s,s=pa(r,t),s!=null&&n.unshift(ba(r,s,i)),s=pa(r,e),s!=null&&n.push(ba(r,s,i))),r=r.return}return n}function Es(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5);return r||null}function eg(r,e,t,n,i){for(var s=e._reactName,o=[];t!==null&&t!==n;){var a=t,l=a.alternate,u=a.stateNode;if(l!==null&&l===n)break;a.tag===5&&u!==null&&(a=u,i?(l=pa(t,s),l!=null&&o.unshift(ba(t,l,a))):i||(l=pa(t,s),l!=null&&o.push(ba(t,l,a)))),t=t.return}o.length!==0&&r.push({event:e,listeners:o})}var W2=/\r\n?/g,G2=/\u0000|\uFFFD/g;function tg(r){return(typeof r=="string"?r:""+r).replace(W2,`
|
|
38
|
-
`).replace(G2,"")}function tl(r,e,t){if(e=tg(e),tg(r)!==e&&t)throw Error(te(425))}function Hl(){}var xd=null,Id=null;function kd(r,e){return r==="textarea"||r==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var Ed=typeof setTimeout=="function"?setTimeout:void 0,X2=typeof clearTimeout=="function"?clearTimeout:void 0,rg=typeof Promise=="function"?Promise:void 0,K2=typeof queueMicrotask=="function"?queueMicrotask:typeof rg<"u"?function(r){return rg.resolve(null).then(r).catch(Z2)}:Ed;function Z2(r){setTimeout(function(){throw r})}function Ec(r,e){var t=e,n=0;do{var i=t.nextSibling;if(r.removeChild(t),i&&i.nodeType===8)if(t=i.data,t==="/$"){if(n===0){r.removeChild(i),ya(e);return}n--}else t!=="$"&&t!=="$?"&&t!=="$!"||n++;t=i}while(t);ya(e)}function Ii(r){for(;r!=null;r=r.nextSibling){var e=r.nodeType;if(e===1||e===3)break;if(e===8){if(e=r.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return r}function ng(r){r=r.previousSibling;for(var e=0;r;){if(r.nodeType===8){var t=r.data;if(t==="$"||t==="$!"||t==="$?"){if(e===0)return r;e--}else t==="/$"&&e++}r=r.previousSibling}return null}var go=Math.random().toString(36).slice(2),Nn="__reactFiber$"+go,Sa="__reactProps$"+go,ni="__reactContainer$"+go,Md="__reactEvents$"+go,q2="__reactListeners$"+go,Q2="__reactHandles$"+go;function es(r){var e=r[Nn];if(e)return e;for(var t=r.parentNode;t;){if(e=t[ni]||t[Nn]){if(t=e.alternate,e.child!==null||t!==null&&t.child!==null)for(r=ng(r);r!==null;){if(t=r[Nn])return t;r=ng(r)}return e}r=t,t=r.parentNode}return null}function za(r){return r=r[Nn]||r[ni],!r||r.tag!==5&&r.tag!==6&&r.tag!==13&&r.tag!==3?null:r}function Fs(r){if(r.tag===5||r.tag===6)return r.stateNode;throw Error(te(33))}function yu(r){return r[Sa]||null}var Ud=[],Ls=-1;function Oi(r){return{current:r}}function ut(r){0>Ls||(r.current=Ud[Ls],Ud[Ls]=null,Ls--)}function rt(r,e){Ls++,Ud[Ls]=r.current,r.current=e}var Bi={},vr=Oi(Bi),Lr=Oi(!1),os=Bi;function to(r,e){var t=r.type.contextTypes;if(!t)return Bi;var n=r.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in t)i[s]=e[s];return n&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=e,r.__reactInternalMemoizedMaskedChildContext=i),i}function _r(r){return r=r.childContextTypes,r!=null}function jl(){ut(Lr),ut(vr)}function ig(r,e,t){if(vr.current!==Bi)throw Error(te(168));rt(vr,e),rt(Lr,t)}function w0(r,e,t){var n=r.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return t;n=n.getChildContext();for(var i in n)if(!(i in e))throw Error(te(108,Ob(r)||"Unknown",i));return It({},t,n)}function Yl(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||Bi,os=vr.current,rt(vr,r),rt(Lr,Lr.current),!0}function sg(r,e,t){var n=r.stateNode;if(!n)throw Error(te(169));t?(r=w0(r,e,os),n.__reactInternalMemoizedMergedChildContext=r,ut(Lr),ut(vr),rt(vr,r)):ut(Lr),rt(Lr,t)}var Zn=null,vu=!1,Mc=!1;function C0(r){Zn===null?Zn=[r]:Zn.push(r)}function J2(r){vu=!0,C0(r)}function Fi(){if(!Mc&&Zn!==null){Mc=!0;var r=0,e=Xe;try{var t=Zn;for(Xe=1;r<t.length;r++){var n=t[r];do n=n(!0);while(n!==null)}Zn=null,vu=!1}catch(i){throw Zn!==null&&(Zn=Zn.slice(r+1)),Yy(Oh,Fi),i}finally{Xe=e,Mc=!1}}return null}var _s=[],$s=0,Wl=null,Gl=0,ln=[],un=0,as=null,qn=1,Qn="";function Gi(r,e){_s[$s++]=Gl,_s[$s++]=Wl,Wl=r,Gl=e}function b0(r,e,t){ln[un++]=qn,ln[un++]=Qn,ln[un++]=as,as=r;var n=qn;r=Qn;var i=32-Mn(n)-1;n&=~(1<<i),t+=1;var s=32-Mn(e)+i;if(30<s){var o=i-i%5;s=(n&(1<<o)-1).toString(32),n>>=o,i-=o,qn=1<<32-Mn(e)+i|t<<i|n,Qn=s+r}else qn=1<<s|t<<i|n,Qn=r}function Yh(r){r.return!==null&&(Gi(r,1),b0(r,1,0))}function Wh(r){for(;r===Wl;)Wl=_s[--$s],_s[$s]=null,Gl=_s[--$s],_s[$s]=null;for(;r===as;)as=ln[--un],ln[un]=null,Qn=ln[--un],ln[un]=null,qn=ln[--un],ln[un]=null}var qr=null,Zr=null,vt=!1,kn=null;function S0(r,e){var t=dn(5,null,null,0);t.elementType="DELETED",t.stateNode=e,t.return=r,e=r.deletions,e===null?(r.deletions=[t],r.flags|=16):e.push(t)}function og(r,e){switch(r.tag){case 5:var t=r.type;return e=e.nodeType!==1||t.toLowerCase()!==e.nodeName.toLowerCase()?null:e,e!==null?(r.stateNode=e,qr=r,Zr=Ii(e.firstChild),!0):!1;case 6:return e=r.pendingProps===""||e.nodeType!==3?null:e,e!==null?(r.stateNode=e,qr=r,Zr=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(t=as!==null?{id:qn,overflow:Qn}:null,r.memoizedState={dehydrated:e,treeContext:t,retryLane:1073741824},t=dn(18,null,null,0),t.stateNode=e,t.return=r,r.child=t,qr=r,Zr=null,!0):!1;default:return!1}}function Ad(r){return(r.mode&1)!==0&&(r.flags&128)===0}function Td(r){if(vt){var e=Zr;if(e){var t=e;if(!og(r,e)){if(Ad(r))throw Error(te(418));e=Ii(t.nextSibling);var n=qr;e&&og(r,e)?S0(n,t):(r.flags=r.flags&-4097|2,vt=!1,qr=r)}}else{if(Ad(r))throw Error(te(418));r.flags=r.flags&-4097|2,vt=!1,qr=r}}}function ag(r){for(r=r.return;r!==null&&r.tag!==5&&r.tag!==3&&r.tag!==13;)r=r.return;qr=r}function rl(r){if(r!==qr)return!1;if(!vt)return ag(r),vt=!0,!1;var e;if((e=r.tag!==3)&&!(e=r.tag!==5)&&(e=r.type,e=e!=="head"&&e!=="body"&&!kd(r.type,r.memoizedProps)),e&&(e=Zr)){if(Ad(r))throw x0(),Error(te(418));for(;e;)S0(r,e),e=Ii(e.nextSibling)}if(ag(r),r.tag===13){if(r=r.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(te(317));e:{for(r=r.nextSibling,e=0;r;){if(r.nodeType===8){var t=r.data;if(t==="/$"){if(e===0){Zr=Ii(r.nextSibling);break e}e--}else t!=="$"&&t!=="$!"&&t!=="$?"||e++}r=r.nextSibling}Zr=null}}else Zr=qr?Ii(r.stateNode.nextSibling):null;return!0}function x0(){for(var r=Zr;r;)r=Ii(r.nextSibling)}function ro(){Zr=qr=null,vt=!1}function Gh(r){kn===null?kn=[r]:kn.push(r)}var eS=oi.ReactCurrentBatchConfig;function Bo(r,e,t){if(r=t.ref,r!==null&&typeof r!="function"&&typeof r!="object"){if(t._owner){if(t=t._owner,t){if(t.tag!==1)throw Error(te(309));var n=t.stateNode}if(!n)throw Error(te(147,r));var i=n,s=""+r;return e!==null&&e.ref!==null&&typeof e.ref=="function"&&e.ref._stringRef===s?e.ref:(e=function(o){var a=i.refs;o===null?delete a[s]:a[s]=o},e._stringRef=s,e)}if(typeof r!="string")throw Error(te(284));if(!t._owner)throw Error(te(290,r))}return r}function nl(r,e){throw r=Object.prototype.toString.call(e),Error(te(31,r==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":r))}function lg(r){var e=r._init;return e(r._payload)}function I0(r){function e(w,g){if(r){var y=w.deletions;y===null?(w.deletions=[g],w.flags|=16):y.push(g)}}function t(w,g){if(!r)return null;for(;g!==null;)e(w,g),g=g.sibling;return null}function n(w,g){for(w=new Map;g!==null;)g.key!==null?w.set(g.key,g):w.set(g.index,g),g=g.sibling;return w}function i(w,g){return w=Ui(w,g),w.index=0,w.sibling=null,w}function s(w,g,y){return w.index=y,r?(y=w.alternate,y!==null?(y=y.index,y<g?(w.flags|=2,g):y):(w.flags|=2,g)):(w.flags|=1048576,g)}function o(w){return r&&w.alternate===null&&(w.flags|=2),w}function a(w,g,y,C){return g===null||g.tag!==6?(g=zc(y,w.mode,C),g.return=w,g):(g=i(g,y),g.return=w,g)}function l(w,g,y,C){var x=y.type;return x===Bs?c(w,g,y.props.children,C,y.key):g!==null&&(g.elementType===x||typeof x=="object"&&x!==null&&x.$$typeof===pi&&lg(x)===g.type)?(C=i(g,y.props),C.ref=Bo(w,g,y),C.return=w,C):(C=Tl(y.type,y.key,y.props,null,w.mode,C),C.ref=Bo(w,g,y),C.return=w,C)}function u(w,g,y,C){return g===null||g.tag!==4||g.stateNode.containerInfo!==y.containerInfo||g.stateNode.implementation!==y.implementation?(g=Dc(y,w.mode,C),g.return=w,g):(g=i(g,y.children||[]),g.return=w,g)}function c(w,g,y,C,x){return g===null||g.tag!==7?(g=is(y,w.mode,C,x),g.return=w,g):(g=i(g,y),g.return=w,g)}function d(w,g,y){if(typeof g=="string"&&g!==""||typeof g=="number")return g=zc(""+g,w.mode,y),g.return=w,g;if(typeof g=="object"&&g!==null){switch(g.$$typeof){case Wa:return y=Tl(g.type,g.key,g.props,null,w.mode,y),y.ref=Bo(w,null,g),y.return=w,y;case Ps:return g=Dc(g,w.mode,y),g.return=w,g;case pi:var C=g._init;return d(w,C(g._payload),y)}if(Vo(g)||Uo(g))return g=is(g,w.mode,y,null),g.return=w,g;nl(w,g)}return null}function h(w,g,y,C){var x=g!==null?g.key:null;if(typeof y=="string"&&y!==""||typeof y=="number")return x!==null?null:a(w,g,""+y,C);if(typeof y=="object"&&y!==null){switch(y.$$typeof){case Wa:return y.key===x?l(w,g,y,C):null;case Ps:return y.key===x?u(w,g,y,C):null;case pi:return x=y._init,h(w,g,x(y._payload),C)}if(Vo(y)||Uo(y))return x!==null?null:c(w,g,y,C,null);nl(w,y)}return null}function f(w,g,y,C,x){if(typeof C=="string"&&C!==""||typeof C=="number")return w=w.get(y)||null,a(g,w,""+C,x);if(typeof C=="object"&&C!==null){switch(C.$$typeof){case Wa:return w=w.get(C.key===null?y:C.key)||null,l(g,w,C,x);case Ps:return w=w.get(C.key===null?y:C.key)||null,u(g,w,C,x);case pi:var I=C._init;return f(w,g,y,I(C._payload),x)}if(Vo(C)||Uo(C))return w=w.get(y)||null,c(g,w,C,x,null);nl(g,C)}return null}function p(w,g,y,C){for(var x=null,I=null,E=g,A=g=0,R=null;E!==null&&A<y.length;A++){E.index>A?(R=E,E=null):R=E.sibling;var F=h(w,E,y[A],C);if(F===null){E===null&&(E=R);break}r&&E&&F.alternate===null&&e(w,E),g=s(F,g,A),I===null?x=F:I.sibling=F,I=F,E=R}if(A===y.length)return t(w,E),vt&&Gi(w,A),x;if(E===null){for(;A<y.length;A++)E=d(w,y[A],C),E!==null&&(g=s(E,g,A),I===null?x=E:I.sibling=E,I=E);return vt&&Gi(w,A),x}for(E=n(w,E);A<y.length;A++)R=f(E,w,A,y[A],C),R!==null&&(r&&R.alternate!==null&&E.delete(R.key===null?A:R.key),g=s(R,g,A),I===null?x=R:I.sibling=R,I=R);return r&&E.forEach(function(z){return e(w,z)}),vt&&Gi(w,A),x}function m(w,g,y,C){var x=Uo(y);if(typeof x!="function")throw Error(te(150));if(y=x.call(y),y==null)throw Error(te(151));for(var I=x=null,E=g,A=g=0,R=null,F=y.next();E!==null&&!F.done;A++,F=y.next()){E.index>A?(R=E,E=null):R=E.sibling;var z=h(w,E,F.value,C);if(z===null){E===null&&(E=R);break}r&&E&&z.alternate===null&&e(w,E),g=s(z,g,A),I===null?x=z:I.sibling=z,I=z,E=R}if(F.done)return t(w,E),vt&&Gi(w,A),x;if(E===null){for(;!F.done;A++,F=y.next())F=d(w,F.value,C),F!==null&&(g=s(F,g,A),I===null?x=F:I.sibling=F,I=F);return vt&&Gi(w,A),x}for(E=n(w,E);!F.done;A++,F=y.next())F=f(E,w,A,F.value,C),F!==null&&(r&&F.alternate!==null&&E.delete(F.key===null?A:F.key),g=s(F,g,A),I===null?x=F:I.sibling=F,I=F);return r&&E.forEach(function(P){return e(w,P)}),vt&&Gi(w,A),x}function S(w,g,y,C){if(typeof y=="object"&&y!==null&&y.type===Bs&&y.key===null&&(y=y.props.children),typeof y=="object"&&y!==null){switch(y.$$typeof){case Wa:e:{for(var x=y.key,I=g;I!==null;){if(I.key===x){if(x=y.type,x===Bs){if(I.tag===7){t(w,I.sibling),g=i(I,y.props.children),g.return=w,w=g;break e}}else if(I.elementType===x||typeof x=="object"&&x!==null&&x.$$typeof===pi&&lg(x)===I.type){t(w,I.sibling),g=i(I,y.props),g.ref=Bo(w,I,y),g.return=w,w=g;break e}t(w,I);break}else e(w,I);I=I.sibling}y.type===Bs?(g=is(y.props.children,w.mode,C,y.key),g.return=w,w=g):(C=Tl(y.type,y.key,y.props,null,w.mode,C),C.ref=Bo(w,g,y),C.return=w,w=C)}return o(w);case Ps:e:{for(I=y.key;g!==null;){if(g.key===I)if(g.tag===4&&g.stateNode.containerInfo===y.containerInfo&&g.stateNode.implementation===y.implementation){t(w,g.sibling),g=i(g,y.children||[]),g.return=w,w=g;break e}else{t(w,g);break}else e(w,g);g=g.sibling}g=Dc(y,w.mode,C),g.return=w,w=g}return o(w);case pi:return I=y._init,S(w,g,I(y._payload),C)}if(Vo(y))return p(w,g,y,C);if(Uo(y))return m(w,g,y,C);nl(w,y)}return typeof y=="string"&&y!==""||typeof y=="number"?(y=""+y,g!==null&&g.tag===6?(t(w,g.sibling),g=i(g,y),g.return=w,w=g):(t(w,g),g=zc(y,w.mode,C),g.return=w,w=g),o(w)):t(w,g)}return S}var no=I0(!0),k0=I0(!1),Xl=Oi(null),Kl=null,Ns=null,Xh=null;function Kh(){Xh=Ns=Kl=null}function Zh(r){var e=Xl.current;ut(Xl),r._currentValue=e}function Rd(r,e,t){for(;r!==null;){var n=r.alternate;if((r.childLanes&e)!==e?(r.childLanes|=e,n!==null&&(n.childLanes|=e)):n!==null&&(n.childLanes&e)!==e&&(n.childLanes|=e),r===t)break;r=r.return}}function Zs(r,e){Kl=r,Xh=Ns=null,r=r.dependencies,r!==null&&r.firstContext!==null&&(r.lanes&e&&(Fr=!0),r.firstContext=null)}function fn(r){var e=r._currentValue;if(Xh!==r)if(r={context:r,memoizedValue:e,next:null},Ns===null){if(Kl===null)throw Error(te(308));Ns=r,Kl.dependencies={lanes:0,firstContext:r}}else Ns=Ns.next=r;return e}var ts=null;function qh(r){ts===null?ts=[r]:ts.push(r)}function E0(r,e,t,n){var i=e.interleaved;return i===null?(t.next=t,qh(e)):(t.next=i.next,i.next=t),e.interleaved=t,ii(r,n)}function ii(r,e){r.lanes|=e;var t=r.alternate;for(t!==null&&(t.lanes|=e),t=r,r=r.return;r!==null;)r.childLanes|=e,t=r.alternate,t!==null&&(t.childLanes|=e),t=r,r=r.return;return t.tag===3?t.stateNode:null}var gi=!1;function Qh(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function M0(r,e){r=r.updateQueue,e.updateQueue===r&&(e.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,effects:r.effects})}function Jn(r,e){return{eventTime:r,lane:e,tag:0,payload:null,callback:null,next:null}}function ki(r,e,t){var n=r.updateQueue;if(n===null)return null;if(n=n.shared,De&2){var i=n.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),n.pending=e,ii(r,t)}return i=n.interleaved,i===null?(e.next=e,qh(n)):(e.next=i.next,i.next=e),n.interleaved=e,ii(r,t)}function Il(r,e,t){if(e=e.updateQueue,e!==null&&(e=e.shared,(t&4194240)!==0)){var n=e.lanes;n&=r.pendingLanes,t|=n,e.lanes=t,Fh(r,t)}}function ug(r,e){var t=r.updateQueue,n=r.alternate;if(n!==null&&(n=n.updateQueue,t===n)){var i=null,s=null;if(t=t.firstBaseUpdate,t!==null){do{var o={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};s===null?i=s=o:s=s.next=o,t=t.next}while(t!==null);s===null?i=s=e:s=s.next=e}else i=s=e;t={baseState:n.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:n.shared,effects:n.effects},r.updateQueue=t;return}r=t.lastBaseUpdate,r===null?t.firstBaseUpdate=e:r.next=e,t.lastBaseUpdate=e}function Zl(r,e,t,n){var i=r.updateQueue;gi=!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=r.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 h=a.lane,f=a.eventTime;if((n&h)===h){c!==null&&(c=c.next={eventTime:f,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var p=r,m=a;switch(h=e,f=t,m.tag){case 1:if(p=m.payload,typeof p=="function"){d=p.call(f,d,h);break e}d=p;break e;case 3:p.flags=p.flags&-65537|128;case 0:if(p=m.payload,h=typeof p=="function"?p.call(f,d,h):p,h==null)break e;d=It({},d,h);break e;case 2:gi=!0}}a.callback!==null&&a.lane!==0&&(r.flags|=64,h=i.effects,h===null?i.effects=[a]:h.push(a))}else f={eventTime:f,lane:h,tag:a.tag,payload:a.payload,callback:a.callback,next:null},c===null?(u=c=f,l=d):c=c.next=f,o|=h;if(a=a.next,a===null){if(a=i.shared.pending,a===null)break;h=a,a=h.next,h.next=null,i.lastBaseUpdate=h,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);us|=o,r.lanes=o,r.memoizedState=d}}function cg(r,e,t){if(r=e.effects,e.effects=null,r!==null)for(e=0;e<r.length;e++){var n=r[e],i=n.callback;if(i!==null){if(n.callback=null,n=t,typeof i!="function")throw Error(te(191,i));i.call(n)}}}var Da={},Hn=Oi(Da),xa=Oi(Da),Ia=Oi(Da);function rs(r){if(r===Da)throw Error(te(174));return r}function Jh(r,e){switch(rt(Ia,e),rt(xa,r),rt(Hn,Da),r=e.nodeType,r){case 9:case 11:e=(e=e.documentElement)?e.namespaceURI:dd(null,"");break;default:r=r===8?e.parentNode:e,e=r.namespaceURI||null,r=r.tagName,e=dd(e,r)}ut(Hn),rt(Hn,e)}function io(){ut(Hn),ut(xa),ut(Ia)}function U0(r){rs(Ia.current);var e=rs(Hn.current),t=dd(e,r.type);e!==t&&(rt(xa,r),rt(Hn,t))}function ef(r){xa.current===r&&(ut(Hn),ut(xa))}var St=Oi(0);function ql(r){for(var e=r;e!==null;){if(e.tag===13){var t=e.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||t.data==="$?"||t.data==="$!"))return e}else if(e.tag===19&&e.memoizedProps.revealOrder!==void 0){if(e.flags&128)return e}else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===r)break;for(;e.sibling===null;){if(e.return===null||e.return===r)return null;e=e.return}e.sibling.return=e.return,e=e.sibling}return null}var Uc=[];function tf(){for(var r=0;r<Uc.length;r++)Uc[r]._workInProgressVersionPrimary=null;Uc.length=0}var kl=oi.ReactCurrentDispatcher,Ac=oi.ReactCurrentBatchConfig,ls=0,xt=null,Ht=null,rr=null,Ql=!1,ra=!1,ka=0,tS=0;function fr(){throw Error(te(321))}function rf(r,e){if(e===null)return!1;for(var t=0;t<e.length&&t<r.length;t++)if(!An(r[t],e[t]))return!1;return!0}function nf(r,e,t,n,i,s){if(ls=s,xt=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,kl.current=r===null||r.memoizedState===null?sS:oS,r=t(n,i),ra){s=0;do{if(ra=!1,ka=0,25<=s)throw Error(te(301));s+=1,rr=Ht=null,e.updateQueue=null,kl.current=aS,r=t(n,i)}while(ra)}if(kl.current=Jl,e=Ht!==null&&Ht.next!==null,ls=0,rr=Ht=xt=null,Ql=!1,e)throw Error(te(300));return r}function sf(){var r=ka!==0;return ka=0,r}function $n(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return rr===null?xt.memoizedState=rr=r:rr=rr.next=r,rr}function pn(){if(Ht===null){var r=xt.alternate;r=r!==null?r.memoizedState:null}else r=Ht.next;var e=rr===null?xt.memoizedState:rr.next;if(e!==null)rr=e,Ht=r;else{if(r===null)throw Error(te(310));Ht=r,r={memoizedState:Ht.memoizedState,baseState:Ht.baseState,baseQueue:Ht.baseQueue,queue:Ht.queue,next:null},rr===null?xt.memoizedState=rr=r:rr=rr.next=r}return rr}function Ea(r,e){return typeof e=="function"?e(r):e}function Tc(r){var e=pn(),t=e.queue;if(t===null)throw Error(te(311));t.lastRenderedReducer=r;var n=Ht,i=n.baseQueue,s=t.pending;if(s!==null){if(i!==null){var o=i.next;i.next=s.next,s.next=o}n.baseQueue=i=s,t.pending=null}if(i!==null){s=i.next,n=n.baseState;var a=o=null,l=null,u=s;do{var c=u.lane;if((ls&c)===c)l!==null&&(l=l.next={lane:0,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null}),n=u.hasEagerState?u.eagerState:r(n,u.action);else{var d={lane:c,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null};l===null?(a=l=d,o=n):l=l.next=d,xt.lanes|=c,us|=c}u=u.next}while(u!==null&&u!==s);l===null?o=n:l.next=a,An(n,e.memoizedState)||(Fr=!0),e.memoizedState=n,e.baseState=o,e.baseQueue=l,t.lastRenderedState=n}if(r=t.interleaved,r!==null){i=r;do s=i.lane,xt.lanes|=s,us|=s,i=i.next;while(i!==r)}else i===null&&(t.lanes=0);return[e.memoizedState,t.dispatch]}function Rc(r){var e=pn(),t=e.queue;if(t===null)throw Error(te(311));t.lastRenderedReducer=r;var n=t.dispatch,i=t.pending,s=e.memoizedState;if(i!==null){t.pending=null;var o=i=i.next;do s=r(s,o.action),o=o.next;while(o!==i);An(s,e.memoizedState)||(Fr=!0),e.memoizedState=s,e.baseQueue===null&&(e.baseState=s),t.lastRenderedState=s}return[s,n]}function A0(){}function T0(r,e){var t=xt,n=pn(),i=e(),s=!An(n.memoizedState,i);if(s&&(n.memoizedState=i,Fr=!0),n=n.queue,of(B0.bind(null,t,n,r),[r]),n.getSnapshot!==e||s||rr!==null&&rr.memoizedState.tag&1){if(t.flags|=2048,Ma(9,P0.bind(null,t,n,i,e),void 0,null),nr===null)throw Error(te(349));ls&30||R0(t,e,i)}return i}function R0(r,e,t){r.flags|=16384,r={getSnapshot:e,value:t},e=xt.updateQueue,e===null?(e={lastEffect:null,stores:null},xt.updateQueue=e,e.stores=[r]):(t=e.stores,t===null?e.stores=[r]:t.push(r))}function P0(r,e,t,n){e.value=t,e.getSnapshot=n,z0(e)&&D0(r)}function B0(r,e,t){return t(function(){z0(e)&&D0(r)})}function z0(r){var e=r.getSnapshot;r=r.value;try{var t=e();return!An(r,t)}catch{return!0}}function D0(r){var e=ii(r,1);e!==null&&Un(e,r,1,-1)}function dg(r){var e=$n();return typeof r=="function"&&(r=r()),e.memoizedState=e.baseState=r,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ea,lastRenderedState:r},e.queue=r,r=r.dispatch=iS.bind(null,xt,r),[e.memoizedState,r]}function Ma(r,e,t,n){return r={tag:r,create:e,destroy:t,deps:n,next:null},e=xt.updateQueue,e===null?(e={lastEffect:null,stores:null},xt.updateQueue=e,e.lastEffect=r.next=r):(t=e.lastEffect,t===null?e.lastEffect=r.next=r:(n=t.next,t.next=r,r.next=n,e.lastEffect=r)),r}function O0(){return pn().memoizedState}function El(r,e,t,n){var i=$n();xt.flags|=r,i.memoizedState=Ma(1|e,t,void 0,n===void 0?null:n)}function wu(r,e,t,n){var i=pn();n=n===void 0?null:n;var s=void 0;if(Ht!==null){var o=Ht.memoizedState;if(s=o.destroy,n!==null&&rf(n,o.deps)){i.memoizedState=Ma(e,t,s,n);return}}xt.flags|=r,i.memoizedState=Ma(1|e,t,s,n)}function hg(r,e){return El(8390656,8,r,e)}function of(r,e){return wu(2048,8,r,e)}function F0(r,e){return wu(4,2,r,e)}function L0(r,e){return wu(4,4,r,e)}function _0(r,e){if(typeof e=="function")return r=r(),e(r),function(){e(null)};if(e!=null)return r=r(),e.current=r,function(){e.current=null}}function $0(r,e,t){return t=t!=null?t.concat([r]):null,wu(4,4,_0.bind(null,e,r),t)}function af(){}function N0(r,e){var t=pn();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&rf(e,n[1])?n[0]:(t.memoizedState=[r,e],r)}function V0(r,e){var t=pn();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&rf(e,n[1])?n[0]:(r=r(),t.memoizedState=[r,e],r)}function H0(r,e,t){return ls&21?(An(t,e)||(t=Xy(),xt.lanes|=t,us|=t,r.baseState=!0),e):(r.baseState&&(r.baseState=!1,Fr=!0),r.memoizedState=t)}function rS(r,e){var t=Xe;Xe=t!==0&&4>t?t:4,r(!0);var n=Ac.transition;Ac.transition={};try{r(!1),e()}finally{Xe=t,Ac.transition=n}}function j0(){return pn().memoizedState}function nS(r,e,t){var n=Mi(r);if(t={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null},Y0(r))W0(e,t);else if(t=E0(r,e,t,n),t!==null){var i=Ur();Un(t,r,n,i),G0(t,e,n)}}function iS(r,e,t){var n=Mi(r),i={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null};if(Y0(r))W0(e,i);else{var s=r.alternate;if(r.lanes===0&&(s===null||s.lanes===0)&&(s=e.lastRenderedReducer,s!==null))try{var o=e.lastRenderedState,a=s(o,t);if(i.hasEagerState=!0,i.eagerState=a,An(a,o)){var l=e.interleaved;l===null?(i.next=i,qh(e)):(i.next=l.next,l.next=i),e.interleaved=i;return}}catch{}finally{}t=E0(r,e,i,n),t!==null&&(i=Ur(),Un(t,r,n,i),G0(t,e,n))}}function Y0(r){var e=r.alternate;return r===xt||e!==null&&e===xt}function W0(r,e){ra=Ql=!0;var t=r.pending;t===null?e.next=e:(e.next=t.next,t.next=e),r.pending=e}function G0(r,e,t){if(t&4194240){var n=e.lanes;n&=r.pendingLanes,t|=n,e.lanes=t,Fh(r,t)}}var Jl={readContext:fn,useCallback:fr,useContext:fr,useEffect:fr,useImperativeHandle:fr,useInsertionEffect:fr,useLayoutEffect:fr,useMemo:fr,useReducer:fr,useRef:fr,useState:fr,useDebugValue:fr,useDeferredValue:fr,useTransition:fr,useMutableSource:fr,useSyncExternalStore:fr,useId:fr,unstable_isNewReconciler:!1},sS={readContext:fn,useCallback:function(r,e){return $n().memoizedState=[r,e===void 0?null:e],r},useContext:fn,useEffect:hg,useImperativeHandle:function(r,e,t){return t=t!=null?t.concat([r]):null,El(4194308,4,_0.bind(null,e,r),t)},useLayoutEffect:function(r,e){return El(4194308,4,r,e)},useInsertionEffect:function(r,e){return El(4,2,r,e)},useMemo:function(r,e){var t=$n();return e=e===void 0?null:e,r=r(),t.memoizedState=[r,e],r},useReducer:function(r,e,t){var n=$n();return e=t!==void 0?t(e):e,n.memoizedState=n.baseState=e,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:e},n.queue=r,r=r.dispatch=nS.bind(null,xt,r),[n.memoizedState,r]},useRef:function(r){var e=$n();return r={current:r},e.memoizedState=r},useState:dg,useDebugValue:af,useDeferredValue:function(r){return $n().memoizedState=r},useTransition:function(){var r=dg(!1),e=r[0];return r=rS.bind(null,r[1]),$n().memoizedState=r,[e,r]},useMutableSource:function(){},useSyncExternalStore:function(r,e,t){var n=xt,i=$n();if(vt){if(t===void 0)throw Error(te(407));t=t()}else{if(t=e(),nr===null)throw Error(te(349));ls&30||R0(n,e,t)}i.memoizedState=t;var s={value:t,getSnapshot:e};return i.queue=s,hg(B0.bind(null,n,s,r),[r]),n.flags|=2048,Ma(9,P0.bind(null,n,s,t,e),void 0,null),t},useId:function(){var r=$n(),e=nr.identifierPrefix;if(vt){var t=Qn,n=qn;t=(n&~(1<<32-Mn(n)-1)).toString(32)+t,e=":"+e+"R"+t,t=ka++,0<t&&(e+="H"+t.toString(32)),e+=":"}else t=tS++,e=":"+e+"r"+t.toString(32)+":";return r.memoizedState=e},unstable_isNewReconciler:!1},oS={readContext:fn,useCallback:N0,useContext:fn,useEffect:of,useImperativeHandle:$0,useInsertionEffect:F0,useLayoutEffect:L0,useMemo:V0,useReducer:Tc,useRef:O0,useState:function(){return Tc(Ea)},useDebugValue:af,useDeferredValue:function(r){var e=pn();return H0(e,Ht.memoizedState,r)},useTransition:function(){var r=Tc(Ea)[0],e=pn().memoizedState;return[r,e]},useMutableSource:A0,useSyncExternalStore:T0,useId:j0,unstable_isNewReconciler:!1},aS={readContext:fn,useCallback:N0,useContext:fn,useEffect:of,useImperativeHandle:$0,useInsertionEffect:F0,useLayoutEffect:L0,useMemo:V0,useReducer:Rc,useRef:O0,useState:function(){return Rc(Ea)},useDebugValue:af,useDeferredValue:function(r){var e=pn();return Ht===null?e.memoizedState=r:H0(e,Ht.memoizedState,r)},useTransition:function(){var r=Rc(Ea)[0],e=pn().memoizedState;return[r,e]},useMutableSource:A0,useSyncExternalStore:T0,useId:j0,unstable_isNewReconciler:!1};function bn(r,e){if(r&&r.defaultProps){e=It({},e),r=r.defaultProps;for(var t in r)e[t]===void 0&&(e[t]=r[t]);return e}return e}function Pd(r,e,t,n){e=r.memoizedState,t=t(n,e),t=t==null?e:It({},e,t),r.memoizedState=t,r.lanes===0&&(r.updateQueue.baseState=t)}var Cu={isMounted:function(r){return(r=r._reactInternals)?fs(r)===r:!1},enqueueSetState:function(r,e,t){r=r._reactInternals;var n=Ur(),i=Mi(r),s=Jn(n,i);s.payload=e,t!=null&&(s.callback=t),e=ki(r,s,i),e!==null&&(Un(e,r,i,n),Il(e,r,i))},enqueueReplaceState:function(r,e,t){r=r._reactInternals;var n=Ur(),i=Mi(r),s=Jn(n,i);s.tag=1,s.payload=e,t!=null&&(s.callback=t),e=ki(r,s,i),e!==null&&(Un(e,r,i,n),Il(e,r,i))},enqueueForceUpdate:function(r,e){r=r._reactInternals;var t=Ur(),n=Mi(r),i=Jn(t,n);i.tag=2,e!=null&&(i.callback=e),e=ki(r,i,n),e!==null&&(Un(e,r,n,t),Il(e,r,n))}};function fg(r,e,t,n,i,s,o){return r=r.stateNode,typeof r.shouldComponentUpdate=="function"?r.shouldComponentUpdate(n,s,o):e.prototype&&e.prototype.isPureReactComponent?!wa(t,n)||!wa(i,s):!0}function X0(r,e,t){var n=!1,i=Bi,s=e.contextType;return typeof s=="object"&&s!==null?s=fn(s):(i=_r(e)?os:vr.current,n=e.contextTypes,s=(n=n!=null)?to(r,i):Bi),e=new e(t,s),r.memoizedState=e.state!==null&&e.state!==void 0?e.state:null,e.updater=Cu,r.stateNode=e,e._reactInternals=r,n&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=i,r.__reactInternalMemoizedMaskedChildContext=s),e}function pg(r,e,t,n){r=e.state,typeof e.componentWillReceiveProps=="function"&&e.componentWillReceiveProps(t,n),typeof e.UNSAFE_componentWillReceiveProps=="function"&&e.UNSAFE_componentWillReceiveProps(t,n),e.state!==r&&Cu.enqueueReplaceState(e,e.state,null)}function Bd(r,e,t,n){var i=r.stateNode;i.props=t,i.state=r.memoizedState,i.refs={},Qh(r);var s=e.contextType;typeof s=="object"&&s!==null?i.context=fn(s):(s=_r(e)?os:vr.current,i.context=to(r,s)),i.state=r.memoizedState,s=e.getDerivedStateFromProps,typeof s=="function"&&(Pd(r,e,s,t),i.state=r.memoizedState),typeof e.getDerivedStateFromProps=="function"||typeof i.getSnapshotBeforeUpdate=="function"||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(e=i.state,typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount(),e!==i.state&&Cu.enqueueReplaceState(i,i.state,null),Zl(r,t,i,n),i.state=r.memoizedState),typeof i.componentDidMount=="function"&&(r.flags|=4194308)}function so(r,e){try{var t="",n=e;do t+=Db(n),n=n.return;while(n);var i=t}catch(s){i=`
|
|
37
|
+
`+i[o].replace(" at new "," at ");return r.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",r.displayName)),l}while(1<=o&&0<=a);break}}}finally{hc=!1,Error.prepareStackTrace=t}return(r=r?r.displayName||r.name:"")?No(r):""}function Ob(r){switch(r.tag){case 5:return No(r.type);case 16:return No("Lazy");case 13:return No("Suspense");case 19:return No("SuspenseList");case 0:case 2:case 15:return r=fc(r.type,!1),r;case 11:return r=fc(r.type.render,!1),r;case 1:return r=fc(r.type,!0),r;default:return""}}function od(r){if(r==null)return null;if(typeof r=="function")return r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case Bs:return"Fragment";case Ps:return"Portal";case nd:return"Profiler";case Ph:return"StrictMode";case id:return"Suspense";case sd:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case My:return(r.displayName||"Context")+".Consumer";case Ey:return(r._context.displayName||"Context")+".Provider";case Bh:var e=r.render;return r=r.displayName,r||(r=e.displayName||e.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case zh:return e=r.displayName||null,e!==null?e:od(r.type)||"Memo";case pi:e=r._payload,r=r._init;try{return od(r(e))}catch{}}return null}function Db(r){var e=r.type;switch(r.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 r=e.render,r=r.displayName||r.name||"",e.displayName||(r!==""?"ForwardRef("+r+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return od(e);case 8:return e===Ph?"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 Pi(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function Ay(r){var e=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function Fb(r){var e=Ay(r)?"checked":"value",t=Object.getOwnPropertyDescriptor(r.constructor.prototype,e),n=""+r[e];if(!r.hasOwnProperty(e)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var i=t.get,s=t.set;return Object.defineProperty(r,e,{configurable:!0,get:function(){return i.call(this)},set:function(o){n=""+o,s.call(this,o)}}),Object.defineProperty(r,e,{enumerable:t.enumerable}),{getValue:function(){return n},setValue:function(o){n=""+o},stopTracking:function(){r._valueTracker=null,delete r[e]}}}}function Ga(r){r._valueTracker||(r._valueTracker=Fb(r))}function Ty(r){if(!r)return!1;var e=r._valueTracker;if(!e)return!0;var t=e.getValue(),n="";return r&&(n=Ay(r)?r.checked?"true":"false":r.value),r=n,r!==t?(e.setValue(r),!0):!1}function Ol(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}function ad(r,e){var t=e.checked;return It({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??r._wrapperState.initialChecked})}function Rp(r,e){var t=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;t=Pi(e.value!=null?e.value:t),r._wrapperState={initialChecked:n,initialValue:t,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function Ry(r,e){e=e.checked,e!=null&&Rh(r,"checked",e,!1)}function ld(r,e){Ry(r,e);var t=Pi(e.value),n=e.type;if(t!=null)n==="number"?(t===0&&r.value===""||r.value!=t)&&(r.value=""+t):r.value!==""+t&&(r.value=""+t);else if(n==="submit"||n==="reset"){r.removeAttribute("value");return}e.hasOwnProperty("value")?ud(r,e.type,t):e.hasOwnProperty("defaultValue")&&ud(r,e.type,Pi(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(r.defaultChecked=!!e.defaultChecked)}function Pp(r,e,t){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=""+r._wrapperState.initialValue,t||e===r.value||(r.value=e),r.defaultValue=e}t=r.name,t!==""&&(r.name=""),r.defaultChecked=!!r._wrapperState.initialChecked,t!==""&&(r.name=t)}function ud(r,e,t){(e!=="number"||Ol(r.ownerDocument)!==r)&&(t==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+t&&(r.defaultValue=""+t))}var Vo=Array.isArray;function Ws(r,e,t,n){if(r=r.options,e){e={};for(var i=0;i<t.length;i++)e["$"+t[i]]=!0;for(t=0;t<r.length;t++)i=e.hasOwnProperty("$"+r[t].value),r[t].selected!==i&&(r[t].selected=i),i&&n&&(r[t].defaultSelected=!0)}else{for(t=""+Pi(t),e=null,i=0;i<r.length;i++){if(r[i].value===t){r[i].selected=!0,n&&(r[i].defaultSelected=!0);return}e!==null||r[i].disabled||(e=r[i])}e!==null&&(e.selected=!0)}}function cd(r,e){if(e.dangerouslySetInnerHTML!=null)throw Error(te(91));return It({},e,{value:void 0,defaultValue:void 0,children:""+r._wrapperState.initialValue})}function Bp(r,e){var t=e.value;if(t==null){if(t=e.children,e=e.defaultValue,t!=null){if(e!=null)throw Error(te(92));if(Vo(t)){if(1<t.length)throw Error(te(93));t=t[0]}e=t}e==null&&(e=""),t=e}r._wrapperState={initialValue:Pi(t)}}function Py(r,e){var t=Pi(e.value),n=Pi(e.defaultValue);t!=null&&(t=""+t,t!==r.value&&(r.value=t),e.defaultValue==null&&r.defaultValue!==t&&(r.defaultValue=t)),n!=null&&(r.defaultValue=""+n)}function zp(r){var e=r.textContent;e===r._wrapperState.initialValue&&e!==""&&e!==null&&(r.value=e)}function By(r){switch(r){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function dd(r,e){return r==null||r==="http://www.w3.org/1999/xhtml"?By(e):r==="http://www.w3.org/2000/svg"&&e==="foreignObject"?"http://www.w3.org/1999/xhtml":r}var Xa,zy=function(r){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(e,t,n,i){MSApp.execUnsafeLocalFunction(function(){return r(e,t,n,i)})}:r}(function(r,e){if(r.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in r)r.innerHTML=e;else{for(Xa=Xa||document.createElement("div"),Xa.innerHTML="<svg>"+e.valueOf().toString()+"</svg>",e=Xa.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;e.firstChild;)r.appendChild(e.firstChild)}});function fa(r,e){if(e){var t=r.firstChild;if(t&&t===r.lastChild&&t.nodeType===3){t.nodeValue=e;return}}r.textContent=e}var qo={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},Lb=["Webkit","ms","Moz","O"];Object.keys(qo).forEach(function(r){Lb.forEach(function(e){e=e+r.charAt(0).toUpperCase()+r.substring(1),qo[e]=qo[r]})});function Oy(r,e,t){return e==null||typeof e=="boolean"||e===""?"":t||typeof e!="number"||e===0||qo.hasOwnProperty(r)&&qo[r]?(""+e).trim():e+"px"}function Dy(r,e){r=r.style;for(var t in e)if(e.hasOwnProperty(t)){var n=t.indexOf("--")===0,i=Oy(t,e[t],n);t==="float"&&(t="cssFloat"),n?r.setProperty(t,i):r[t]=i}}var _b=It({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 hd(r,e){if(e){if(_b[r]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(te(137,r));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(te(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(te(61))}if(e.style!=null&&typeof e.style!="object")throw Error(te(62))}}function fd(r,e){if(r.indexOf("-")===-1)return typeof e.is=="string";switch(r){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 pd=null;function Oh(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var gd=null,Gs=null,Xs=null;function Op(r){if(r=za(r)){if(typeof gd!="function")throw Error(te(280));var e=r.stateNode;e&&(e=yu(e),gd(r.stateNode,r.type,e))}}function Fy(r){Gs?Xs?Xs.push(r):Xs=[r]:Gs=r}function Ly(){if(Gs){var r=Gs,e=Xs;if(Xs=Gs=null,Op(r),e)for(r=0;r<e.length;r++)Op(e[r])}}function _y(r,e){return r(e)}function $y(){}var pc=!1;function Ny(r,e,t){if(pc)return r(e,t);pc=!0;try{return _y(r,e,t)}finally{pc=!1,(Gs!==null||Xs!==null)&&($y(),Ly())}}function pa(r,e){var t=r.stateNode;if(t===null)return null;var n=yu(t);if(n===null)return null;t=n[e];e:switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(n=!n.disabled)||(r=r.type,n=!(r==="button"||r==="input"||r==="select"||r==="textarea")),r=!n;break e;default:r=!1}if(r)return null;if(t&&typeof t!="function")throw Error(te(231,e,typeof t));return t}var md=!1;if(ri)try{var Ao={};Object.defineProperty(Ao,"passive",{get:function(){md=!0}}),window.addEventListener("test",Ao,Ao),window.removeEventListener("test",Ao,Ao)}catch{md=!1}function $b(r,e,t,n,i,s,o,a,l){var u=Array.prototype.slice.call(arguments,3);try{e.apply(t,u)}catch(c){this.onError(c)}}var Qo=!1,Dl=null,Fl=!1,yd=null,Nb={onError:function(r){Qo=!0,Dl=r}};function Vb(r,e,t,n,i,s,o,a,l){Qo=!1,Dl=null,$b.apply(Nb,arguments)}function Hb(r,e,t,n,i,s,o,a,l){if(Vb.apply(this,arguments),Qo){if(Qo){var u=Dl;Qo=!1,Dl=null}else throw Error(te(198));Fl||(Fl=!0,yd=u)}}function fs(r){var e=r,t=r;if(r.alternate)for(;e.return;)e=e.return;else{r=e;do e=r,e.flags&4098&&(t=e.return),r=e.return;while(r)}return e.tag===3?t:null}function Vy(r){if(r.tag===13){var e=r.memoizedState;if(e===null&&(r=r.alternate,r!==null&&(e=r.memoizedState)),e!==null)return e.dehydrated}return null}function Dp(r){if(fs(r)!==r)throw Error(te(188))}function jb(r){var e=r.alternate;if(!e){if(e=fs(r),e===null)throw Error(te(188));return e!==r?null:r}for(var t=r,n=e;;){var i=t.return;if(i===null)break;var s=i.alternate;if(s===null){if(n=i.return,n!==null){t=n;continue}break}if(i.child===s.child){for(s=i.child;s;){if(s===t)return Dp(i),r;if(s===n)return Dp(i),e;s=s.sibling}throw Error(te(188))}if(t.return!==n.return)t=i,n=s;else{for(var o=!1,a=i.child;a;){if(a===t){o=!0,t=i,n=s;break}if(a===n){o=!0,n=i,t=s;break}a=a.sibling}if(!o){for(a=s.child;a;){if(a===t){o=!0,t=s,n=i;break}if(a===n){o=!0,n=s,t=i;break}a=a.sibling}if(!o)throw Error(te(189))}}if(t.alternate!==n)throw Error(te(190))}if(t.tag!==3)throw Error(te(188));return t.stateNode.current===t?r:e}function Hy(r){return r=jb(r),r!==null?jy(r):null}function jy(r){if(r.tag===5||r.tag===6)return r;for(r=r.child;r!==null;){var e=jy(r);if(e!==null)return e;r=r.sibling}return null}var Yy=Jr.unstable_scheduleCallback,Fp=Jr.unstable_cancelCallback,Yb=Jr.unstable_shouldYield,Wb=Jr.unstable_requestPaint,Rt=Jr.unstable_now,Gb=Jr.unstable_getCurrentPriorityLevel,Dh=Jr.unstable_ImmediatePriority,Wy=Jr.unstable_UserBlockingPriority,Ll=Jr.unstable_NormalPriority,Xb=Jr.unstable_LowPriority,Gy=Jr.unstable_IdlePriority,fu=null,Vn=null;function Kb(r){if(Vn&&typeof Vn.onCommitFiberRoot=="function")try{Vn.onCommitFiberRoot(fu,r,void 0,(r.current.flags&128)===128)}catch{}}var Mn=Math.clz32?Math.clz32:Qb,Zb=Math.log,qb=Math.LN2;function Qb(r){return r>>>=0,r===0?32:31-(Zb(r)/qb|0)|0}var Ka=64,Za=4194304;function Ho(r){switch(r&-r){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 r&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return r&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return r}}function _l(r,e){var t=r.pendingLanes;if(t===0)return 0;var n=0,i=r.suspendedLanes,s=r.pingedLanes,o=t&268435455;if(o!==0){var a=o&~i;a!==0?n=Ho(a):(s&=o,s!==0&&(n=Ho(s)))}else o=t&~i,o!==0?n=Ho(o):s!==0&&(n=Ho(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|=t&16),e=r.entangledLanes,e!==0)for(r=r.entanglements,e&=n;0<e;)t=31-Mn(e),i=1<<t,n|=r[t],e&=~i;return n}function Jb(r,e){switch(r){case 1:case 2:case 4:return e+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function e2(r,e){for(var t=r.suspendedLanes,n=r.pingedLanes,i=r.expirationTimes,s=r.pendingLanes;0<s;){var o=31-Mn(s),a=1<<o,l=i[o];l===-1?(!(a&t)||a&n)&&(i[o]=Jb(a,e)):l<=e&&(r.expiredLanes|=a),s&=~a}}function vd(r){return r=r.pendingLanes&-1073741825,r!==0?r:r&1073741824?1073741824:0}function Xy(){var r=Ka;return Ka<<=1,!(Ka&4194240)&&(Ka=64),r}function gc(r){for(var e=[],t=0;31>t;t++)e.push(r);return e}function Pa(r,e,t){r.pendingLanes|=e,e!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,e=31-Mn(e),r[e]=t}function t2(r,e){var t=r.pendingLanes&~e;r.pendingLanes=e,r.suspendedLanes=0,r.pingedLanes=0,r.expiredLanes&=e,r.mutableReadLanes&=e,r.entangledLanes&=e,e=r.entanglements;var n=r.eventTimes;for(r=r.expirationTimes;0<t;){var i=31-Mn(t),s=1<<i;e[i]=0,n[i]=-1,r[i]=-1,t&=~s}}function Fh(r,e){var t=r.entangledLanes|=e;for(r=r.entanglements;t;){var n=31-Mn(t),i=1<<n;i&e|r[n]&e&&(r[n]|=e),t&=~i}}var Xe=0;function Ky(r){return r&=-r,1<r?4<r?r&268435455?16:536870912:4:1}var Zy,Lh,qy,Qy,Jy,wd=!1,qa=[],bi=null,Si=null,xi=null,ga=new Map,ma=new Map,yi=[],r2="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function Lp(r,e){switch(r){case"focusin":case"focusout":bi=null;break;case"dragenter":case"dragleave":Si=null;break;case"mouseover":case"mouseout":xi=null;break;case"pointerover":case"pointerout":ga.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":ma.delete(e.pointerId)}}function To(r,e,t,n,i,s){return r===null||r.nativeEvent!==s?(r={blockedOn:e,domEventName:t,eventSystemFlags:n,nativeEvent:s,targetContainers:[i]},e!==null&&(e=za(e),e!==null&&Lh(e)),r):(r.eventSystemFlags|=n,e=r.targetContainers,i!==null&&e.indexOf(i)===-1&&e.push(i),r)}function n2(r,e,t,n,i){switch(e){case"focusin":return bi=To(bi,r,e,t,n,i),!0;case"dragenter":return Si=To(Si,r,e,t,n,i),!0;case"mouseover":return xi=To(xi,r,e,t,n,i),!0;case"pointerover":var s=i.pointerId;return ga.set(s,To(ga.get(s)||null,r,e,t,n,i)),!0;case"gotpointercapture":return s=i.pointerId,ma.set(s,To(ma.get(s)||null,r,e,t,n,i)),!0}return!1}function e0(r){var e=es(r.target);if(e!==null){var t=fs(e);if(t!==null){if(e=t.tag,e===13){if(e=Vy(t),e!==null){r.blockedOn=e,Jy(r.priority,function(){qy(t)});return}}else if(e===3&&t.stateNode.current.memoizedState.isDehydrated){r.blockedOn=t.tag===3?t.stateNode.containerInfo:null;return}}}r.blockedOn=null}function bl(r){if(r.blockedOn!==null)return!1;for(var e=r.targetContainers;0<e.length;){var t=Cd(r.domEventName,r.eventSystemFlags,e[0],r.nativeEvent);if(t===null){t=r.nativeEvent;var n=new t.constructor(t.type,t);pd=n,t.target.dispatchEvent(n),pd=null}else return e=za(t),e!==null&&Lh(e),r.blockedOn=t,!1;e.shift()}return!0}function _p(r,e,t){bl(r)&&t.delete(e)}function i2(){wd=!1,bi!==null&&bl(bi)&&(bi=null),Si!==null&&bl(Si)&&(Si=null),xi!==null&&bl(xi)&&(xi=null),ga.forEach(_p),ma.forEach(_p)}function Ro(r,e){r.blockedOn===e&&(r.blockedOn=null,wd||(wd=!0,Jr.unstable_scheduleCallback(Jr.unstable_NormalPriority,i2)))}function ya(r){function e(i){return Ro(i,r)}if(0<qa.length){Ro(qa[0],r);for(var t=1;t<qa.length;t++){var n=qa[t];n.blockedOn===r&&(n.blockedOn=null)}}for(bi!==null&&Ro(bi,r),Si!==null&&Ro(Si,r),xi!==null&&Ro(xi,r),ga.forEach(e),ma.forEach(e),t=0;t<yi.length;t++)n=yi[t],n.blockedOn===r&&(n.blockedOn=null);for(;0<yi.length&&(t=yi[0],t.blockedOn===null);)e0(t),t.blockedOn===null&&yi.shift()}var Ks=oi.ReactCurrentBatchConfig,$l=!0;function s2(r,e,t,n){var i=Xe,s=Ks.transition;Ks.transition=null;try{Xe=1,_h(r,e,t,n)}finally{Xe=i,Ks.transition=s}}function o2(r,e,t,n){var i=Xe,s=Ks.transition;Ks.transition=null;try{Xe=4,_h(r,e,t,n)}finally{Xe=i,Ks.transition=s}}function _h(r,e,t,n){if($l){var i=Cd(r,e,t,n);if(i===null)kc(r,e,n,Nl,t),Lp(r,n);else if(n2(i,r,e,t,n))n.stopPropagation();else if(Lp(r,n),e&4&&-1<r2.indexOf(r)){for(;i!==null;){var s=za(i);if(s!==null&&Zy(s),s=Cd(r,e,t,n),s===null&&kc(r,e,n,Nl,t),s===i)break;i=s}i!==null&&n.stopPropagation()}else kc(r,e,n,null,t)}}var Nl=null;function Cd(r,e,t,n){if(Nl=null,r=Oh(n),r=es(r),r!==null)if(e=fs(r),e===null)r=null;else if(t=e.tag,t===13){if(r=Vy(e),r!==null)return r;r=null}else if(t===3){if(e.stateNode.current.memoizedState.isDehydrated)return e.tag===3?e.stateNode.containerInfo:null;r=null}else e!==r&&(r=null);return Nl=r,null}function t0(r){switch(r){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(Gb()){case Dh:return 1;case Wy:return 4;case Ll:case Xb:return 16;case Gy:return 536870912;default:return 16}default:return 16}}var wi=null,$h=null,Sl=null;function r0(){if(Sl)return Sl;var r,e=$h,t=e.length,n,i="value"in wi?wi.value:wi.textContent,s=i.length;for(r=0;r<t&&e[r]===i[r];r++);var o=t-r;for(n=1;n<=o&&e[t-n]===i[s-n];n++);return Sl=i.slice(r,1<n?1-n:void 0)}function xl(r){var e=r.keyCode;return"charCode"in r?(r=r.charCode,r===0&&e===13&&(r=13)):r=e,r===10&&(r=13),32<=r||r===13?r:0}function Qa(){return!0}function $p(){return!1}function tn(r){function e(t,n,i,s,o){this._reactName=t,this._targetInst=i,this.type=n,this.nativeEvent=s,this.target=o,this.currentTarget=null;for(var a in r)r.hasOwnProperty(a)&&(t=r[a],this[a]=t?t(s):s[a]);return this.isDefaultPrevented=(s.defaultPrevented!=null?s.defaultPrevented:s.returnValue===!1)?Qa:$p,this.isPropagationStopped=$p,this}return It(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var t=this.nativeEvent;t&&(t.preventDefault?t.preventDefault():typeof t.returnValue!="unknown"&&(t.returnValue=!1),this.isDefaultPrevented=Qa)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=Qa)},persist:function(){},isPersistent:Qa}),e}var po={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Nh=tn(po),Ba=It({},po,{view:0,detail:0}),a2=tn(Ba),mc,yc,Po,pu=It({},Ba,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Vh,button:0,buttons:0,relatedTarget:function(r){return r.relatedTarget===void 0?r.fromElement===r.srcElement?r.toElement:r.fromElement:r.relatedTarget},movementX:function(r){return"movementX"in r?r.movementX:(r!==Po&&(Po&&r.type==="mousemove"?(mc=r.screenX-Po.screenX,yc=r.screenY-Po.screenY):yc=mc=0,Po=r),mc)},movementY:function(r){return"movementY"in r?r.movementY:yc}}),Np=tn(pu),l2=It({},pu,{dataTransfer:0}),u2=tn(l2),c2=It({},Ba,{relatedTarget:0}),vc=tn(c2),d2=It({},po,{animationName:0,elapsedTime:0,pseudoElement:0}),h2=tn(d2),f2=It({},po,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),p2=tn(f2),g2=It({},po,{data:0}),Vp=tn(g2),m2={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},y2={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},v2={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function w2(r){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(r):(r=v2[r])?!!e[r]:!1}function Vh(){return w2}var C2=It({},Ba,{key:function(r){if(r.key){var e=m2[r.key]||r.key;if(e!=="Unidentified")return e}return r.type==="keypress"?(r=xl(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?y2[r.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Vh,charCode:function(r){return r.type==="keypress"?xl(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?xl(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),b2=tn(C2),S2=It({},pu,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Hp=tn(S2),x2=It({},Ba,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Vh}),I2=tn(x2),k2=It({},po,{propertyName:0,elapsedTime:0,pseudoElement:0}),E2=tn(k2),M2=It({},pu,{deltaX:function(r){return"deltaX"in r?r.deltaX:"wheelDeltaX"in r?-r.wheelDeltaX:0},deltaY:function(r){return"deltaY"in r?r.deltaY:"wheelDeltaY"in r?-r.wheelDeltaY:"wheelDelta"in r?-r.wheelDelta:0},deltaZ:0,deltaMode:0}),U2=tn(M2),A2=[9,13,27,32],Hh=ri&&"CompositionEvent"in window,Jo=null;ri&&"documentMode"in document&&(Jo=document.documentMode);var T2=ri&&"TextEvent"in window&&!Jo,n0=ri&&(!Hh||Jo&&8<Jo&&11>=Jo),jp=" ",Yp=!1;function i0(r,e){switch(r){case"keyup":return A2.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function s0(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var zs=!1;function R2(r,e){switch(r){case"compositionend":return s0(e);case"keypress":return e.which!==32?null:(Yp=!0,jp);case"textInput":return r=e.data,r===jp&&Yp?null:r;default:return null}}function P2(r,e){if(zs)return r==="compositionend"||!Hh&&i0(r,e)?(r=r0(),Sl=$h=wi=null,zs=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1<e.char.length)return e.char;if(e.which)return String.fromCharCode(e.which)}return null;case"compositionend":return n0&&e.locale!=="ko"?null:e.data;default:return null}}var B2={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Wp(r){var e=r&&r.nodeName&&r.nodeName.toLowerCase();return e==="input"?!!B2[r.type]:e==="textarea"}function o0(r,e,t,n){Fy(n),e=Vl(e,"onChange"),0<e.length&&(t=new Nh("onChange","change",null,t,n),r.push({event:t,listeners:e}))}var ea=null,va=null;function z2(r){y0(r,0)}function gu(r){var e=Fs(r);if(Ty(e))return r}function O2(r,e){if(r==="change")return e}var a0=!1;if(ri){var wc;if(ri){var Cc="oninput"in document;if(!Cc){var Gp=document.createElement("div");Gp.setAttribute("oninput","return;"),Cc=typeof Gp.oninput=="function"}wc=Cc}else wc=!1;a0=wc&&(!document.documentMode||9<document.documentMode)}function Xp(){ea&&(ea.detachEvent("onpropertychange",l0),va=ea=null)}function l0(r){if(r.propertyName==="value"&&gu(va)){var e=[];o0(e,va,r,Oh(r)),Ny(z2,e)}}function D2(r,e,t){r==="focusin"?(Xp(),ea=e,va=t,ea.attachEvent("onpropertychange",l0)):r==="focusout"&&Xp()}function F2(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return gu(va)}function L2(r,e){if(r==="click")return gu(e)}function _2(r,e){if(r==="input"||r==="change")return gu(e)}function $2(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var An=typeof Object.is=="function"?Object.is:$2;function wa(r,e){if(An(r,e))return!0;if(typeof r!="object"||r===null||typeof e!="object"||e===null)return!1;var t=Object.keys(r),n=Object.keys(e);if(t.length!==n.length)return!1;for(n=0;n<t.length;n++){var i=t[n];if(!rd.call(e,i)||!An(r[i],e[i]))return!1}return!0}function Kp(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function Zp(r,e){var t=Kp(r);r=0;for(var n;t;){if(t.nodeType===3){if(n=r+t.textContent.length,r<=e&&n>=e)return{node:t,offset:e-r};r=n}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=Kp(t)}}function u0(r,e){return r&&e?r===e?!0:r&&r.nodeType===3?!1:e&&e.nodeType===3?u0(r,e.parentNode):"contains"in r?r.contains(e):r.compareDocumentPosition?!!(r.compareDocumentPosition(e)&16):!1:!1}function c0(){for(var r=window,e=Ol();e instanceof r.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)r=e.contentWindow;else break;e=Ol(r.document)}return e}function jh(r){var e=r&&r.nodeName&&r.nodeName.toLowerCase();return e&&(e==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||e==="textarea"||r.contentEditable==="true")}function N2(r){var e=c0(),t=r.focusedElem,n=r.selectionRange;if(e!==t&&t&&t.ownerDocument&&u0(t.ownerDocument.documentElement,t)){if(n!==null&&jh(t)){if(e=n.start,r=n.end,r===void 0&&(r=e),"selectionStart"in t)t.selectionStart=e,t.selectionEnd=Math.min(r,t.value.length);else if(r=(e=t.ownerDocument||document)&&e.defaultView||window,r.getSelection){r=r.getSelection();var i=t.textContent.length,s=Math.min(n.start,i);n=n.end===void 0?s:Math.min(n.end,i),!r.extend&&s>n&&(i=n,n=s,s=i),i=Zp(t,s);var o=Zp(t,n);i&&o&&(r.rangeCount!==1||r.anchorNode!==i.node||r.anchorOffset!==i.offset||r.focusNode!==o.node||r.focusOffset!==o.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),r.removeAllRanges(),s>n?(r.addRange(e),r.extend(o.node,o.offset)):(e.setEnd(o.node,o.offset),r.addRange(e)))}}for(e=[],r=t;r=r.parentNode;)r.nodeType===1&&e.push({element:r,left:r.scrollLeft,top:r.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t<e.length;t++)r=e[t],r.element.scrollLeft=r.left,r.element.scrollTop=r.top}}var V2=ri&&"documentMode"in document&&11>=document.documentMode,Os=null,bd=null,ta=null,Sd=!1;function qp(r,e,t){var n=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;Sd||Os==null||Os!==Ol(n)||(n=Os,"selectionStart"in n&&jh(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}),ta&&wa(ta,n)||(ta=n,n=Vl(bd,"onSelect"),0<n.length&&(e=new Nh("onSelect","select",null,e,t),r.push({event:e,listeners:n}),e.target=Os)))}function Ja(r,e){var t={};return t[r.toLowerCase()]=e.toLowerCase(),t["Webkit"+r]="webkit"+e,t["Moz"+r]="moz"+e,t}var Ds={animationend:Ja("Animation","AnimationEnd"),animationiteration:Ja("Animation","AnimationIteration"),animationstart:Ja("Animation","AnimationStart"),transitionend:Ja("Transition","TransitionEnd")},bc={},d0={};ri&&(d0=document.createElement("div").style,"AnimationEvent"in window||(delete Ds.animationend.animation,delete Ds.animationiteration.animation,delete Ds.animationstart.animation),"TransitionEvent"in window||delete Ds.transitionend.transition);function mu(r){if(bc[r])return bc[r];if(!Ds[r])return r;var e=Ds[r],t;for(t in e)if(e.hasOwnProperty(t)&&t in d0)return bc[r]=e[t];return r}var h0=mu("animationend"),f0=mu("animationiteration"),p0=mu("animationstart"),g0=mu("transitionend"),m0=new Map,Qp="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Oi(r,e){m0.set(r,e),hs(e,[r])}for(var Sc=0;Sc<Qp.length;Sc++){var xc=Qp[Sc],H2=xc.toLowerCase(),j2=xc[0].toUpperCase()+xc.slice(1);Oi(H2,"on"+j2)}Oi(h0,"onAnimationEnd");Oi(f0,"onAnimationIteration");Oi(p0,"onAnimationStart");Oi("dblclick","onDoubleClick");Oi("focusin","onFocus");Oi("focusout","onBlur");Oi(g0,"onTransitionEnd");eo("onMouseEnter",["mouseout","mouseover"]);eo("onMouseLeave",["mouseout","mouseover"]);eo("onPointerEnter",["pointerout","pointerover"]);eo("onPointerLeave",["pointerout","pointerover"]);hs("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));hs("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));hs("onBeforeInput",["compositionend","keypress","textInput","paste"]);hs("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));hs("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));hs("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var jo="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Y2=new Set("cancel close invalid load scroll toggle".split(" ").concat(jo));function Jp(r,e,t){var n=r.type||"unknown-event";r.currentTarget=t,Hb(n,e,void 0,r),r.currentTarget=null}function y0(r,e){e=(e&4)!==0;for(var t=0;t<r.length;t++){var n=r[t],i=n.event;n=n.listeners;e:{var s=void 0;if(e)for(var o=n.length-1;0<=o;o--){var a=n[o],l=a.instance,u=a.currentTarget;if(a=a.listener,l!==s&&i.isPropagationStopped())break e;Jp(i,a,u),s=l}else for(o=0;o<n.length;o++){if(a=n[o],l=a.instance,u=a.currentTarget,a=a.listener,l!==s&&i.isPropagationStopped())break e;Jp(i,a,u),s=l}}}if(Fl)throw r=yd,Fl=!1,yd=null,r}function at(r,e){var t=e[Md];t===void 0&&(t=e[Md]=new Set);var n=r+"__bubble";t.has(n)||(v0(e,r,2,!1),t.add(n))}function Ic(r,e,t){var n=0;e&&(n|=4),v0(t,r,n,e)}var el="_reactListening"+Math.random().toString(36).slice(2);function Ca(r){if(!r[el]){r[el]=!0,ky.forEach(function(t){t!=="selectionchange"&&(Y2.has(t)||Ic(t,!1,r),Ic(t,!0,r))});var e=r.nodeType===9?r:r.ownerDocument;e===null||e[el]||(e[el]=!0,Ic("selectionchange",!1,e))}}function v0(r,e,t,n){switch(t0(e)){case 1:var i=s2;break;case 4:i=o2;break;default:i=_h}t=i.bind(null,e,t,r),i=void 0,!md||e!=="touchstart"&&e!=="touchmove"&&e!=="wheel"||(i=!0),n?i!==void 0?r.addEventListener(e,t,{capture:!0,passive:i}):r.addEventListener(e,t,!0):i!==void 0?r.addEventListener(e,t,{passive:i}):r.addEventListener(e,t,!1)}function kc(r,e,t,n,i){var s=n;if(!(e&1)&&!(e&2)&&n!==null)e:for(;;){if(n===null)return;var o=n.tag;if(o===3||o===4){var a=n.stateNode.containerInfo;if(a===i||a.nodeType===8&&a.parentNode===i)break;if(o===4)for(o=n.return;o!==null;){var l=o.tag;if((l===3||l===4)&&(l=o.stateNode.containerInfo,l===i||l.nodeType===8&&l.parentNode===i))return;o=o.return}for(;a!==null;){if(o=es(a),o===null)return;if(l=o.tag,l===5||l===6){n=s=o;continue e}a=a.parentNode}}n=n.return}Ny(function(){var u=s,c=Oh(t),d=[];e:{var h=m0.get(r);if(h!==void 0){var f=Nh,p=r;switch(r){case"keypress":if(xl(t)===0)break e;case"keydown":case"keyup":f=b2;break;case"focusin":p="focus",f=vc;break;case"focusout":p="blur",f=vc;break;case"beforeblur":case"afterblur":f=vc;break;case"click":if(t.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":f=Np;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":f=u2;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":f=I2;break;case h0:case f0:case p0:f=h2;break;case g0:f=E2;break;case"scroll":f=a2;break;case"wheel":f=U2;break;case"copy":case"cut":case"paste":f=p2;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":f=Hp}var m=(e&4)!==0,S=!m&&r==="scroll",w=m?h!==null?h+"Capture":null:h;m=[];for(var g=u,y;g!==null;){y=g;var C=y.stateNode;if(y.tag===5&&C!==null&&(y=C,w!==null&&(C=pa(g,w),C!=null&&m.push(ba(g,C,y)))),S)break;g=g.return}0<m.length&&(h=new f(h,p,null,t,c),d.push({event:h,listeners:m}))}}if(!(e&7)){e:{if(h=r==="mouseover"||r==="pointerover",f=r==="mouseout"||r==="pointerout",h&&t!==pd&&(p=t.relatedTarget||t.fromElement)&&(es(p)||p[ni]))break e;if((f||h)&&(h=c.window===c?c:(h=c.ownerDocument)?h.defaultView||h.parentWindow:window,f?(p=t.relatedTarget||t.toElement,f=u,p=p?es(p):null,p!==null&&(S=fs(p),p!==S||p.tag!==5&&p.tag!==6)&&(p=null)):(f=null,p=u),f!==p)){if(m=Np,C="onMouseLeave",w="onMouseEnter",g="mouse",(r==="pointerout"||r==="pointerover")&&(m=Hp,C="onPointerLeave",w="onPointerEnter",g="pointer"),S=f==null?h:Fs(f),y=p==null?h:Fs(p),h=new m(C,g+"leave",f,t,c),h.target=S,h.relatedTarget=y,C=null,es(c)===u&&(m=new m(w,g+"enter",p,t,c),m.target=y,m.relatedTarget=S,C=m),S=C,f&&p)t:{for(m=f,w=p,g=0,y=m;y;y=Es(y))g++;for(y=0,C=w;C;C=Es(C))y++;for(;0<g-y;)m=Es(m),g--;for(;0<y-g;)w=Es(w),y--;for(;g--;){if(m===w||w!==null&&m===w.alternate)break t;m=Es(m),w=Es(w)}m=null}else m=null;f!==null&&eg(d,h,f,m,!1),p!==null&&S!==null&&eg(d,S,p,m,!0)}}e:{if(h=u?Fs(u):window,f=h.nodeName&&h.nodeName.toLowerCase(),f==="select"||f==="input"&&h.type==="file")var x=O2;else if(Wp(h))if(a0)x=_2;else{x=F2;var I=D2}else(f=h.nodeName)&&f.toLowerCase()==="input"&&(h.type==="checkbox"||h.type==="radio")&&(x=L2);if(x&&(x=x(r,u))){o0(d,x,t,c);break e}I&&I(r,h,u),r==="focusout"&&(I=h._wrapperState)&&I.controlled&&h.type==="number"&&ud(h,"number",h.value)}switch(I=u?Fs(u):window,r){case"focusin":(Wp(I)||I.contentEditable==="true")&&(Os=I,bd=u,ta=null);break;case"focusout":ta=bd=Os=null;break;case"mousedown":Sd=!0;break;case"contextmenu":case"mouseup":case"dragend":Sd=!1,qp(d,t,c);break;case"selectionchange":if(V2)break;case"keydown":case"keyup":qp(d,t,c)}var E;if(Hh)e:{switch(r){case"compositionstart":var A="onCompositionStart";break e;case"compositionend":A="onCompositionEnd";break e;case"compositionupdate":A="onCompositionUpdate";break e}A=void 0}else zs?i0(r,t)&&(A="onCompositionEnd"):r==="keydown"&&t.keyCode===229&&(A="onCompositionStart");A&&(n0&&t.locale!=="ko"&&(zs||A!=="onCompositionStart"?A==="onCompositionEnd"&&zs&&(E=r0()):(wi=c,$h="value"in wi?wi.value:wi.textContent,zs=!0)),I=Vl(u,A),0<I.length&&(A=new Vp(A,r,null,t,c),d.push({event:A,listeners:I}),E?A.data=E:(E=s0(t),E!==null&&(A.data=E)))),(E=T2?R2(r,t):P2(r,t))&&(u=Vl(u,"onBeforeInput"),0<u.length&&(c=new Vp("onBeforeInput","beforeinput",null,t,c),d.push({event:c,listeners:u}),c.data=E))}y0(d,e)})}function ba(r,e,t){return{instance:r,listener:e,currentTarget:t}}function Vl(r,e){for(var t=e+"Capture",n=[];r!==null;){var i=r,s=i.stateNode;i.tag===5&&s!==null&&(i=s,s=pa(r,t),s!=null&&n.unshift(ba(r,s,i)),s=pa(r,e),s!=null&&n.push(ba(r,s,i))),r=r.return}return n}function Es(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5);return r||null}function eg(r,e,t,n,i){for(var s=e._reactName,o=[];t!==null&&t!==n;){var a=t,l=a.alternate,u=a.stateNode;if(l!==null&&l===n)break;a.tag===5&&u!==null&&(a=u,i?(l=pa(t,s),l!=null&&o.unshift(ba(t,l,a))):i||(l=pa(t,s),l!=null&&o.push(ba(t,l,a)))),t=t.return}o.length!==0&&r.push({event:e,listeners:o})}var W2=/\r\n?/g,G2=/\u0000|\uFFFD/g;function tg(r){return(typeof r=="string"?r:""+r).replace(W2,`
|
|
38
|
+
`).replace(G2,"")}function tl(r,e,t){if(e=tg(e),tg(r)!==e&&t)throw Error(te(425))}function Hl(){}var xd=null,Id=null;function kd(r,e){return r==="textarea"||r==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var Ed=typeof setTimeout=="function"?setTimeout:void 0,X2=typeof clearTimeout=="function"?clearTimeout:void 0,rg=typeof Promise=="function"?Promise:void 0,K2=typeof queueMicrotask=="function"?queueMicrotask:typeof rg<"u"?function(r){return rg.resolve(null).then(r).catch(Z2)}:Ed;function Z2(r){setTimeout(function(){throw r})}function Ec(r,e){var t=e,n=0;do{var i=t.nextSibling;if(r.removeChild(t),i&&i.nodeType===8)if(t=i.data,t==="/$"){if(n===0){r.removeChild(i),ya(e);return}n--}else t!=="$"&&t!=="$?"&&t!=="$!"||n++;t=i}while(t);ya(e)}function Ii(r){for(;r!=null;r=r.nextSibling){var e=r.nodeType;if(e===1||e===3)break;if(e===8){if(e=r.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return r}function ng(r){r=r.previousSibling;for(var e=0;r;){if(r.nodeType===8){var t=r.data;if(t==="$"||t==="$!"||t==="$?"){if(e===0)return r;e--}else t==="/$"&&e++}r=r.previousSibling}return null}var go=Math.random().toString(36).slice(2),Nn="__reactFiber$"+go,Sa="__reactProps$"+go,ni="__reactContainer$"+go,Md="__reactEvents$"+go,q2="__reactListeners$"+go,Q2="__reactHandles$"+go;function es(r){var e=r[Nn];if(e)return e;for(var t=r.parentNode;t;){if(e=t[ni]||t[Nn]){if(t=e.alternate,e.child!==null||t!==null&&t.child!==null)for(r=ng(r);r!==null;){if(t=r[Nn])return t;r=ng(r)}return e}r=t,t=r.parentNode}return null}function za(r){return r=r[Nn]||r[ni],!r||r.tag!==5&&r.tag!==6&&r.tag!==13&&r.tag!==3?null:r}function Fs(r){if(r.tag===5||r.tag===6)return r.stateNode;throw Error(te(33))}function yu(r){return r[Sa]||null}var Ud=[],Ls=-1;function Di(r){return{current:r}}function ct(r){0>Ls||(r.current=Ud[Ls],Ud[Ls]=null,Ls--)}function rt(r,e){Ls++,Ud[Ls]=r.current,r.current=e}var Bi={},vr=Di(Bi),Lr=Di(!1),os=Bi;function to(r,e){var t=r.type.contextTypes;if(!t)return Bi;var n=r.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in t)i[s]=e[s];return n&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=e,r.__reactInternalMemoizedMaskedChildContext=i),i}function _r(r){return r=r.childContextTypes,r!=null}function jl(){ct(Lr),ct(vr)}function ig(r,e,t){if(vr.current!==Bi)throw Error(te(168));rt(vr,e),rt(Lr,t)}function w0(r,e,t){var n=r.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return t;n=n.getChildContext();for(var i in n)if(!(i in e))throw Error(te(108,Db(r)||"Unknown",i));return It({},t,n)}function Yl(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||Bi,os=vr.current,rt(vr,r),rt(Lr,Lr.current),!0}function sg(r,e,t){var n=r.stateNode;if(!n)throw Error(te(169));t?(r=w0(r,e,os),n.__reactInternalMemoizedMergedChildContext=r,ct(Lr),ct(vr),rt(vr,r)):ct(Lr),rt(Lr,t)}var Zn=null,vu=!1,Mc=!1;function C0(r){Zn===null?Zn=[r]:Zn.push(r)}function J2(r){vu=!0,C0(r)}function Fi(){if(!Mc&&Zn!==null){Mc=!0;var r=0,e=Xe;try{var t=Zn;for(Xe=1;r<t.length;r++){var n=t[r];do n=n(!0);while(n!==null)}Zn=null,vu=!1}catch(i){throw Zn!==null&&(Zn=Zn.slice(r+1)),Yy(Dh,Fi),i}finally{Xe=e,Mc=!1}}return null}var _s=[],$s=0,Wl=null,Gl=0,ln=[],un=0,as=null,qn=1,Qn="";function Gi(r,e){_s[$s++]=Gl,_s[$s++]=Wl,Wl=r,Gl=e}function b0(r,e,t){ln[un++]=qn,ln[un++]=Qn,ln[un++]=as,as=r;var n=qn;r=Qn;var i=32-Mn(n)-1;n&=~(1<<i),t+=1;var s=32-Mn(e)+i;if(30<s){var o=i-i%5;s=(n&(1<<o)-1).toString(32),n>>=o,i-=o,qn=1<<32-Mn(e)+i|t<<i|n,Qn=s+r}else qn=1<<s|t<<i|n,Qn=r}function Yh(r){r.return!==null&&(Gi(r,1),b0(r,1,0))}function Wh(r){for(;r===Wl;)Wl=_s[--$s],_s[$s]=null,Gl=_s[--$s],_s[$s]=null;for(;r===as;)as=ln[--un],ln[un]=null,Qn=ln[--un],ln[un]=null,qn=ln[--un],ln[un]=null}var qr=null,Zr=null,vt=!1,kn=null;function S0(r,e){var t=dn(5,null,null,0);t.elementType="DELETED",t.stateNode=e,t.return=r,e=r.deletions,e===null?(r.deletions=[t],r.flags|=16):e.push(t)}function og(r,e){switch(r.tag){case 5:var t=r.type;return e=e.nodeType!==1||t.toLowerCase()!==e.nodeName.toLowerCase()?null:e,e!==null?(r.stateNode=e,qr=r,Zr=Ii(e.firstChild),!0):!1;case 6:return e=r.pendingProps===""||e.nodeType!==3?null:e,e!==null?(r.stateNode=e,qr=r,Zr=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(t=as!==null?{id:qn,overflow:Qn}:null,r.memoizedState={dehydrated:e,treeContext:t,retryLane:1073741824},t=dn(18,null,null,0),t.stateNode=e,t.return=r,r.child=t,qr=r,Zr=null,!0):!1;default:return!1}}function Ad(r){return(r.mode&1)!==0&&(r.flags&128)===0}function Td(r){if(vt){var e=Zr;if(e){var t=e;if(!og(r,e)){if(Ad(r))throw Error(te(418));e=Ii(t.nextSibling);var n=qr;e&&og(r,e)?S0(n,t):(r.flags=r.flags&-4097|2,vt=!1,qr=r)}}else{if(Ad(r))throw Error(te(418));r.flags=r.flags&-4097|2,vt=!1,qr=r}}}function ag(r){for(r=r.return;r!==null&&r.tag!==5&&r.tag!==3&&r.tag!==13;)r=r.return;qr=r}function rl(r){if(r!==qr)return!1;if(!vt)return ag(r),vt=!0,!1;var e;if((e=r.tag!==3)&&!(e=r.tag!==5)&&(e=r.type,e=e!=="head"&&e!=="body"&&!kd(r.type,r.memoizedProps)),e&&(e=Zr)){if(Ad(r))throw x0(),Error(te(418));for(;e;)S0(r,e),e=Ii(e.nextSibling)}if(ag(r),r.tag===13){if(r=r.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(te(317));e:{for(r=r.nextSibling,e=0;r;){if(r.nodeType===8){var t=r.data;if(t==="/$"){if(e===0){Zr=Ii(r.nextSibling);break e}e--}else t!=="$"&&t!=="$!"&&t!=="$?"||e++}r=r.nextSibling}Zr=null}}else Zr=qr?Ii(r.stateNode.nextSibling):null;return!0}function x0(){for(var r=Zr;r;)r=Ii(r.nextSibling)}function ro(){Zr=qr=null,vt=!1}function Gh(r){kn===null?kn=[r]:kn.push(r)}var eS=oi.ReactCurrentBatchConfig;function Bo(r,e,t){if(r=t.ref,r!==null&&typeof r!="function"&&typeof r!="object"){if(t._owner){if(t=t._owner,t){if(t.tag!==1)throw Error(te(309));var n=t.stateNode}if(!n)throw Error(te(147,r));var i=n,s=""+r;return e!==null&&e.ref!==null&&typeof e.ref=="function"&&e.ref._stringRef===s?e.ref:(e=function(o){var a=i.refs;o===null?delete a[s]:a[s]=o},e._stringRef=s,e)}if(typeof r!="string")throw Error(te(284));if(!t._owner)throw Error(te(290,r))}return r}function nl(r,e){throw r=Object.prototype.toString.call(e),Error(te(31,r==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":r))}function lg(r){var e=r._init;return e(r._payload)}function I0(r){function e(w,g){if(r){var y=w.deletions;y===null?(w.deletions=[g],w.flags|=16):y.push(g)}}function t(w,g){if(!r)return null;for(;g!==null;)e(w,g),g=g.sibling;return null}function n(w,g){for(w=new Map;g!==null;)g.key!==null?w.set(g.key,g):w.set(g.index,g),g=g.sibling;return w}function i(w,g){return w=Ui(w,g),w.index=0,w.sibling=null,w}function s(w,g,y){return w.index=y,r?(y=w.alternate,y!==null?(y=y.index,y<g?(w.flags|=2,g):y):(w.flags|=2,g)):(w.flags|=1048576,g)}function o(w){return r&&w.alternate===null&&(w.flags|=2),w}function a(w,g,y,C){return g===null||g.tag!==6?(g=zc(y,w.mode,C),g.return=w,g):(g=i(g,y),g.return=w,g)}function l(w,g,y,C){var x=y.type;return x===Bs?c(w,g,y.props.children,C,y.key):g!==null&&(g.elementType===x||typeof x=="object"&&x!==null&&x.$$typeof===pi&&lg(x)===g.type)?(C=i(g,y.props),C.ref=Bo(w,g,y),C.return=w,C):(C=Tl(y.type,y.key,y.props,null,w.mode,C),C.ref=Bo(w,g,y),C.return=w,C)}function u(w,g,y,C){return g===null||g.tag!==4||g.stateNode.containerInfo!==y.containerInfo||g.stateNode.implementation!==y.implementation?(g=Oc(y,w.mode,C),g.return=w,g):(g=i(g,y.children||[]),g.return=w,g)}function c(w,g,y,C,x){return g===null||g.tag!==7?(g=is(y,w.mode,C,x),g.return=w,g):(g=i(g,y),g.return=w,g)}function d(w,g,y){if(typeof g=="string"&&g!==""||typeof g=="number")return g=zc(""+g,w.mode,y),g.return=w,g;if(typeof g=="object"&&g!==null){switch(g.$$typeof){case Wa:return y=Tl(g.type,g.key,g.props,null,w.mode,y),y.ref=Bo(w,null,g),y.return=w,y;case Ps:return g=Oc(g,w.mode,y),g.return=w,g;case pi:var C=g._init;return d(w,C(g._payload),y)}if(Vo(g)||Uo(g))return g=is(g,w.mode,y,null),g.return=w,g;nl(w,g)}return null}function h(w,g,y,C){var x=g!==null?g.key:null;if(typeof y=="string"&&y!==""||typeof y=="number")return x!==null?null:a(w,g,""+y,C);if(typeof y=="object"&&y!==null){switch(y.$$typeof){case Wa:return y.key===x?l(w,g,y,C):null;case Ps:return y.key===x?u(w,g,y,C):null;case pi:return x=y._init,h(w,g,x(y._payload),C)}if(Vo(y)||Uo(y))return x!==null?null:c(w,g,y,C,null);nl(w,y)}return null}function f(w,g,y,C,x){if(typeof C=="string"&&C!==""||typeof C=="number")return w=w.get(y)||null,a(g,w,""+C,x);if(typeof C=="object"&&C!==null){switch(C.$$typeof){case Wa:return w=w.get(C.key===null?y:C.key)||null,l(g,w,C,x);case Ps:return w=w.get(C.key===null?y:C.key)||null,u(g,w,C,x);case pi:var I=C._init;return f(w,g,y,I(C._payload),x)}if(Vo(C)||Uo(C))return w=w.get(y)||null,c(g,w,C,x,null);nl(g,C)}return null}function p(w,g,y,C){for(var x=null,I=null,E=g,A=g=0,R=null;E!==null&&A<y.length;A++){E.index>A?(R=E,E=null):R=E.sibling;var F=h(w,E,y[A],C);if(F===null){E===null&&(E=R);break}r&&E&&F.alternate===null&&e(w,E),g=s(F,g,A),I===null?x=F:I.sibling=F,I=F,E=R}if(A===y.length)return t(w,E),vt&&Gi(w,A),x;if(E===null){for(;A<y.length;A++)E=d(w,y[A],C),E!==null&&(g=s(E,g,A),I===null?x=E:I.sibling=E,I=E);return vt&&Gi(w,A),x}for(E=n(w,E);A<y.length;A++)R=f(E,w,A,y[A],C),R!==null&&(r&&R.alternate!==null&&E.delete(R.key===null?A:R.key),g=s(R,g,A),I===null?x=R:I.sibling=R,I=R);return r&&E.forEach(function(z){return e(w,z)}),vt&&Gi(w,A),x}function m(w,g,y,C){var x=Uo(y);if(typeof x!="function")throw Error(te(150));if(y=x.call(y),y==null)throw Error(te(151));for(var I=x=null,E=g,A=g=0,R=null,F=y.next();E!==null&&!F.done;A++,F=y.next()){E.index>A?(R=E,E=null):R=E.sibling;var z=h(w,E,F.value,C);if(z===null){E===null&&(E=R);break}r&&E&&z.alternate===null&&e(w,E),g=s(z,g,A),I===null?x=z:I.sibling=z,I=z,E=R}if(F.done)return t(w,E),vt&&Gi(w,A),x;if(E===null){for(;!F.done;A++,F=y.next())F=d(w,F.value,C),F!==null&&(g=s(F,g,A),I===null?x=F:I.sibling=F,I=F);return vt&&Gi(w,A),x}for(E=n(w,E);!F.done;A++,F=y.next())F=f(E,w,A,F.value,C),F!==null&&(r&&F.alternate!==null&&E.delete(F.key===null?A:F.key),g=s(F,g,A),I===null?x=F:I.sibling=F,I=F);return r&&E.forEach(function(P){return e(w,P)}),vt&&Gi(w,A),x}function S(w,g,y,C){if(typeof y=="object"&&y!==null&&y.type===Bs&&y.key===null&&(y=y.props.children),typeof y=="object"&&y!==null){switch(y.$$typeof){case Wa:e:{for(var x=y.key,I=g;I!==null;){if(I.key===x){if(x=y.type,x===Bs){if(I.tag===7){t(w,I.sibling),g=i(I,y.props.children),g.return=w,w=g;break e}}else if(I.elementType===x||typeof x=="object"&&x!==null&&x.$$typeof===pi&&lg(x)===I.type){t(w,I.sibling),g=i(I,y.props),g.ref=Bo(w,I,y),g.return=w,w=g;break e}t(w,I);break}else e(w,I);I=I.sibling}y.type===Bs?(g=is(y.props.children,w.mode,C,y.key),g.return=w,w=g):(C=Tl(y.type,y.key,y.props,null,w.mode,C),C.ref=Bo(w,g,y),C.return=w,w=C)}return o(w);case Ps:e:{for(I=y.key;g!==null;){if(g.key===I)if(g.tag===4&&g.stateNode.containerInfo===y.containerInfo&&g.stateNode.implementation===y.implementation){t(w,g.sibling),g=i(g,y.children||[]),g.return=w,w=g;break e}else{t(w,g);break}else e(w,g);g=g.sibling}g=Oc(y,w.mode,C),g.return=w,w=g}return o(w);case pi:return I=y._init,S(w,g,I(y._payload),C)}if(Vo(y))return p(w,g,y,C);if(Uo(y))return m(w,g,y,C);nl(w,y)}return typeof y=="string"&&y!==""||typeof y=="number"?(y=""+y,g!==null&&g.tag===6?(t(w,g.sibling),g=i(g,y),g.return=w,w=g):(t(w,g),g=zc(y,w.mode,C),g.return=w,w=g),o(w)):t(w,g)}return S}var no=I0(!0),k0=I0(!1),Xl=Di(null),Kl=null,Ns=null,Xh=null;function Kh(){Xh=Ns=Kl=null}function Zh(r){var e=Xl.current;ct(Xl),r._currentValue=e}function Rd(r,e,t){for(;r!==null;){var n=r.alternate;if((r.childLanes&e)!==e?(r.childLanes|=e,n!==null&&(n.childLanes|=e)):n!==null&&(n.childLanes&e)!==e&&(n.childLanes|=e),r===t)break;r=r.return}}function Zs(r,e){Kl=r,Xh=Ns=null,r=r.dependencies,r!==null&&r.firstContext!==null&&(r.lanes&e&&(Fr=!0),r.firstContext=null)}function fn(r){var e=r._currentValue;if(Xh!==r)if(r={context:r,memoizedValue:e,next:null},Ns===null){if(Kl===null)throw Error(te(308));Ns=r,Kl.dependencies={lanes:0,firstContext:r}}else Ns=Ns.next=r;return e}var ts=null;function qh(r){ts===null?ts=[r]:ts.push(r)}function E0(r,e,t,n){var i=e.interleaved;return i===null?(t.next=t,qh(e)):(t.next=i.next,i.next=t),e.interleaved=t,ii(r,n)}function ii(r,e){r.lanes|=e;var t=r.alternate;for(t!==null&&(t.lanes|=e),t=r,r=r.return;r!==null;)r.childLanes|=e,t=r.alternate,t!==null&&(t.childLanes|=e),t=r,r=r.return;return t.tag===3?t.stateNode:null}var gi=!1;function Qh(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function M0(r,e){r=r.updateQueue,e.updateQueue===r&&(e.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,effects:r.effects})}function Jn(r,e){return{eventTime:r,lane:e,tag:0,payload:null,callback:null,next:null}}function ki(r,e,t){var n=r.updateQueue;if(n===null)return null;if(n=n.shared,Oe&2){var i=n.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),n.pending=e,ii(r,t)}return i=n.interleaved,i===null?(e.next=e,qh(n)):(e.next=i.next,i.next=e),n.interleaved=e,ii(r,t)}function Il(r,e,t){if(e=e.updateQueue,e!==null&&(e=e.shared,(t&4194240)!==0)){var n=e.lanes;n&=r.pendingLanes,t|=n,e.lanes=t,Fh(r,t)}}function ug(r,e){var t=r.updateQueue,n=r.alternate;if(n!==null&&(n=n.updateQueue,t===n)){var i=null,s=null;if(t=t.firstBaseUpdate,t!==null){do{var o={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};s===null?i=s=o:s=s.next=o,t=t.next}while(t!==null);s===null?i=s=e:s=s.next=e}else i=s=e;t={baseState:n.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:n.shared,effects:n.effects},r.updateQueue=t;return}r=t.lastBaseUpdate,r===null?t.firstBaseUpdate=e:r.next=e,t.lastBaseUpdate=e}function Zl(r,e,t,n){var i=r.updateQueue;gi=!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=r.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 h=a.lane,f=a.eventTime;if((n&h)===h){c!==null&&(c=c.next={eventTime:f,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var p=r,m=a;switch(h=e,f=t,m.tag){case 1:if(p=m.payload,typeof p=="function"){d=p.call(f,d,h);break e}d=p;break e;case 3:p.flags=p.flags&-65537|128;case 0:if(p=m.payload,h=typeof p=="function"?p.call(f,d,h):p,h==null)break e;d=It({},d,h);break e;case 2:gi=!0}}a.callback!==null&&a.lane!==0&&(r.flags|=64,h=i.effects,h===null?i.effects=[a]:h.push(a))}else f={eventTime:f,lane:h,tag:a.tag,payload:a.payload,callback:a.callback,next:null},c===null?(u=c=f,l=d):c=c.next=f,o|=h;if(a=a.next,a===null){if(a=i.shared.pending,a===null)break;h=a,a=h.next,h.next=null,i.lastBaseUpdate=h,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);us|=o,r.lanes=o,r.memoizedState=d}}function cg(r,e,t){if(r=e.effects,e.effects=null,r!==null)for(e=0;e<r.length;e++){var n=r[e],i=n.callback;if(i!==null){if(n.callback=null,n=t,typeof i!="function")throw Error(te(191,i));i.call(n)}}}var Oa={},Hn=Di(Oa),xa=Di(Oa),Ia=Di(Oa);function rs(r){if(r===Oa)throw Error(te(174));return r}function Jh(r,e){switch(rt(Ia,e),rt(xa,r),rt(Hn,Oa),r=e.nodeType,r){case 9:case 11:e=(e=e.documentElement)?e.namespaceURI:dd(null,"");break;default:r=r===8?e.parentNode:e,e=r.namespaceURI||null,r=r.tagName,e=dd(e,r)}ct(Hn),rt(Hn,e)}function io(){ct(Hn),ct(xa),ct(Ia)}function U0(r){rs(Ia.current);var e=rs(Hn.current),t=dd(e,r.type);e!==t&&(rt(xa,r),rt(Hn,t))}function ef(r){xa.current===r&&(ct(Hn),ct(xa))}var St=Di(0);function ql(r){for(var e=r;e!==null;){if(e.tag===13){var t=e.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||t.data==="$?"||t.data==="$!"))return e}else if(e.tag===19&&e.memoizedProps.revealOrder!==void 0){if(e.flags&128)return e}else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===r)break;for(;e.sibling===null;){if(e.return===null||e.return===r)return null;e=e.return}e.sibling.return=e.return,e=e.sibling}return null}var Uc=[];function tf(){for(var r=0;r<Uc.length;r++)Uc[r]._workInProgressVersionPrimary=null;Uc.length=0}var kl=oi.ReactCurrentDispatcher,Ac=oi.ReactCurrentBatchConfig,ls=0,xt=null,Ht=null,rr=null,Ql=!1,ra=!1,ka=0,tS=0;function fr(){throw Error(te(321))}function rf(r,e){if(e===null)return!1;for(var t=0;t<e.length&&t<r.length;t++)if(!An(r[t],e[t]))return!1;return!0}function nf(r,e,t,n,i,s){if(ls=s,xt=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,kl.current=r===null||r.memoizedState===null?sS:oS,r=t(n,i),ra){s=0;do{if(ra=!1,ka=0,25<=s)throw Error(te(301));s+=1,rr=Ht=null,e.updateQueue=null,kl.current=aS,r=t(n,i)}while(ra)}if(kl.current=Jl,e=Ht!==null&&Ht.next!==null,ls=0,rr=Ht=xt=null,Ql=!1,e)throw Error(te(300));return r}function sf(){var r=ka!==0;return ka=0,r}function $n(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return rr===null?xt.memoizedState=rr=r:rr=rr.next=r,rr}function pn(){if(Ht===null){var r=xt.alternate;r=r!==null?r.memoizedState:null}else r=Ht.next;var e=rr===null?xt.memoizedState:rr.next;if(e!==null)rr=e,Ht=r;else{if(r===null)throw Error(te(310));Ht=r,r={memoizedState:Ht.memoizedState,baseState:Ht.baseState,baseQueue:Ht.baseQueue,queue:Ht.queue,next:null},rr===null?xt.memoizedState=rr=r:rr=rr.next=r}return rr}function Ea(r,e){return typeof e=="function"?e(r):e}function Tc(r){var e=pn(),t=e.queue;if(t===null)throw Error(te(311));t.lastRenderedReducer=r;var n=Ht,i=n.baseQueue,s=t.pending;if(s!==null){if(i!==null){var o=i.next;i.next=s.next,s.next=o}n.baseQueue=i=s,t.pending=null}if(i!==null){s=i.next,n=n.baseState;var a=o=null,l=null,u=s;do{var c=u.lane;if((ls&c)===c)l!==null&&(l=l.next={lane:0,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null}),n=u.hasEagerState?u.eagerState:r(n,u.action);else{var d={lane:c,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null};l===null?(a=l=d,o=n):l=l.next=d,xt.lanes|=c,us|=c}u=u.next}while(u!==null&&u!==s);l===null?o=n:l.next=a,An(n,e.memoizedState)||(Fr=!0),e.memoizedState=n,e.baseState=o,e.baseQueue=l,t.lastRenderedState=n}if(r=t.interleaved,r!==null){i=r;do s=i.lane,xt.lanes|=s,us|=s,i=i.next;while(i!==r)}else i===null&&(t.lanes=0);return[e.memoizedState,t.dispatch]}function Rc(r){var e=pn(),t=e.queue;if(t===null)throw Error(te(311));t.lastRenderedReducer=r;var n=t.dispatch,i=t.pending,s=e.memoizedState;if(i!==null){t.pending=null;var o=i=i.next;do s=r(s,o.action),o=o.next;while(o!==i);An(s,e.memoizedState)||(Fr=!0),e.memoizedState=s,e.baseQueue===null&&(e.baseState=s),t.lastRenderedState=s}return[s,n]}function A0(){}function T0(r,e){var t=xt,n=pn(),i=e(),s=!An(n.memoizedState,i);if(s&&(n.memoizedState=i,Fr=!0),n=n.queue,of(B0.bind(null,t,n,r),[r]),n.getSnapshot!==e||s||rr!==null&&rr.memoizedState.tag&1){if(t.flags|=2048,Ma(9,P0.bind(null,t,n,i,e),void 0,null),nr===null)throw Error(te(349));ls&30||R0(t,e,i)}return i}function R0(r,e,t){r.flags|=16384,r={getSnapshot:e,value:t},e=xt.updateQueue,e===null?(e={lastEffect:null,stores:null},xt.updateQueue=e,e.stores=[r]):(t=e.stores,t===null?e.stores=[r]:t.push(r))}function P0(r,e,t,n){e.value=t,e.getSnapshot=n,z0(e)&&O0(r)}function B0(r,e,t){return t(function(){z0(e)&&O0(r)})}function z0(r){var e=r.getSnapshot;r=r.value;try{var t=e();return!An(r,t)}catch{return!0}}function O0(r){var e=ii(r,1);e!==null&&Un(e,r,1,-1)}function dg(r){var e=$n();return typeof r=="function"&&(r=r()),e.memoizedState=e.baseState=r,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ea,lastRenderedState:r},e.queue=r,r=r.dispatch=iS.bind(null,xt,r),[e.memoizedState,r]}function Ma(r,e,t,n){return r={tag:r,create:e,destroy:t,deps:n,next:null},e=xt.updateQueue,e===null?(e={lastEffect:null,stores:null},xt.updateQueue=e,e.lastEffect=r.next=r):(t=e.lastEffect,t===null?e.lastEffect=r.next=r:(n=t.next,t.next=r,r.next=n,e.lastEffect=r)),r}function D0(){return pn().memoizedState}function El(r,e,t,n){var i=$n();xt.flags|=r,i.memoizedState=Ma(1|e,t,void 0,n===void 0?null:n)}function wu(r,e,t,n){var i=pn();n=n===void 0?null:n;var s=void 0;if(Ht!==null){var o=Ht.memoizedState;if(s=o.destroy,n!==null&&rf(n,o.deps)){i.memoizedState=Ma(e,t,s,n);return}}xt.flags|=r,i.memoizedState=Ma(1|e,t,s,n)}function hg(r,e){return El(8390656,8,r,e)}function of(r,e){return wu(2048,8,r,e)}function F0(r,e){return wu(4,2,r,e)}function L0(r,e){return wu(4,4,r,e)}function _0(r,e){if(typeof e=="function")return r=r(),e(r),function(){e(null)};if(e!=null)return r=r(),e.current=r,function(){e.current=null}}function $0(r,e,t){return t=t!=null?t.concat([r]):null,wu(4,4,_0.bind(null,e,r),t)}function af(){}function N0(r,e){var t=pn();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&rf(e,n[1])?n[0]:(t.memoizedState=[r,e],r)}function V0(r,e){var t=pn();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&rf(e,n[1])?n[0]:(r=r(),t.memoizedState=[r,e],r)}function H0(r,e,t){return ls&21?(An(t,e)||(t=Xy(),xt.lanes|=t,us|=t,r.baseState=!0),e):(r.baseState&&(r.baseState=!1,Fr=!0),r.memoizedState=t)}function rS(r,e){var t=Xe;Xe=t!==0&&4>t?t:4,r(!0);var n=Ac.transition;Ac.transition={};try{r(!1),e()}finally{Xe=t,Ac.transition=n}}function j0(){return pn().memoizedState}function nS(r,e,t){var n=Mi(r);if(t={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null},Y0(r))W0(e,t);else if(t=E0(r,e,t,n),t!==null){var i=Ur();Un(t,r,n,i),G0(t,e,n)}}function iS(r,e,t){var n=Mi(r),i={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null};if(Y0(r))W0(e,i);else{var s=r.alternate;if(r.lanes===0&&(s===null||s.lanes===0)&&(s=e.lastRenderedReducer,s!==null))try{var o=e.lastRenderedState,a=s(o,t);if(i.hasEagerState=!0,i.eagerState=a,An(a,o)){var l=e.interleaved;l===null?(i.next=i,qh(e)):(i.next=l.next,l.next=i),e.interleaved=i;return}}catch{}finally{}t=E0(r,e,i,n),t!==null&&(i=Ur(),Un(t,r,n,i),G0(t,e,n))}}function Y0(r){var e=r.alternate;return r===xt||e!==null&&e===xt}function W0(r,e){ra=Ql=!0;var t=r.pending;t===null?e.next=e:(e.next=t.next,t.next=e),r.pending=e}function G0(r,e,t){if(t&4194240){var n=e.lanes;n&=r.pendingLanes,t|=n,e.lanes=t,Fh(r,t)}}var Jl={readContext:fn,useCallback:fr,useContext:fr,useEffect:fr,useImperativeHandle:fr,useInsertionEffect:fr,useLayoutEffect:fr,useMemo:fr,useReducer:fr,useRef:fr,useState:fr,useDebugValue:fr,useDeferredValue:fr,useTransition:fr,useMutableSource:fr,useSyncExternalStore:fr,useId:fr,unstable_isNewReconciler:!1},sS={readContext:fn,useCallback:function(r,e){return $n().memoizedState=[r,e===void 0?null:e],r},useContext:fn,useEffect:hg,useImperativeHandle:function(r,e,t){return t=t!=null?t.concat([r]):null,El(4194308,4,_0.bind(null,e,r),t)},useLayoutEffect:function(r,e){return El(4194308,4,r,e)},useInsertionEffect:function(r,e){return El(4,2,r,e)},useMemo:function(r,e){var t=$n();return e=e===void 0?null:e,r=r(),t.memoizedState=[r,e],r},useReducer:function(r,e,t){var n=$n();return e=t!==void 0?t(e):e,n.memoizedState=n.baseState=e,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:e},n.queue=r,r=r.dispatch=nS.bind(null,xt,r),[n.memoizedState,r]},useRef:function(r){var e=$n();return r={current:r},e.memoizedState=r},useState:dg,useDebugValue:af,useDeferredValue:function(r){return $n().memoizedState=r},useTransition:function(){var r=dg(!1),e=r[0];return r=rS.bind(null,r[1]),$n().memoizedState=r,[e,r]},useMutableSource:function(){},useSyncExternalStore:function(r,e,t){var n=xt,i=$n();if(vt){if(t===void 0)throw Error(te(407));t=t()}else{if(t=e(),nr===null)throw Error(te(349));ls&30||R0(n,e,t)}i.memoizedState=t;var s={value:t,getSnapshot:e};return i.queue=s,hg(B0.bind(null,n,s,r),[r]),n.flags|=2048,Ma(9,P0.bind(null,n,s,t,e),void 0,null),t},useId:function(){var r=$n(),e=nr.identifierPrefix;if(vt){var t=Qn,n=qn;t=(n&~(1<<32-Mn(n)-1)).toString(32)+t,e=":"+e+"R"+t,t=ka++,0<t&&(e+="H"+t.toString(32)),e+=":"}else t=tS++,e=":"+e+"r"+t.toString(32)+":";return r.memoizedState=e},unstable_isNewReconciler:!1},oS={readContext:fn,useCallback:N0,useContext:fn,useEffect:of,useImperativeHandle:$0,useInsertionEffect:F0,useLayoutEffect:L0,useMemo:V0,useReducer:Tc,useRef:D0,useState:function(){return Tc(Ea)},useDebugValue:af,useDeferredValue:function(r){var e=pn();return H0(e,Ht.memoizedState,r)},useTransition:function(){var r=Tc(Ea)[0],e=pn().memoizedState;return[r,e]},useMutableSource:A0,useSyncExternalStore:T0,useId:j0,unstable_isNewReconciler:!1},aS={readContext:fn,useCallback:N0,useContext:fn,useEffect:of,useImperativeHandle:$0,useInsertionEffect:F0,useLayoutEffect:L0,useMemo:V0,useReducer:Rc,useRef:D0,useState:function(){return Rc(Ea)},useDebugValue:af,useDeferredValue:function(r){var e=pn();return Ht===null?e.memoizedState=r:H0(e,Ht.memoizedState,r)},useTransition:function(){var r=Rc(Ea)[0],e=pn().memoizedState;return[r,e]},useMutableSource:A0,useSyncExternalStore:T0,useId:j0,unstable_isNewReconciler:!1};function bn(r,e){if(r&&r.defaultProps){e=It({},e),r=r.defaultProps;for(var t in r)e[t]===void 0&&(e[t]=r[t]);return e}return e}function Pd(r,e,t,n){e=r.memoizedState,t=t(n,e),t=t==null?e:It({},e,t),r.memoizedState=t,r.lanes===0&&(r.updateQueue.baseState=t)}var Cu={isMounted:function(r){return(r=r._reactInternals)?fs(r)===r:!1},enqueueSetState:function(r,e,t){r=r._reactInternals;var n=Ur(),i=Mi(r),s=Jn(n,i);s.payload=e,t!=null&&(s.callback=t),e=ki(r,s,i),e!==null&&(Un(e,r,i,n),Il(e,r,i))},enqueueReplaceState:function(r,e,t){r=r._reactInternals;var n=Ur(),i=Mi(r),s=Jn(n,i);s.tag=1,s.payload=e,t!=null&&(s.callback=t),e=ki(r,s,i),e!==null&&(Un(e,r,i,n),Il(e,r,i))},enqueueForceUpdate:function(r,e){r=r._reactInternals;var t=Ur(),n=Mi(r),i=Jn(t,n);i.tag=2,e!=null&&(i.callback=e),e=ki(r,i,n),e!==null&&(Un(e,r,n,t),Il(e,r,n))}};function fg(r,e,t,n,i,s,o){return r=r.stateNode,typeof r.shouldComponentUpdate=="function"?r.shouldComponentUpdate(n,s,o):e.prototype&&e.prototype.isPureReactComponent?!wa(t,n)||!wa(i,s):!0}function X0(r,e,t){var n=!1,i=Bi,s=e.contextType;return typeof s=="object"&&s!==null?s=fn(s):(i=_r(e)?os:vr.current,n=e.contextTypes,s=(n=n!=null)?to(r,i):Bi),e=new e(t,s),r.memoizedState=e.state!==null&&e.state!==void 0?e.state:null,e.updater=Cu,r.stateNode=e,e._reactInternals=r,n&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=i,r.__reactInternalMemoizedMaskedChildContext=s),e}function pg(r,e,t,n){r=e.state,typeof e.componentWillReceiveProps=="function"&&e.componentWillReceiveProps(t,n),typeof e.UNSAFE_componentWillReceiveProps=="function"&&e.UNSAFE_componentWillReceiveProps(t,n),e.state!==r&&Cu.enqueueReplaceState(e,e.state,null)}function Bd(r,e,t,n){var i=r.stateNode;i.props=t,i.state=r.memoizedState,i.refs={},Qh(r);var s=e.contextType;typeof s=="object"&&s!==null?i.context=fn(s):(s=_r(e)?os:vr.current,i.context=to(r,s)),i.state=r.memoizedState,s=e.getDerivedStateFromProps,typeof s=="function"&&(Pd(r,e,s,t),i.state=r.memoizedState),typeof e.getDerivedStateFromProps=="function"||typeof i.getSnapshotBeforeUpdate=="function"||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(e=i.state,typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount(),e!==i.state&&Cu.enqueueReplaceState(i,i.state,null),Zl(r,t,i,n),i.state=r.memoizedState),typeof i.componentDidMount=="function"&&(r.flags|=4194308)}function so(r,e){try{var t="",n=e;do t+=Ob(n),n=n.return;while(n);var i=t}catch(s){i=`
|
|
39
39
|
Error generating stack: `+s.message+`
|
|
40
|
-
`+s.stack}return{value:r,source:e,stack:i,digest:null}}function Pc(r,e,t){return{value:r,source:null,stack:t??null,digest:e??null}}function zd(r,e){try{console.error(e.value)}catch(t){setTimeout(function(){throw t})}}var lS=typeof WeakMap=="function"?WeakMap:Map;function K0(r,e,t){t=Jn(-1,t),t.tag=3,t.payload={element:null};var n=e.value;return t.callback=function(){tu||(tu=!0,jd=n),zd(r,e)},t}function Z0(r,e,t){t=Jn(-1,t),t.tag=3;var n=r.type.getDerivedStateFromError;if(typeof n=="function"){var i=e.value;t.payload=function(){return n(i)},t.callback=function(){zd(r,e)}}var s=r.stateNode;return s!==null&&typeof s.componentDidCatch=="function"&&(t.callback=function(){zd(r,e),typeof n!="function"&&(Ei===null?Ei=new Set([this]):Ei.add(this));var o=e.stack;this.componentDidCatch(e.value,{componentStack:o!==null?o:""})}),t}function gg(r,e,t){var n=r.pingCache;if(n===null){n=r.pingCache=new lS;var i=new Set;n.set(e,i)}else i=n.get(e),i===void 0&&(i=new Set,n.set(e,i));i.has(t)||(i.add(t),r=SS.bind(null,r,e,t),e.then(r,r))}function mg(r){do{var e;if((e=r.tag===13)&&(e=r.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return r;r=r.return}while(r!==null);return null}function yg(r,e,t,n,i){return r.mode&1?(r.flags|=65536,r.lanes=i,r):(r===e?r.flags|=65536:(r.flags|=128,t.flags|=131072,t.flags&=-52805,t.tag===1&&(t.alternate===null?t.tag=17:(e=Jn(-1,1),e.tag=2,ki(t,e,1))),t.lanes|=1),r)}var uS=oi.ReactCurrentOwner,Fr=!1;function kr(r,e,t,n){e.child=r===null?k0(e,null,t,n):no(e,r.child,t,n)}function vg(r,e,t,n,i){t=t.render;var s=e.ref;return Zs(e,i),n=nf(r,e,t,n,s,i),t=sf(),r!==null&&!Fr?(e.updateQueue=r.updateQueue,e.flags&=-2053,r.lanes&=~i,si(r,e,i)):(vt&&t&&Yh(e),e.flags|=1,kr(r,e,n,i),e.child)}function wg(r,e,t,n,i){if(r===null){var s=t.type;return typeof s=="function"&&!gf(s)&&s.defaultProps===void 0&&t.compare===null&&t.defaultProps===void 0?(e.tag=15,e.type=s,q0(r,e,s,n,i)):(r=Tl(t.type,null,n,e,e.mode,i),r.ref=e.ref,r.return=e,e.child=r)}if(s=r.child,!(r.lanes&i)){var o=s.memoizedProps;if(t=t.compare,t=t!==null?t:wa,t(o,n)&&r.ref===e.ref)return si(r,e,i)}return e.flags|=1,r=Ui(s,n),r.ref=e.ref,r.return=e,e.child=r}function q0(r,e,t,n,i){if(r!==null){var s=r.memoizedProps;if(wa(s,n)&&r.ref===e.ref)if(Fr=!1,e.pendingProps=n=s,(r.lanes&i)!==0)r.flags&131072&&(Fr=!0);else return e.lanes=r.lanes,si(r,e,i)}return Dd(r,e,t,n,i)}function Q0(r,e,t){var n=e.pendingProps,i=n.children,s=r!==null?r.memoizedState:null;if(n.mode==="hidden")if(!(e.mode&1))e.memoizedState={baseLanes:0,cachePool:null,transitions:null},rt(Hs,Gr),Gr|=t;else{if(!(t&1073741824))return r=s!==null?s.baseLanes|t:t,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:r,cachePool:null,transitions:null},e.updateQueue=null,rt(Hs,Gr),Gr|=r,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=s!==null?s.baseLanes:t,rt(Hs,Gr),Gr|=n}else s!==null?(n=s.baseLanes|t,e.memoizedState=null):n=t,rt(Hs,Gr),Gr|=n;return kr(r,e,i,t),e.child}function J0(r,e){var t=e.ref;(r===null&&t!==null||r!==null&&r.ref!==t)&&(e.flags|=512,e.flags|=2097152)}function Dd(r,e,t,n,i){var s=_r(t)?os:vr.current;return s=to(e,s),Zs(e,i),t=nf(r,e,t,n,s,i),n=sf(),r!==null&&!Fr?(e.updateQueue=r.updateQueue,e.flags&=-2053,r.lanes&=~i,si(r,e,i)):(vt&&n&&Yh(e),e.flags|=1,kr(r,e,t,i),e.child)}function Cg(r,e,t,n,i){if(_r(t)){var s=!0;Yl(e)}else s=!1;if(Zs(e,i),e.stateNode===null)Ml(r,e),X0(e,t,n),Bd(e,t,n,i),n=!0;else if(r===null){var o=e.stateNode,a=e.memoizedProps;o.props=a;var l=o.context,u=t.contextType;typeof u=="object"&&u!==null?u=fn(u):(u=_r(t)?os:vr.current,u=to(e,u));var c=t.getDerivedStateFromProps,d=typeof c=="function"||typeof o.getSnapshotBeforeUpdate=="function";d||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==n||l!==u)&&pg(e,o,n,u),gi=!1;var h=e.memoizedState;o.state=h,Zl(e,n,o,i),l=e.memoizedState,a!==n||h!==l||Lr.current||gi?(typeof c=="function"&&(Pd(e,t,c,n),l=e.memoizedState),(a=gi||fg(e,t,a,n,h,l,u))?(d||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount=="function"&&(e.flags|=4194308)):(typeof o.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=n,e.memoizedState=l),o.props=n,o.state=l,o.context=u,n=a):(typeof o.componentDidMount=="function"&&(e.flags|=4194308),n=!1)}else{o=e.stateNode,M0(r,e),a=e.memoizedProps,u=e.type===e.elementType?a:bn(e.type,a),o.props=u,d=e.pendingProps,h=o.context,l=t.contextType,typeof l=="object"&&l!==null?l=fn(l):(l=_r(t)?os:vr.current,l=to(e,l));var f=t.getDerivedStateFromProps;(c=typeof f=="function"||typeof o.getSnapshotBeforeUpdate=="function")||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==d||h!==l)&&pg(e,o,n,l),gi=!1,h=e.memoizedState,o.state=h,Zl(e,n,o,i);var p=e.memoizedState;a!==d||h!==p||Lr.current||gi?(typeof f=="function"&&(Pd(e,t,f,n),p=e.memoizedState),(u=gi||fg(e,t,u,n,h,p,l)||!1)?(c||typeof o.UNSAFE_componentWillUpdate!="function"&&typeof o.componentWillUpdate!="function"||(typeof o.componentWillUpdate=="function"&&o.componentWillUpdate(n,p,l),typeof o.UNSAFE_componentWillUpdate=="function"&&o.UNSAFE_componentWillUpdate(n,p,l)),typeof o.componentDidUpdate=="function"&&(e.flags|=4),typeof o.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof o.componentDidUpdate!="function"||a===r.memoizedProps&&h===r.memoizedState||(e.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||a===r.memoizedProps&&h===r.memoizedState||(e.flags|=1024),e.memoizedProps=n,e.memoizedState=p),o.props=n,o.state=p,o.context=l,n=u):(typeof o.componentDidUpdate!="function"||a===r.memoizedProps&&h===r.memoizedState||(e.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||a===r.memoizedProps&&h===r.memoizedState||(e.flags|=1024),n=!1)}return Od(r,e,t,n,s,i)}function Od(r,e,t,n,i,s){J0(r,e);var o=(e.flags&128)!==0;if(!n&&!o)return i&&sg(e,t,!1),si(r,e,s);n=e.stateNode,uS.current=e;var a=o&&typeof t.getDerivedStateFromError!="function"?null:n.render();return e.flags|=1,r!==null&&o?(e.child=no(e,r.child,null,s),e.child=no(e,null,a,s)):kr(r,e,a,s),e.memoizedState=n.state,i&&sg(e,t,!0),e.child}function e1(r){var e=r.stateNode;e.pendingContext?ig(r,e.pendingContext,e.pendingContext!==e.context):e.context&&ig(r,e.context,!1),Jh(r,e.containerInfo)}function bg(r,e,t,n,i){return ro(),Gh(i),e.flags|=256,kr(r,e,t,n),e.child}var Fd={dehydrated:null,treeContext:null,retryLane:0};function Ld(r){return{baseLanes:r,cachePool:null,transitions:null}}function t1(r,e,t){var n=e.pendingProps,i=St.current,s=!1,o=(e.flags&128)!==0,a;if((a=o)||(a=r!==null&&r.memoizedState===null?!1:(i&2)!==0),a?(s=!0,e.flags&=-129):(r===null||r.memoizedState!==null)&&(i|=1),rt(St,i&1),r===null)return Td(e),r=e.memoizedState,r!==null&&(r=r.dehydrated,r!==null)?(e.mode&1?r.data==="$!"?e.lanes=8:e.lanes=1073741824:e.lanes=1,null):(o=n.children,r=n.fallback,s?(n=e.mode,s=e.child,o={mode:"hidden",children:o},!(n&1)&&s!==null?(s.childLanes=0,s.pendingProps=o):s=xu(o,n,0,null),r=is(r,n,t,null),s.return=e,r.return=e,s.sibling=r,e.child=s,e.child.memoizedState=Ld(t),e.memoizedState=Fd,r):lf(e,o));if(i=r.memoizedState,i!==null&&(a=i.dehydrated,a!==null))return cS(r,e,o,n,a,i,t);if(s){s=n.fallback,o=e.mode,i=r.child,a=i.sibling;var l={mode:"hidden",children:n.children};return!(o&1)&&e.child!==i?(n=e.child,n.childLanes=0,n.pendingProps=l,e.deletions=null):(n=Ui(i,l),n.subtreeFlags=i.subtreeFlags&14680064),a!==null?s=Ui(a,s):(s=is(s,o,t,null),s.flags|=2),s.return=e,n.return=e,n.sibling=s,e.child=n,n=s,s=e.child,o=r.child.memoizedState,o=o===null?Ld(t):{baseLanes:o.baseLanes|t,cachePool:null,transitions:o.transitions},s.memoizedState=o,s.childLanes=r.childLanes&~t,e.memoizedState=Fd,n}return s=r.child,r=s.sibling,n=Ui(s,{mode:"visible",children:n.children}),!(e.mode&1)&&(n.lanes=t),n.return=e,n.sibling=null,r!==null&&(t=e.deletions,t===null?(e.deletions=[r],e.flags|=16):t.push(r)),e.child=n,e.memoizedState=null,n}function lf(r,e){return e=xu({mode:"visible",children:e},r.mode,0,null),e.return=r,r.child=e}function il(r,e,t,n){return n!==null&&Gh(n),no(e,r.child,null,t),r=lf(e,e.pendingProps.children),r.flags|=2,e.memoizedState=null,r}function cS(r,e,t,n,i,s,o){if(t)return e.flags&256?(e.flags&=-257,n=Pc(Error(te(422))),il(r,e,o,n)):e.memoizedState!==null?(e.child=r.child,e.flags|=128,null):(s=n.fallback,i=e.mode,n=xu({mode:"visible",children:n.children},i,0,null),s=is(s,i,o,null),s.flags|=2,n.return=e,s.return=e,n.sibling=s,e.child=n,e.mode&1&&no(e,r.child,null,o),e.child.memoizedState=Ld(o),e.memoizedState=Fd,s);if(!(e.mode&1))return il(r,e,o,null);if(i.data==="$!"){if(n=i.nextSibling&&i.nextSibling.dataset,n)var a=n.dgst;return n=a,s=Error(te(419)),n=Pc(s,n,void 0),il(r,e,o,n)}if(a=(o&r.childLanes)!==0,Fr||a){if(n=nr,n!==null){switch(o&-o){case 4:i=2;break;case 16:i=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}i=i&(n.suspendedLanes|o)?0:i,i!==0&&i!==s.retryLane&&(s.retryLane=i,ii(r,i),Un(n,r,i,-1))}return pf(),n=Pc(Error(te(421))),il(r,e,o,n)}return i.data==="$?"?(e.flags|=128,e.child=r.child,e=xS.bind(null,r),i._reactRetry=e,null):(r=s.treeContext,Zr=Ii(i.nextSibling),qr=e,vt=!0,kn=null,r!==null&&(ln[un++]=qn,ln[un++]=Qn,ln[un++]=as,qn=r.id,Qn=r.overflow,as=e),e=lf(e,n.children),e.flags|=4096,e)}function Sg(r,e,t){r.lanes|=e;var n=r.alternate;n!==null&&(n.lanes|=e),Rd(r.return,e,t)}function Bc(r,e,t,n,i){var s=r.memoizedState;s===null?r.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:n,tail:t,tailMode:i}:(s.isBackwards=e,s.rendering=null,s.renderingStartTime=0,s.last=n,s.tail=t,s.tailMode=i)}function r1(r,e,t){var n=e.pendingProps,i=n.revealOrder,s=n.tail;if(kr(r,e,n.children,t),n=St.current,n&2)n=n&1|2,e.flags|=128;else{if(r!==null&&r.flags&128)e:for(r=e.child;r!==null;){if(r.tag===13)r.memoizedState!==null&&Sg(r,t,e);else if(r.tag===19)Sg(r,t,e);else if(r.child!==null){r.child.return=r,r=r.child;continue}if(r===e)break e;for(;r.sibling===null;){if(r.return===null||r.return===e)break e;r=r.return}r.sibling.return=r.return,r=r.sibling}n&=1}if(rt(St,n),!(e.mode&1))e.memoizedState=null;else switch(i){case"forwards":for(t=e.child,i=null;t!==null;)r=t.alternate,r!==null&&ql(r)===null&&(i=t),t=t.sibling;t=i,t===null?(i=e.child,e.child=null):(i=t.sibling,t.sibling=null),Bc(e,!1,i,t,s);break;case"backwards":for(t=null,i=e.child,e.child=null;i!==null;){if(r=i.alternate,r!==null&&ql(r)===null){e.child=i;break}r=i.sibling,i.sibling=t,t=i,i=r}Bc(e,!0,t,null,s);break;case"together":Bc(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function Ml(r,e){!(e.mode&1)&&r!==null&&(r.alternate=null,e.alternate=null,e.flags|=2)}function si(r,e,t){if(r!==null&&(e.dependencies=r.dependencies),us|=e.lanes,!(t&e.childLanes))return null;if(r!==null&&e.child!==r.child)throw Error(te(153));if(e.child!==null){for(r=e.child,t=Ui(r,r.pendingProps),e.child=t,t.return=e;r.sibling!==null;)r=r.sibling,t=t.sibling=Ui(r,r.pendingProps),t.return=e;t.sibling=null}return e.child}function dS(r,e,t){switch(e.tag){case 3:e1(e),ro();break;case 5:U0(e);break;case 1:_r(e.type)&&Yl(e);break;case 4:Jh(e,e.stateNode.containerInfo);break;case 10:var n=e.type._context,i=e.memoizedProps.value;rt(Xl,n._currentValue),n._currentValue=i;break;case 13:if(n=e.memoizedState,n!==null)return n.dehydrated!==null?(rt(St,St.current&1),e.flags|=128,null):t&e.child.childLanes?t1(r,e,t):(rt(St,St.current&1),r=si(r,e,t),r!==null?r.sibling:null);rt(St,St.current&1);break;case 19:if(n=(t&e.childLanes)!==0,r.flags&128){if(n)return r1(r,e,t);e.flags|=128}if(i=e.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),rt(St,St.current),n)break;return null;case 22:case 23:return e.lanes=0,Q0(r,e,t)}return si(r,e,t)}var n1,_d,i1,s1;n1=function(r,e){for(var t=e.child;t!==null;){if(t.tag===5||t.tag===6)r.appendChild(t.stateNode);else if(t.tag!==4&&t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return;t=t.return}t.sibling.return=t.return,t=t.sibling}};_d=function(){};i1=function(r,e,t,n){var i=r.memoizedProps;if(i!==n){r=e.stateNode,rs(Hn.current);var s=null;switch(t){case"input":i=ad(r,i),n=ad(r,n),s=[];break;case"select":i=It({},i,{value:void 0}),n=It({},n,{value:void 0}),s=[];break;case"textarea":i=cd(r,i),n=cd(r,n),s=[];break;default:typeof i.onClick!="function"&&typeof n.onClick=="function"&&(r.onclick=Hl)}hd(t,n);var o;t=null;for(u in i)if(!n.hasOwnProperty(u)&&i.hasOwnProperty(u)&&i[u]!=null)if(u==="style"){var a=i[u];for(o in a)a.hasOwnProperty(o)&&(t||(t={}),t[o]="")}else u!=="dangerouslySetInnerHTML"&&u!=="children"&&u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&u!=="autoFocus"&&(ha.hasOwnProperty(u)?s||(s=[]):(s=s||[]).push(u,null));for(u in n){var l=n[u];if(a=i!=null?i[u]:void 0,n.hasOwnProperty(u)&&l!==a&&(l!=null||a!=null))if(u==="style")if(a){for(o in a)!a.hasOwnProperty(o)||l&&l.hasOwnProperty(o)||(t||(t={}),t[o]="");for(o in l)l.hasOwnProperty(o)&&a[o]!==l[o]&&(t||(t={}),t[o]=l[o])}else t||(s||(s=[]),s.push(u,t)),t=l;else u==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,a=a?a.__html:void 0,l!=null&&a!==l&&(s=s||[]).push(u,l)):u==="children"?typeof l!="string"&&typeof l!="number"||(s=s||[]).push(u,""+l):u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&(ha.hasOwnProperty(u)?(l!=null&&u==="onScroll"&&at("scroll",r),s||a===l||(s=[])):(s=s||[]).push(u,l))}t&&(s=s||[]).push("style",t);var u=s;(e.updateQueue=u)&&(e.flags|=4)}};s1=function(r,e,t,n){t!==n&&(e.flags|=4)};function zo(r,e){if(!vt)switch(r.tailMode){case"hidden":e=r.tail;for(var t=null;e!==null;)e.alternate!==null&&(t=e),e=e.sibling;t===null?r.tail=null:t.sibling=null;break;case"collapsed":t=r.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e||r.tail===null?r.tail=null:r.tail.sibling=null:n.sibling=null}}function pr(r){var e=r.alternate!==null&&r.alternate.child===r.child,t=0,n=0;if(e)for(var i=r.child;i!==null;)t|=i.lanes|i.childLanes,n|=i.subtreeFlags&14680064,n|=i.flags&14680064,i.return=r,i=i.sibling;else for(i=r.child;i!==null;)t|=i.lanes|i.childLanes,n|=i.subtreeFlags,n|=i.flags,i.return=r,i=i.sibling;return r.subtreeFlags|=n,r.childLanes=t,e}function hS(r,e,t){var n=e.pendingProps;switch(Wh(e),e.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return pr(e),null;case 1:return _r(e.type)&&jl(),pr(e),null;case 3:return n=e.stateNode,io(),ut(Lr),ut(vr),tf(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(r===null||r.child===null)&&(rl(e)?e.flags|=4:r===null||r.memoizedState.isDehydrated&&!(e.flags&256)||(e.flags|=1024,kn!==null&&(Gd(kn),kn=null))),_d(r,e),pr(e),null;case 5:ef(e);var i=rs(Ia.current);if(t=e.type,r!==null&&e.stateNode!=null)i1(r,e,t,n,i),r.ref!==e.ref&&(e.flags|=512,e.flags|=2097152);else{if(!n){if(e.stateNode===null)throw Error(te(166));return pr(e),null}if(r=rs(Hn.current),rl(e)){n=e.stateNode,t=e.type;var s=e.memoizedProps;switch(n[Nn]=e,n[Sa]=s,r=(e.mode&1)!==0,t){case"dialog":at("cancel",n),at("close",n);break;case"iframe":case"object":case"embed":at("load",n);break;case"video":case"audio":for(i=0;i<jo.length;i++)at(jo[i],n);break;case"source":at("error",n);break;case"img":case"image":case"link":at("error",n),at("load",n);break;case"details":at("toggle",n);break;case"input":Rp(n,s),at("invalid",n);break;case"select":n._wrapperState={wasMultiple:!!s.multiple},at("invalid",n);break;case"textarea":Bp(n,s),at("invalid",n)}hd(t,s),i=null;for(var o in s)if(s.hasOwnProperty(o)){var a=s[o];o==="children"?typeof a=="string"?n.textContent!==a&&(s.suppressHydrationWarning!==!0&&tl(n.textContent,a,r),i=["children",a]):typeof a=="number"&&n.textContent!==""+a&&(s.suppressHydrationWarning!==!0&&tl(n.textContent,a,r),i=["children",""+a]):ha.hasOwnProperty(o)&&a!=null&&o==="onScroll"&&at("scroll",n)}switch(t){case"input":Ga(n),Pp(n,s,!0);break;case"textarea":Ga(n),zp(n);break;case"select":case"option":break;default:typeof s.onClick=="function"&&(n.onclick=Hl)}n=i,e.updateQueue=n,n!==null&&(e.flags|=4)}else{o=i.nodeType===9?i:i.ownerDocument,r==="http://www.w3.org/1999/xhtml"&&(r=By(t)),r==="http://www.w3.org/1999/xhtml"?t==="script"?(r=o.createElement("div"),r.innerHTML="<script><\/script>",r=r.removeChild(r.firstChild)):typeof n.is=="string"?r=o.createElement(t,{is:n.is}):(r=o.createElement(t),t==="select"&&(o=r,n.multiple?o.multiple=!0:n.size&&(o.size=n.size))):r=o.createElementNS(r,t),r[Nn]=e,r[Sa]=n,n1(r,e,!1,!1),e.stateNode=r;e:{switch(o=fd(t,n),t){case"dialog":at("cancel",r),at("close",r),i=n;break;case"iframe":case"object":case"embed":at("load",r),i=n;break;case"video":case"audio":for(i=0;i<jo.length;i++)at(jo[i],r);i=n;break;case"source":at("error",r),i=n;break;case"img":case"image":case"link":at("error",r),at("load",r),i=n;break;case"details":at("toggle",r),i=n;break;case"input":Rp(r,n),i=ad(r,n),at("invalid",r);break;case"option":i=n;break;case"select":r._wrapperState={wasMultiple:!!n.multiple},i=It({},n,{value:void 0}),at("invalid",r);break;case"textarea":Bp(r,n),i=cd(r,n),at("invalid",r);break;default:i=n}hd(t,i),a=i;for(s in a)if(a.hasOwnProperty(s)){var l=a[s];s==="style"?Oy(r,l):s==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,l!=null&&zy(r,l)):s==="children"?typeof l=="string"?(t!=="textarea"||l!=="")&&fa(r,l):typeof l=="number"&&fa(r,""+l):s!=="suppressContentEditableWarning"&&s!=="suppressHydrationWarning"&&s!=="autoFocus"&&(ha.hasOwnProperty(s)?l!=null&&s==="onScroll"&&at("scroll",r):l!=null&&Rh(r,s,l,o))}switch(t){case"input":Ga(r),Pp(r,n,!1);break;case"textarea":Ga(r),zp(r);break;case"option":n.value!=null&&r.setAttribute("value",""+Pi(n.value));break;case"select":r.multiple=!!n.multiple,s=n.value,s!=null?Ws(r,!!n.multiple,s,!1):n.defaultValue!=null&&Ws(r,!!n.multiple,n.defaultValue,!0);break;default:typeof i.onClick=="function"&&(r.onclick=Hl)}switch(t){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break e;case"img":n=!0;break e;default:n=!1}}n&&(e.flags|=4)}e.ref!==null&&(e.flags|=512,e.flags|=2097152)}return pr(e),null;case 6:if(r&&e.stateNode!=null)s1(r,e,r.memoizedProps,n);else{if(typeof n!="string"&&e.stateNode===null)throw Error(te(166));if(t=rs(Ia.current),rs(Hn.current),rl(e)){if(n=e.stateNode,t=e.memoizedProps,n[Nn]=e,(s=n.nodeValue!==t)&&(r=qr,r!==null))switch(r.tag){case 3:tl(n.nodeValue,t,(r.mode&1)!==0);break;case 5:r.memoizedProps.suppressHydrationWarning!==!0&&tl(n.nodeValue,t,(r.mode&1)!==0)}s&&(e.flags|=4)}else n=(t.nodeType===9?t:t.ownerDocument).createTextNode(n),n[Nn]=e,e.stateNode=n}return pr(e),null;case 13:if(ut(St),n=e.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(vt&&Zr!==null&&e.mode&1&&!(e.flags&128))x0(),ro(),e.flags|=98560,s=!1;else if(s=rl(e),n!==null&&n.dehydrated!==null){if(r===null){if(!s)throw Error(te(318));if(s=e.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(te(317));s[Nn]=e}else ro(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;pr(e),s=!1}else kn!==null&&(Gd(kn),kn=null),s=!0;if(!s)return e.flags&65536?e:null}return e.flags&128?(e.lanes=t,e):(n=n!==null,n!==(r!==null&&r.memoizedState!==null)&&n&&(e.child.flags|=8192,e.mode&1&&(r===null||St.current&1?Wt===0&&(Wt=3):pf())),e.updateQueue!==null&&(e.flags|=4),pr(e),null);case 4:return io(),_d(r,e),r===null&&Ca(e.stateNode.containerInfo),pr(e),null;case 10:return Zh(e.type._context),pr(e),null;case 17:return _r(e.type)&&jl(),pr(e),null;case 19:if(ut(St),s=e.memoizedState,s===null)return pr(e),null;if(n=(e.flags&128)!==0,o=s.rendering,o===null)if(n)zo(s,!1);else{if(Wt!==0||r!==null&&r.flags&128)for(r=e.child;r!==null;){if(o=ql(r),o!==null){for(e.flags|=128,zo(s,!1),n=o.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),e.subtreeFlags=0,n=t,t=e.child;t!==null;)s=t,r=n,s.flags&=14680066,o=s.alternate,o===null?(s.childLanes=0,s.lanes=r,s.child=null,s.subtreeFlags=0,s.memoizedProps=null,s.memoizedState=null,s.updateQueue=null,s.dependencies=null,s.stateNode=null):(s.childLanes=o.childLanes,s.lanes=o.lanes,s.child=o.child,s.subtreeFlags=0,s.deletions=null,s.memoizedProps=o.memoizedProps,s.memoizedState=o.memoizedState,s.updateQueue=o.updateQueue,s.type=o.type,r=o.dependencies,s.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext}),t=t.sibling;return rt(St,St.current&1|2),e.child}r=r.sibling}s.tail!==null&&Rt()>oo&&(e.flags|=128,n=!0,zo(s,!1),e.lanes=4194304)}else{if(!n)if(r=ql(o),r!==null){if(e.flags|=128,n=!0,t=r.updateQueue,t!==null&&(e.updateQueue=t,e.flags|=4),zo(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!vt)return pr(e),null}else 2*Rt()-s.renderingStartTime>oo&&t!==1073741824&&(e.flags|=128,n=!0,zo(s,!1),e.lanes=4194304);s.isBackwards?(o.sibling=e.child,e.child=o):(t=s.last,t!==null?t.sibling=o:e.child=o,s.last=o)}return s.tail!==null?(e=s.tail,s.rendering=e,s.tail=e.sibling,s.renderingStartTime=Rt(),e.sibling=null,t=St.current,rt(St,n?t&1|2:t&1),e):(pr(e),null);case 22:case 23:return ff(),n=e.memoizedState!==null,r!==null&&r.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?Gr&1073741824&&(pr(e),e.subtreeFlags&6&&(e.flags|=8192)):pr(e),null;case 24:return null;case 25:return null}throw Error(te(156,e.tag))}function fS(r,e){switch(Wh(e),e.tag){case 1:return _r(e.type)&&jl(),r=e.flags,r&65536?(e.flags=r&-65537|128,e):null;case 3:return io(),ut(Lr),ut(vr),tf(),r=e.flags,r&65536&&!(r&128)?(e.flags=r&-65537|128,e):null;case 5:return ef(e),null;case 13:if(ut(St),r=e.memoizedState,r!==null&&r.dehydrated!==null){if(e.alternate===null)throw Error(te(340));ro()}return r=e.flags,r&65536?(e.flags=r&-65537|128,e):null;case 19:return ut(St),null;case 4:return io(),null;case 10:return Zh(e.type._context),null;case 22:case 23:return ff(),null;case 24:return null;default:return null}}var sl=!1,mr=!1,pS=typeof WeakSet=="function"?WeakSet:Set,fe=null;function Vs(r,e){var t=r.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(n){Ut(r,e,n)}else t.current=null}function $d(r,e,t){try{t()}catch(n){Ut(r,e,n)}}var xg=!1;function gS(r,e){if(xd=$l,r=c0(),jh(r)){if("selectionStart"in r)var t={start:r.selectionStart,end:r.selectionEnd};else e:{t=(t=r.ownerDocument)&&t.defaultView||window;var n=t.getSelection&&t.getSelection();if(n&&n.rangeCount!==0){t=n.anchorNode;var i=n.anchorOffset,s=n.focusNode;n=n.focusOffset;try{t.nodeType,s.nodeType}catch{t=null;break e}var o=0,a=-1,l=-1,u=0,c=0,d=r,h=null;t:for(;;){for(var f;d!==t||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),(f=d.firstChild)!==null;)h=d,d=f;for(;;){if(d===r)break t;if(h===t&&++u===i&&(a=o),h===s&&++c===n&&(l=o),(f=d.nextSibling)!==null)break;d=h,h=d.parentNode}d=f}t=a===-1||l===-1?null:{start:a,end:l}}else t=null}t=t||{start:0,end:0}}else t=null;for(Id={focusedElem:r,selectionRange:t},$l=!1,fe=e;fe!==null;)if(e=fe,r=e.child,(e.subtreeFlags&1028)!==0&&r!==null)r.return=e,fe=r;else for(;fe!==null;){e=fe;try{var p=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(p!==null){var m=p.memoizedProps,S=p.memoizedState,w=e.stateNode,g=w.getSnapshotBeforeUpdate(e.elementType===e.type?m:bn(e.type,m),S);w.__reactInternalSnapshotBeforeUpdate=g}break;case 3:var y=e.stateNode.containerInfo;y.nodeType===1?y.textContent="":y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(te(163))}}catch(C){Ut(e,e.return,C)}if(r=e.sibling,r!==null){r.return=e.return,fe=r;break}fe=e.return}return p=xg,xg=!1,p}function na(r,e,t){var n=e.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var i=n=n.next;do{if((i.tag&r)===r){var s=i.destroy;i.destroy=void 0,s!==void 0&&$d(e,t,s)}i=i.next}while(i!==n)}}function bu(r,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var t=e=e.next;do{if((t.tag&r)===r){var n=t.create;t.destroy=n()}t=t.next}while(t!==e)}}function Nd(r){var e=r.ref;if(e!==null){var t=r.stateNode;switch(r.tag){case 5:r=t;break;default:r=t}typeof e=="function"?e(r):e.current=r}}function o1(r){var e=r.alternate;e!==null&&(r.alternate=null,o1(e)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(e=r.stateNode,e!==null&&(delete e[Nn],delete e[Sa],delete e[Md],delete e[q2],delete e[Q2])),r.stateNode=null,r.return=null,r.dependencies=null,r.memoizedProps=null,r.memoizedState=null,r.pendingProps=null,r.stateNode=null,r.updateQueue=null}function a1(r){return r.tag===5||r.tag===3||r.tag===4}function Ig(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||a1(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function Vd(r,e,t){var n=r.tag;if(n===5||n===6)r=r.stateNode,e?t.nodeType===8?t.parentNode.insertBefore(r,e):t.insertBefore(r,e):(t.nodeType===8?(e=t.parentNode,e.insertBefore(r,t)):(e=t,e.appendChild(r)),t=t._reactRootContainer,t!=null||e.onclick!==null||(e.onclick=Hl));else if(n!==4&&(r=r.child,r!==null))for(Vd(r,e,t),r=r.sibling;r!==null;)Vd(r,e,t),r=r.sibling}function Hd(r,e,t){var n=r.tag;if(n===5||n===6)r=r.stateNode,e?t.insertBefore(r,e):t.appendChild(r);else if(n!==4&&(r=r.child,r!==null))for(Hd(r,e,t),r=r.sibling;r!==null;)Hd(r,e,t),r=r.sibling}var ar=null,Sn=!1;function fi(r,e,t){for(t=t.child;t!==null;)l1(r,e,t),t=t.sibling}function l1(r,e,t){if(Vn&&typeof Vn.onCommitFiberUnmount=="function")try{Vn.onCommitFiberUnmount(fu,t)}catch{}switch(t.tag){case 5:mr||Vs(t,e);case 6:var n=ar,i=Sn;ar=null,fi(r,e,t),ar=n,Sn=i,ar!==null&&(Sn?(r=ar,t=t.stateNode,r.nodeType===8?r.parentNode.removeChild(t):r.removeChild(t)):ar.removeChild(t.stateNode));break;case 18:ar!==null&&(Sn?(r=ar,t=t.stateNode,r.nodeType===8?Ec(r.parentNode,t):r.nodeType===1&&Ec(r,t),ya(r)):Ec(ar,t.stateNode));break;case 4:n=ar,i=Sn,ar=t.stateNode.containerInfo,Sn=!0,fi(r,e,t),ar=n,Sn=i;break;case 0:case 11:case 14:case 15:if(!mr&&(n=t.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)&&$d(t,e,o),i=i.next}while(i!==n)}fi(r,e,t);break;case 1:if(!mr&&(Vs(t,e),n=t.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=t.memoizedProps,n.state=t.memoizedState,n.componentWillUnmount()}catch(a){Ut(t,e,a)}fi(r,e,t);break;case 21:fi(r,e,t);break;case 22:t.mode&1?(mr=(n=mr)||t.memoizedState!==null,fi(r,e,t),mr=n):fi(r,e,t);break;default:fi(r,e,t)}}function kg(r){var e=r.updateQueue;if(e!==null){r.updateQueue=null;var t=r.stateNode;t===null&&(t=r.stateNode=new pS),e.forEach(function(n){var i=IS.bind(null,r,n);t.has(n)||(t.add(n),n.then(i,i))})}}function vn(r,e){var t=e.deletions;if(t!==null)for(var n=0;n<t.length;n++){var i=t[n];try{var s=r,o=e,a=o;e:for(;a!==null;){switch(a.tag){case 5:ar=a.stateNode,Sn=!1;break e;case 3:ar=a.stateNode.containerInfo,Sn=!0;break e;case 4:ar=a.stateNode.containerInfo,Sn=!0;break e}a=a.return}if(ar===null)throw Error(te(160));l1(s,o,i),ar=null,Sn=!1;var l=i.alternate;l!==null&&(l.return=null),i.return=null}catch(u){Ut(i,e,u)}}if(e.subtreeFlags&12854)for(e=e.child;e!==null;)u1(e,r),e=e.sibling}function u1(r,e){var t=r.alternate,n=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:if(vn(e,r),Ln(r),n&4){try{na(3,r,r.return),bu(3,r)}catch(m){Ut(r,r.return,m)}try{na(5,r,r.return)}catch(m){Ut(r,r.return,m)}}break;case 1:vn(e,r),Ln(r),n&512&&t!==null&&Vs(t,t.return);break;case 5:if(vn(e,r),Ln(r),n&512&&t!==null&&Vs(t,t.return),r.flags&32){var i=r.stateNode;try{fa(i,"")}catch(m){Ut(r,r.return,m)}}if(n&4&&(i=r.stateNode,i!=null)){var s=r.memoizedProps,o=t!==null?t.memoizedProps:s,a=r.type,l=r.updateQueue;if(r.updateQueue=null,l!==null)try{a==="input"&&s.type==="radio"&&s.name!=null&&Ry(i,s),fd(a,o);var u=fd(a,s);for(o=0;o<l.length;o+=2){var c=l[o],d=l[o+1];c==="style"?Oy(i,d):c==="dangerouslySetInnerHTML"?zy(i,d):c==="children"?fa(i,d):Rh(i,c,d,u)}switch(a){case"input":ld(i,s);break;case"textarea":Py(i,s);break;case"select":var h=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!s.multiple;var f=s.value;f!=null?Ws(i,!!s.multiple,f,!1):h!==!!s.multiple&&(s.defaultValue!=null?Ws(i,!!s.multiple,s.defaultValue,!0):Ws(i,!!s.multiple,s.multiple?[]:"",!1))}i[Sa]=s}catch(m){Ut(r,r.return,m)}}break;case 6:if(vn(e,r),Ln(r),n&4){if(r.stateNode===null)throw Error(te(162));i=r.stateNode,s=r.memoizedProps;try{i.nodeValue=s}catch(m){Ut(r,r.return,m)}}break;case 3:if(vn(e,r),Ln(r),n&4&&t!==null&&t.memoizedState.isDehydrated)try{ya(e.containerInfo)}catch(m){Ut(r,r.return,m)}break;case 4:vn(e,r),Ln(r);break;case 13:vn(e,r),Ln(r),i=r.child,i.flags&8192&&(s=i.memoizedState!==null,i.stateNode.isHidden=s,!s||i.alternate!==null&&i.alternate.memoizedState!==null||(df=Rt())),n&4&&kg(r);break;case 22:if(c=t!==null&&t.memoizedState!==null,r.mode&1?(mr=(u=mr)||c,vn(e,r),mr=u):vn(e,r),Ln(r),n&8192){if(u=r.memoizedState!==null,(r.stateNode.isHidden=u)&&!c&&r.mode&1)for(fe=r,c=r.child;c!==null;){for(d=fe=c;fe!==null;){switch(h=fe,f=h.child,h.tag){case 0:case 11:case 14:case 15:na(4,h,h.return);break;case 1:Vs(h,h.return);var p=h.stateNode;if(typeof p.componentWillUnmount=="function"){n=h,t=h.return;try{e=n,p.props=e.memoizedProps,p.state=e.memoizedState,p.componentWillUnmount()}catch(m){Ut(n,t,m)}}break;case 5:Vs(h,h.return);break;case 22:if(h.memoizedState!==null){Mg(d);continue}}f!==null?(f.return=h,fe=f):Mg(d)}c=c.sibling}e:for(c=null,d=r;;){if(d.tag===5){if(c===null){c=d;try{i=d.stateNode,u?(s=i.style,typeof s.setProperty=="function"?s.setProperty("display","none","important"):s.display="none"):(a=d.stateNode,l=d.memoizedProps.style,o=l!=null&&l.hasOwnProperty("display")?l.display:null,a.style.display=Dy("display",o))}catch(m){Ut(r,r.return,m)}}}else if(d.tag===6){if(c===null)try{d.stateNode.nodeValue=u?"":d.memoizedProps}catch(m){Ut(r,r.return,m)}}else if((d.tag!==22&&d.tag!==23||d.memoizedState===null||d===r)&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===r)break e;for(;d.sibling===null;){if(d.return===null||d.return===r)break e;c===d&&(c=null),d=d.return}c===d&&(c=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:vn(e,r),Ln(r),n&4&&kg(r);break;case 21:break;default:vn(e,r),Ln(r)}}function Ln(r){var e=r.flags;if(e&2){try{e:{for(var t=r.return;t!==null;){if(a1(t)){var n=t;break e}t=t.return}throw Error(te(160))}switch(n.tag){case 5:var i=n.stateNode;n.flags&32&&(fa(i,""),n.flags&=-33);var s=Ig(r);Hd(r,s,i);break;case 3:case 4:var o=n.stateNode.containerInfo,a=Ig(r);Vd(r,a,o);break;default:throw Error(te(161))}}catch(l){Ut(r,r.return,l)}r.flags&=-3}e&4096&&(r.flags&=-4097)}function mS(r,e,t){fe=r,c1(r)}function c1(r,e,t){for(var n=(r.mode&1)!==0;fe!==null;){var i=fe,s=i.child;if(i.tag===22&&n){var o=i.memoizedState!==null||sl;if(!o){var a=i.alternate,l=a!==null&&a.memoizedState!==null||mr;a=sl;var u=mr;if(sl=o,(mr=l)&&!u)for(fe=i;fe!==null;)o=fe,l=o.child,o.tag===22&&o.memoizedState!==null?Ug(i):l!==null?(l.return=o,fe=l):Ug(i);for(;s!==null;)fe=s,c1(s),s=s.sibling;fe=i,sl=a,mr=u}Eg(r)}else i.subtreeFlags&8772&&s!==null?(s.return=i,fe=s):Eg(r)}}function Eg(r){for(;fe!==null;){var e=fe;if(e.flags&8772){var t=e.alternate;try{if(e.flags&8772)switch(e.tag){case 0:case 11:case 15:mr||bu(5,e);break;case 1:var n=e.stateNode;if(e.flags&4&&!mr)if(t===null)n.componentDidMount();else{var i=e.elementType===e.type?t.memoizedProps:bn(e.type,t.memoizedProps);n.componentDidUpdate(i,t.memoizedState,n.__reactInternalSnapshotBeforeUpdate)}var s=e.updateQueue;s!==null&&cg(e,s,n);break;case 3:var o=e.updateQueue;if(o!==null){if(t=null,e.child!==null)switch(e.child.tag){case 5:t=e.child.stateNode;break;case 1:t=e.child.stateNode}cg(e,o,t)}break;case 5:var a=e.stateNode;if(t===null&&e.flags&4){t=a;var l=e.memoizedProps;switch(e.type){case"button":case"input":case"select":case"textarea":l.autoFocus&&t.focus();break;case"img":l.src&&(t.src=l.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(e.memoizedState===null){var u=e.alternate;if(u!==null){var c=u.memoizedState;if(c!==null){var d=c.dehydrated;d!==null&&ya(d)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(te(163))}mr||e.flags&512&&Nd(e)}catch(h){Ut(e,e.return,h)}}if(e===r){fe=null;break}if(t=e.sibling,t!==null){t.return=e.return,fe=t;break}fe=e.return}}function Mg(r){for(;fe!==null;){var e=fe;if(e===r){fe=null;break}var t=e.sibling;if(t!==null){t.return=e.return,fe=t;break}fe=e.return}}function Ug(r){for(;fe!==null;){var e=fe;try{switch(e.tag){case 0:case 11:case 15:var t=e.return;try{bu(4,e)}catch(l){Ut(e,t,l)}break;case 1:var n=e.stateNode;if(typeof n.componentDidMount=="function"){var i=e.return;try{n.componentDidMount()}catch(l){Ut(e,i,l)}}var s=e.return;try{Nd(e)}catch(l){Ut(e,s,l)}break;case 5:var o=e.return;try{Nd(e)}catch(l){Ut(e,o,l)}}}catch(l){Ut(e,e.return,l)}if(e===r){fe=null;break}var a=e.sibling;if(a!==null){a.return=e.return,fe=a;break}fe=e.return}}var yS=Math.ceil,eu=oi.ReactCurrentDispatcher,uf=oi.ReactCurrentOwner,hn=oi.ReactCurrentBatchConfig,De=0,nr=null,Dt=null,lr=0,Gr=0,Hs=Oi(0),Wt=0,Ua=null,us=0,Su=0,cf=0,ia=null,Or=null,df=0,oo=1/0,Kn=null,tu=!1,jd=null,Ei=null,ol=!1,Ci=null,ru=0,sa=0,Yd=null,Ul=-1,Al=0;function Ur(){return De&6?Rt():Ul!==-1?Ul:Ul=Rt()}function Mi(r){return r.mode&1?De&2&&lr!==0?lr&-lr:eS.transition!==null?(Al===0&&(Al=Xy()),Al):(r=Xe,r!==0||(r=window.event,r=r===void 0?16:t0(r.type)),r):1}function Un(r,e,t,n){if(50<sa)throw sa=0,Yd=null,Error(te(185));Pa(r,t,n),(!(De&2)||r!==nr)&&(r===nr&&(!(De&2)&&(Su|=t),Wt===4&&vi(r,lr)),$r(r,n),t===1&&De===0&&!(e.mode&1)&&(oo=Rt()+500,vu&&Fi()))}function $r(r,e){var t=r.callbackNode;e2(r,e);var n=_l(r,r===nr?lr:0);if(n===0)t!==null&&Fp(t),r.callbackNode=null,r.callbackPriority=0;else if(e=n&-n,r.callbackPriority!==e){if(t!=null&&Fp(t),e===1)r.tag===0?J2(Ag.bind(null,r)):C0(Ag.bind(null,r)),K2(function(){!(De&6)&&Fi()}),t=null;else{switch(Ky(n)){case 1:t=Oh;break;case 4:t=Wy;break;case 16:t=Ll;break;case 536870912:t=Gy;break;default:t=Ll}t=v1(t,d1.bind(null,r))}r.callbackPriority=e,r.callbackNode=t}}function d1(r,e){if(Ul=-1,Al=0,De&6)throw Error(te(327));var t=r.callbackNode;if(qs()&&r.callbackNode!==t)return null;var n=_l(r,r===nr?lr:0);if(n===0)return null;if(n&30||n&r.expiredLanes||e)e=nu(r,n);else{e=n;var i=De;De|=2;var s=f1();(nr!==r||lr!==e)&&(Kn=null,oo=Rt()+500,ns(r,e));do try{CS();break}catch(a){h1(r,a)}while(!0);Kh(),eu.current=s,De=i,Dt!==null?e=0:(nr=null,lr=0,e=Wt)}if(e!==0){if(e===2&&(i=vd(r),i!==0&&(n=i,e=Wd(r,i))),e===1)throw t=Ua,ns(r,0),vi(r,n),$r(r,Rt()),t;if(e===6)vi(r,n);else{if(i=r.current.alternate,!(n&30)&&!vS(i)&&(e=nu(r,n),e===2&&(s=vd(r),s!==0&&(n=s,e=Wd(r,s))),e===1))throw t=Ua,ns(r,0),vi(r,n),$r(r,Rt()),t;switch(r.finishedWork=i,r.finishedLanes=n,e){case 0:case 1:throw Error(te(345));case 2:Xi(r,Or,Kn);break;case 3:if(vi(r,n),(n&130023424)===n&&(e=df+500-Rt(),10<e)){if(_l(r,0)!==0)break;if(i=r.suspendedLanes,(i&n)!==n){Ur(),r.pingedLanes|=r.suspendedLanes&i;break}r.timeoutHandle=Ed(Xi.bind(null,r,Or,Kn),e);break}Xi(r,Or,Kn);break;case 4:if(vi(r,n),(n&4194240)===n)break;for(e=r.eventTimes,i=-1;0<n;){var o=31-Mn(n);s=1<<o,o=e[o],o>i&&(i=o),n&=~s}if(n=i,n=Rt()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*yS(n/1960))-n,10<n){r.timeoutHandle=Ed(Xi.bind(null,r,Or,Kn),n);break}Xi(r,Or,Kn);break;case 5:Xi(r,Or,Kn);break;default:throw Error(te(329))}}}return $r(r,Rt()),r.callbackNode===t?d1.bind(null,r):null}function Wd(r,e){var t=ia;return r.current.memoizedState.isDehydrated&&(ns(r,e).flags|=256),r=nu(r,e),r!==2&&(e=Or,Or=t,e!==null&&Gd(e)),r}function Gd(r){Or===null?Or=r:Or.push.apply(Or,r)}function vS(r){for(var e=r;;){if(e.flags&16384){var t=e.updateQueue;if(t!==null&&(t=t.stores,t!==null))for(var n=0;n<t.length;n++){var i=t[n],s=i.getSnapshot;i=i.value;try{if(!An(s(),i))return!1}catch{return!1}}}if(t=e.child,e.subtreeFlags&16384&&t!==null)t.return=e,e=t;else{if(e===r)break;for(;e.sibling===null;){if(e.return===null||e.return===r)return!0;e=e.return}e.sibling.return=e.return,e=e.sibling}}return!0}function vi(r,e){for(e&=~cf,e&=~Su,r.suspendedLanes|=e,r.pingedLanes&=~e,r=r.expirationTimes;0<e;){var t=31-Mn(e),n=1<<t;r[t]=-1,e&=~n}}function Ag(r){if(De&6)throw Error(te(327));qs();var e=_l(r,0);if(!(e&1))return $r(r,Rt()),null;var t=nu(r,e);if(r.tag!==0&&t===2){var n=vd(r);n!==0&&(e=n,t=Wd(r,n))}if(t===1)throw t=Ua,ns(r,0),vi(r,e),$r(r,Rt()),t;if(t===6)throw Error(te(345));return r.finishedWork=r.current.alternate,r.finishedLanes=e,Xi(r,Or,Kn),$r(r,Rt()),null}function hf(r,e){var t=De;De|=1;try{return r(e)}finally{De=t,De===0&&(oo=Rt()+500,vu&&Fi())}}function cs(r){Ci!==null&&Ci.tag===0&&!(De&6)&&qs();var e=De;De|=1;var t=hn.transition,n=Xe;try{if(hn.transition=null,Xe=1,r)return r()}finally{Xe=n,hn.transition=t,De=e,!(De&6)&&Fi()}}function ff(){Gr=Hs.current,ut(Hs)}function ns(r,e){r.finishedWork=null,r.finishedLanes=0;var t=r.timeoutHandle;if(t!==-1&&(r.timeoutHandle=-1,X2(t)),Dt!==null)for(t=Dt.return;t!==null;){var n=t;switch(Wh(n),n.tag){case 1:n=n.type.childContextTypes,n!=null&&jl();break;case 3:io(),ut(Lr),ut(vr),tf();break;case 5:ef(n);break;case 4:io();break;case 13:ut(St);break;case 19:ut(St);break;case 10:Zh(n.type._context);break;case 22:case 23:ff()}t=t.return}if(nr=r,Dt=r=Ui(r.current,null),lr=Gr=e,Wt=0,Ua=null,cf=Su=us=0,Or=ia=null,ts!==null){for(e=0;e<ts.length;e++)if(t=ts[e],n=t.interleaved,n!==null){t.interleaved=null;var i=n.next,s=t.pending;if(s!==null){var o=s.next;s.next=i,n.next=o}t.pending=n}ts=null}return r}function h1(r,e){do{var t=Dt;try{if(Kh(),kl.current=Jl,Ql){for(var n=xt.memoizedState;n!==null;){var i=n.queue;i!==null&&(i.pending=null),n=n.next}Ql=!1}if(ls=0,rr=Ht=xt=null,ra=!1,ka=0,uf.current=null,t===null||t.return===null){Wt=1,Ua=e,Dt=null;break}e:{var s=r,o=t.return,a=t,l=e;if(e=lr,a.flags|=32768,l!==null&&typeof l=="object"&&typeof l.then=="function"){var u=l,c=a,d=c.tag;if(!(c.mode&1)&&(d===0||d===11||d===15)){var h=c.alternate;h?(c.updateQueue=h.updateQueue,c.memoizedState=h.memoizedState,c.lanes=h.lanes):(c.updateQueue=null,c.memoizedState=null)}var f=mg(o);if(f!==null){f.flags&=-257,yg(f,o,a,s,e),f.mode&1&&gg(s,u,e),e=f,l=u;var p=e.updateQueue;if(p===null){var m=new Set;m.add(l),e.updateQueue=m}else p.add(l);break e}else{if(!(e&1)){gg(s,u,e),pf();break e}l=Error(te(426))}}else if(vt&&a.mode&1){var S=mg(o);if(S!==null){!(S.flags&65536)&&(S.flags|=256),yg(S,o,a,s,e),Gh(so(l,a));break e}}s=l=so(l,a),Wt!==4&&(Wt=2),ia===null?ia=[s]:ia.push(s),s=o;do{switch(s.tag){case 3:s.flags|=65536,e&=-e,s.lanes|=e;var w=K0(s,l,e);ug(s,w);break e;case 1:a=l;var g=s.type,y=s.stateNode;if(!(s.flags&128)&&(typeof g.getDerivedStateFromError=="function"||y!==null&&typeof y.componentDidCatch=="function"&&(Ei===null||!Ei.has(y)))){s.flags|=65536,e&=-e,s.lanes|=e;var C=Z0(s,a,e);ug(s,C);break e}}s=s.return}while(s!==null)}g1(t)}catch(x){e=x,Dt===t&&t!==null&&(Dt=t=t.return);continue}break}while(!0)}function f1(){var r=eu.current;return eu.current=Jl,r===null?Jl:r}function pf(){(Wt===0||Wt===3||Wt===2)&&(Wt=4),nr===null||!(us&268435455)&&!(Su&268435455)||vi(nr,lr)}function nu(r,e){var t=De;De|=2;var n=f1();(nr!==r||lr!==e)&&(Kn=null,ns(r,e));do try{wS();break}catch(i){h1(r,i)}while(!0);if(Kh(),De=t,eu.current=n,Dt!==null)throw Error(te(261));return nr=null,lr=0,Wt}function wS(){for(;Dt!==null;)p1(Dt)}function CS(){for(;Dt!==null&&!Yb();)p1(Dt)}function p1(r){var e=y1(r.alternate,r,Gr);r.memoizedProps=r.pendingProps,e===null?g1(r):Dt=e,uf.current=null}function g1(r){var e=r;do{var t=e.alternate;if(r=e.return,e.flags&32768){if(t=fS(t,e),t!==null){t.flags&=32767,Dt=t;return}if(r!==null)r.flags|=32768,r.subtreeFlags=0,r.deletions=null;else{Wt=6,Dt=null;return}}else if(t=hS(t,e,Gr),t!==null){Dt=t;return}if(e=e.sibling,e!==null){Dt=e;return}Dt=e=r}while(e!==null);Wt===0&&(Wt=5)}function Xi(r,e,t){var n=Xe,i=hn.transition;try{hn.transition=null,Xe=1,bS(r,e,t,n)}finally{hn.transition=i,Xe=n}return null}function bS(r,e,t,n){do qs();while(Ci!==null);if(De&6)throw Error(te(327));t=r.finishedWork;var i=r.finishedLanes;if(t===null)return null;if(r.finishedWork=null,r.finishedLanes=0,t===r.current)throw Error(te(177));r.callbackNode=null,r.callbackPriority=0;var s=t.lanes|t.childLanes;if(t2(r,s),r===nr&&(Dt=nr=null,lr=0),!(t.subtreeFlags&2064)&&!(t.flags&2064)||ol||(ol=!0,v1(Ll,function(){return qs(),null})),s=(t.flags&15990)!==0,t.subtreeFlags&15990||s){s=hn.transition,hn.transition=null;var o=Xe;Xe=1;var a=De;De|=4,uf.current=null,gS(r,t),u1(t,r),N2(Id),$l=!!xd,Id=xd=null,r.current=t,mS(t),Wb(),De=a,Xe=o,hn.transition=s}else r.current=t;if(ol&&(ol=!1,Ci=r,ru=i),s=r.pendingLanes,s===0&&(Ei=null),Kb(t.stateNode),$r(r,Rt()),e!==null)for(n=r.onRecoverableError,t=0;t<e.length;t++)i=e[t],n(i.value,{componentStack:i.stack,digest:i.digest});if(tu)throw tu=!1,r=jd,jd=null,r;return ru&1&&r.tag!==0&&qs(),s=r.pendingLanes,s&1?r===Yd?sa++:(sa=0,Yd=r):sa=0,Fi(),null}function qs(){if(Ci!==null){var r=Ky(ru),e=hn.transition,t=Xe;try{if(hn.transition=null,Xe=16>r?16:r,Ci===null)var n=!1;else{if(r=Ci,Ci=null,ru=0,De&6)throw Error(te(331));var i=De;for(De|=4,fe=r.current;fe!==null;){var s=fe,o=s.child;if(fe.flags&16){var a=s.deletions;if(a!==null){for(var l=0;l<a.length;l++){var u=a[l];for(fe=u;fe!==null;){var c=fe;switch(c.tag){case 0:case 11:case 15:na(8,c,s)}var d=c.child;if(d!==null)d.return=c,fe=d;else for(;fe!==null;){c=fe;var h=c.sibling,f=c.return;if(o1(c),c===u){fe=null;break}if(h!==null){h.return=f,fe=h;break}fe=f}}}var p=s.alternate;if(p!==null){var m=p.child;if(m!==null){p.child=null;do{var S=m.sibling;m.sibling=null,m=S}while(m!==null)}}fe=s}}if(s.subtreeFlags&2064&&o!==null)o.return=s,fe=o;else e:for(;fe!==null;){if(s=fe,s.flags&2048)switch(s.tag){case 0:case 11:case 15:na(9,s,s.return)}var w=s.sibling;if(w!==null){w.return=s.return,fe=w;break e}fe=s.return}}var g=r.current;for(fe=g;fe!==null;){o=fe;var y=o.child;if(o.subtreeFlags&2064&&y!==null)y.return=o,fe=y;else e:for(o=g;fe!==null;){if(a=fe,a.flags&2048)try{switch(a.tag){case 0:case 11:case 15:bu(9,a)}}catch(x){Ut(a,a.return,x)}if(a===o){fe=null;break e}var C=a.sibling;if(C!==null){C.return=a.return,fe=C;break e}fe=a.return}}if(De=i,Fi(),Vn&&typeof Vn.onPostCommitFiberRoot=="function")try{Vn.onPostCommitFiberRoot(fu,r)}catch{}n=!0}return n}finally{Xe=t,hn.transition=e}}return!1}function Tg(r,e,t){e=so(t,e),e=K0(r,e,1),r=ki(r,e,1),e=Ur(),r!==null&&(Pa(r,1,e),$r(r,e))}function Ut(r,e,t){if(r.tag===3)Tg(r,r,t);else for(;e!==null;){if(e.tag===3){Tg(e,r,t);break}else if(e.tag===1){var n=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(Ei===null||!Ei.has(n))){r=so(t,r),r=Z0(e,r,1),e=ki(e,r,1),r=Ur(),e!==null&&(Pa(e,1,r),$r(e,r));break}}e=e.return}}function SS(r,e,t){var n=r.pingCache;n!==null&&n.delete(e),e=Ur(),r.pingedLanes|=r.suspendedLanes&t,nr===r&&(lr&t)===t&&(Wt===4||Wt===3&&(lr&130023424)===lr&&500>Rt()-df?ns(r,0):cf|=t),$r(r,e)}function m1(r,e){e===0&&(r.mode&1?(e=Za,Za<<=1,!(Za&130023424)&&(Za=4194304)):e=1);var t=Ur();r=ii(r,e),r!==null&&(Pa(r,e,t),$r(r,t))}function xS(r){var e=r.memoizedState,t=0;e!==null&&(t=e.retryLane),m1(r,t)}function IS(r,e){var t=0;switch(r.tag){case 13:var n=r.stateNode,i=r.memoizedState;i!==null&&(t=i.retryLane);break;case 19:n=r.stateNode;break;default:throw Error(te(314))}n!==null&&n.delete(e),m1(r,t)}var y1;y1=function(r,e,t){if(r!==null)if(r.memoizedProps!==e.pendingProps||Lr.current)Fr=!0;else{if(!(r.lanes&t)&&!(e.flags&128))return Fr=!1,dS(r,e,t);Fr=!!(r.flags&131072)}else Fr=!1,vt&&e.flags&1048576&&b0(e,Gl,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;Ml(r,e),r=e.pendingProps;var i=to(e,vr.current);Zs(e,t),i=nf(null,e,n,r,i,t);var s=sf();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,_r(n)?(s=!0,Yl(e)):s=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,Qh(e),i.updater=Cu,e.stateNode=i,i._reactInternals=e,Bd(e,n,r,t),e=Od(null,e,n,!0,s,t)):(e.tag=0,vt&&s&&Yh(e),kr(null,e,i,t),e=e.child),e;case 16:n=e.elementType;e:{switch(Ml(r,e),r=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=ES(n),r=bn(n,r),i){case 0:e=Dd(null,e,n,r,t);break e;case 1:e=Cg(null,e,n,r,t);break e;case 11:e=vg(null,e,n,r,t);break e;case 14:e=wg(null,e,n,bn(n.type,r),t);break e}throw Error(te(306,n,""))}return e;case 0:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:bn(n,i),Dd(r,e,n,i,t);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:bn(n,i),Cg(r,e,n,i,t);case 3:e:{if(e1(e),r===null)throw Error(te(387));n=e.pendingProps,s=e.memoizedState,i=s.element,M0(r,e),Zl(e,n,null,t);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=so(Error(te(423)),e),e=bg(r,e,n,t,i);break e}else if(n!==i){i=so(Error(te(424)),e),e=bg(r,e,n,t,i);break e}else for(Zr=Ii(e.stateNode.containerInfo.firstChild),qr=e,vt=!0,kn=null,t=k0(e,null,n,t),e.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(ro(),n===i){e=si(r,e,t);break e}kr(r,e,n,t)}e=e.child}return e;case 5:return U0(e),r===null&&Td(e),n=e.type,i=e.pendingProps,s=r!==null?r.memoizedProps:null,o=i.children,kd(n,i)?o=null:s!==null&&kd(n,s)&&(e.flags|=32),J0(r,e),kr(r,e,o,t),e.child;case 6:return r===null&&Td(e),null;case 13:return t1(r,e,t);case 4:return Jh(e,e.stateNode.containerInfo),n=e.pendingProps,r===null?e.child=no(e,null,n,t):kr(r,e,n,t),e.child;case 11:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:bn(n,i),vg(r,e,n,i,t);case 7:return kr(r,e,e.pendingProps,t),e.child;case 8:return kr(r,e,e.pendingProps.children,t),e.child;case 12:return kr(r,e,e.pendingProps.children,t),e.child;case 10:e:{if(n=e.type._context,i=e.pendingProps,s=e.memoizedProps,o=i.value,rt(Xl,n._currentValue),n._currentValue=o,s!==null)if(An(s.value,o)){if(s.children===i.children&&!Lr.current){e=si(r,e,t);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=Jn(-1,t&-t),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|=t,l=s.alternate,l!==null&&(l.lanes|=t),Rd(s.return,t,e),a.lanes|=t;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(te(341));o.lanes|=t,a=o.alternate,a!==null&&(a.lanes|=t),Rd(o,t,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}kr(r,e,i.children,t),e=e.child}return e;case 9:return i=e.type,n=e.pendingProps.children,Zs(e,t),i=fn(i),n=n(i),e.flags|=1,kr(r,e,n,t),e.child;case 14:return n=e.type,i=bn(n,e.pendingProps),i=bn(n.type,i),wg(r,e,n,i,t);case 15:return q0(r,e,e.type,e.pendingProps,t);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:bn(n,i),Ml(r,e),e.tag=1,_r(n)?(r=!0,Yl(e)):r=!1,Zs(e,t),X0(e,n,i),Bd(e,n,i,t),Od(null,e,n,!0,r,t);case 19:return r1(r,e,t);case 22:return Q0(r,e,t)}throw Error(te(156,e.tag))};function v1(r,e){return Yy(r,e)}function kS(r,e,t,n){this.tag=r,this.key=t,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 dn(r,e,t,n){return new kS(r,e,t,n)}function gf(r){return r=r.prototype,!(!r||!r.isReactComponent)}function ES(r){if(typeof r=="function")return gf(r)?1:0;if(r!=null){if(r=r.$$typeof,r===Bh)return 11;if(r===zh)return 14}return 2}function Ui(r,e){var t=r.alternate;return t===null?(t=dn(r.tag,e,r.key,r.mode),t.elementType=r.elementType,t.type=r.type,t.stateNode=r.stateNode,t.alternate=r,r.alternate=t):(t.pendingProps=e,t.type=r.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=r.flags&14680064,t.childLanes=r.childLanes,t.lanes=r.lanes,t.child=r.child,t.memoizedProps=r.memoizedProps,t.memoizedState=r.memoizedState,t.updateQueue=r.updateQueue,e=r.dependencies,t.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},t.sibling=r.sibling,t.index=r.index,t.ref=r.ref,t}function Tl(r,e,t,n,i,s){var o=2;if(n=r,typeof r=="function")gf(r)&&(o=1);else if(typeof r=="string")o=5;else e:switch(r){case Bs:return is(t.children,i,s,e);case Ph:o=8,i|=8;break;case nd:return r=dn(12,t,e,i|2),r.elementType=nd,r.lanes=s,r;case id:return r=dn(13,t,e,i),r.elementType=id,r.lanes=s,r;case sd:return r=dn(19,t,e,i),r.elementType=sd,r.lanes=s,r;case Uy:return xu(t,i,s,e);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case Ey:o=10;break e;case My:o=9;break e;case Bh:o=11;break e;case zh:o=14;break e;case pi:o=16,n=null;break e}throw Error(te(130,r==null?r:typeof r,""))}return e=dn(o,t,e,i),e.elementType=r,e.type=n,e.lanes=s,e}function is(r,e,t,n){return r=dn(7,r,n,e),r.lanes=t,r}function xu(r,e,t,n){return r=dn(22,r,n,e),r.elementType=Uy,r.lanes=t,r.stateNode={isHidden:!1},r}function zc(r,e,t){return r=dn(6,r,null,e),r.lanes=t,r}function Dc(r,e,t){return e=dn(4,r.children!==null?r.children:[],r.key,e),e.lanes=t,e.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},e}function MS(r,e,t,n,i){this.tag=e,this.containerInfo=r,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=gc(0),this.expirationTimes=gc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=gc(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function mf(r,e,t,n,i,s,o,a,l){return r=new MS(r,e,t,a,l),e===1?(e=1,s===!0&&(e|=8)):e=0,s=dn(3,null,null,e),r.current=s,s.stateNode=r,s.memoizedState={element:n,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},Qh(s),r}function US(r,e,t){var n=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Ps,key:n==null?null:""+n,children:r,containerInfo:e,implementation:t}}function w1(r){if(!r)return Bi;r=r._reactInternals;e:{if(fs(r)!==r||r.tag!==1)throw Error(te(170));var e=r;do{switch(e.tag){case 3:e=e.stateNode.context;break e;case 1:if(_r(e.type)){e=e.stateNode.__reactInternalMemoizedMergedChildContext;break e}}e=e.return}while(e!==null);throw Error(te(171))}if(r.tag===1){var t=r.type;if(_r(t))return w0(r,t,e)}return e}function C1(r,e,t,n,i,s,o,a,l){return r=mf(t,n,!0,r,i,s,o,a,l),r.context=w1(null),t=r.current,n=Ur(),i=Mi(t),s=Jn(n,i),s.callback=e??null,ki(t,s,i),r.current.lanes=i,Pa(r,i,n),$r(r,n),r}function Iu(r,e,t,n){var i=e.current,s=Ur(),o=Mi(i);return t=w1(t),e.context===null?e.context=t:e.pendingContext=t,e=Jn(s,o),e.payload={element:r},n=n===void 0?null:n,n!==null&&(e.callback=n),r=ki(i,e,o),r!==null&&(Un(r,i,o,s),Il(r,i,o)),o}function iu(r){if(r=r.current,!r.child)return null;switch(r.child.tag){case 5:return r.child.stateNode;default:return r.child.stateNode}}function Rg(r,e){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var t=r.retryLane;r.retryLane=t!==0&&t<e?t:e}}function yf(r,e){Rg(r,e),(r=r.alternate)&&Rg(r,e)}function AS(){return null}var b1=typeof reportError=="function"?reportError:function(r){console.error(r)};function vf(r){this._internalRoot=r}ku.prototype.render=vf.prototype.render=function(r){var e=this._internalRoot;if(e===null)throw Error(te(409));Iu(r,e,null,null)};ku.prototype.unmount=vf.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var e=r.containerInfo;cs(function(){Iu(null,r,null,null)}),e[ni]=null}};function ku(r){this._internalRoot=r}ku.prototype.unstable_scheduleHydration=function(r){if(r){var e=Qy();r={blockedOn:null,target:r,priority:e};for(var t=0;t<yi.length&&e!==0&&e<yi[t].priority;t++);yi.splice(t,0,r),t===0&&e0(r)}};function wf(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function Eu(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11&&(r.nodeType!==8||r.nodeValue!==" react-mount-point-unstable "))}function Pg(){}function TS(r,e,t,n,i){if(i){if(typeof n=="function"){var s=n;n=function(){var u=iu(o);s.call(u)}}var o=C1(e,n,r,0,null,!1,!1,"",Pg);return r._reactRootContainer=o,r[ni]=o.current,Ca(r.nodeType===8?r.parentNode:r),cs(),o}for(;i=r.lastChild;)r.removeChild(i);if(typeof n=="function"){var a=n;n=function(){var u=iu(l);a.call(u)}}var l=mf(r,0,!1,null,null,!1,!1,"",Pg);return r._reactRootContainer=l,r[ni]=l.current,Ca(r.nodeType===8?r.parentNode:r),cs(function(){Iu(e,l,t,n)}),l}function Mu(r,e,t,n,i){var s=t._reactRootContainer;if(s){var o=s;if(typeof i=="function"){var a=i;i=function(){var l=iu(o);a.call(l)}}Iu(e,o,r,i)}else o=TS(t,e,r,i,n);return iu(o)}Zy=function(r){switch(r.tag){case 3:var e=r.stateNode;if(e.current.memoizedState.isDehydrated){var t=Ho(e.pendingLanes);t!==0&&(Fh(e,t|1),$r(e,Rt()),!(De&6)&&(oo=Rt()+500,Fi()))}break;case 13:cs(function(){var n=ii(r,1);if(n!==null){var i=Ur();Un(n,r,1,i)}}),yf(r,1)}};Lh=function(r){if(r.tag===13){var e=ii(r,134217728);if(e!==null){var t=Ur();Un(e,r,134217728,t)}yf(r,134217728)}};qy=function(r){if(r.tag===13){var e=Mi(r),t=ii(r,e);if(t!==null){var n=Ur();Un(t,r,e,n)}yf(r,e)}};Qy=function(){return Xe};Jy=function(r,e){var t=Xe;try{return Xe=r,e()}finally{Xe=t}};gd=function(r,e,t){switch(e){case"input":if(ld(r,t),e=t.name,t.type==="radio"&&e!=null){for(t=r;t.parentNode;)t=t.parentNode;for(t=t.querySelectorAll("input[name="+JSON.stringify(""+e)+'][type="radio"]'),e=0;e<t.length;e++){var n=t[e];if(n!==r&&n.form===r.form){var i=yu(n);if(!i)throw Error(te(90));Ty(n),ld(n,i)}}}break;case"textarea":Py(r,t);break;case"select":e=t.value,e!=null&&Ws(r,!!t.multiple,e,!1)}};_y=hf;$y=cs;var RS={usingClientEntryPoint:!1,Events:[za,Fs,yu,Fy,Ly,hf]},Do={findFiberByHostInstance:es,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},PS={bundleType:Do.bundleType,version:Do.version,rendererPackageName:Do.rendererPackageName,rendererConfig:Do.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:oi.ReactCurrentDispatcher,findHostInstanceByFiber:function(r){return r=Hy(r),r===null?null:r.stateNode},findFiberByHostInstance:Do.findFiberByHostInstance||AS,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var al=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!al.isDisabled&&al.supportsFiber)try{fu=al.inject(PS),Vn=al}catch{}}en.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=RS;en.createPortal=function(r,e){var t=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!wf(e))throw Error(te(200));return US(r,e,null,t)};en.createRoot=function(r,e){if(!wf(r))throw Error(te(299));var t=!1,n="",i=b1;return e!=null&&(e.unstable_strictMode===!0&&(t=!0),e.identifierPrefix!==void 0&&(n=e.identifierPrefix),e.onRecoverableError!==void 0&&(i=e.onRecoverableError)),e=mf(r,1,!1,null,null,t,!1,n,i),r[ni]=e.current,Ca(r.nodeType===8?r.parentNode:r),new vf(e)};en.findDOMNode=function(r){if(r==null)return null;if(r.nodeType===1)return r;var e=r._reactInternals;if(e===void 0)throw typeof r.render=="function"?Error(te(188)):(r=Object.keys(r).join(","),Error(te(268,r)));return r=Hy(e),r=r===null?null:r.stateNode,r};en.flushSync=function(r){return cs(r)};en.hydrate=function(r,e,t){if(!Eu(e))throw Error(te(200));return Mu(null,r,e,!0,t)};en.hydrateRoot=function(r,e,t){if(!wf(r))throw Error(te(405));var n=t!=null&&t.hydratedSources||null,i=!1,s="",o=b1;if(t!=null&&(t.unstable_strictMode===!0&&(i=!0),t.identifierPrefix!==void 0&&(s=t.identifierPrefix),t.onRecoverableError!==void 0&&(o=t.onRecoverableError)),e=C1(e,null,r,1,t??null,i,!1,s,o),r[ni]=e.current,Ca(r),n)for(r=0;r<n.length;r++)t=n[r],i=t._getVersion,i=i(t._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[t,i]:e.mutableSourceEagerHydrationData.push(t,i);return new ku(e)};en.render=function(r,e,t){if(!Eu(e))throw Error(te(200));return Mu(null,r,e,!1,t)};en.unmountComponentAtNode=function(r){if(!Eu(r))throw Error(te(40));return r._reactRootContainer?(cs(function(){Mu(null,null,r,!1,function(){r._reactRootContainer=null,r[ni]=null})}),!0):!1};en.unstable_batchedUpdates=hf;en.unstable_renderSubtreeIntoContainer=function(r,e,t,n){if(!Eu(t))throw Error(te(200));if(r==null||r._reactInternals===void 0)throw Error(te(38));return Mu(r,e,t,!1,n)};en.version="18.3.1-next-f1338f8080-20240426";function S1(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(S1)}catch(r){console.error(r)}}S1(),Sy.exports=en;var BS=Sy.exports,Bg=BS;td.createRoot=Bg.createRoot,td.hydrateRoot=Bg.hydrateRoot;var x1=Object.defineProperty,zS=(r,e,t)=>e in r?x1(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ye=(r,e)=>x1(r,"name",{value:e,configurable:!0}),oa=(r,e,t)=>(zS(r,typeof e!="symbol"?e+"":e,t),t),ce=(r=>(r[r.Keyboard=0]="Keyboard",r[r.Mouse=1]="Mouse",r[r.Gamepad=2]="Gamepad",r[r.Touch=3]="Touch",r[r.TVRemote=4]="TVRemote",r[r.TextInput=5]="TextInput",r[r.Motion=6]="Motion",r[r.TouchZone=7]="TouchZone",r))(ce||{}),Ai=(r=>(r[r.KeyA=0]="KeyA",r[r.KeyB=1]="KeyB",r[r.KeyC=2]="KeyC",r[r.KeyD=3]="KeyD",r[r.KeyE=4]="KeyE",r[r.KeyF=5]="KeyF",r[r.KeyG=6]="KeyG",r[r.KeyH=7]="KeyH",r[r.KeyI=8]="KeyI",r[r.KeyJ=9]="KeyJ",r[r.KeyK=10]="KeyK",r[r.KeyL=11]="KeyL",r[r.KeyM=12]="KeyM",r[r.KeyN=13]="KeyN",r[r.KeyO=14]="KeyO",r[r.KeyP=15]="KeyP",r[r.KeyQ=16]="KeyQ",r[r.KeyR=17]="KeyR",r[r.KeyS=18]="KeyS",r[r.KeyT=19]="KeyT",r[r.KeyU=20]="KeyU",r[r.KeyV=21]="KeyV",r[r.KeyW=22]="KeyW",r[r.KeyX=23]="KeyX",r[r.KeyY=24]="KeyY",r[r.KeyZ=25]="KeyZ",r[r.Digit0=26]="Digit0",r[r.Digit1=27]="Digit1",r[r.Digit2=28]="Digit2",r[r.Digit3=29]="Digit3",r[r.Digit4=30]="Digit4",r[r.Digit5=31]="Digit5",r[r.Digit6=32]="Digit6",r[r.Digit7=33]="Digit7",r[r.Digit8=34]="Digit8",r[r.Digit9=35]="Digit9",r[r.ArrowUp=36]="ArrowUp",r[r.ArrowDown=37]="ArrowDown",r[r.ArrowLeft=38]="ArrowLeft",r[r.ArrowRight=39]="ArrowRight",r[r.Space=40]="Space",r[r.Enter=41]="Enter",r[r.Escape=42]="Escape",r[r.Backspace=43]="Backspace",r[r.Tab=44]="Tab",r[r.ShiftLeft=45]="ShiftLeft",r[r.ShiftRight=46]="ShiftRight",r[r.ControlLeft=47]="ControlLeft",r[r.ControlRight=48]="ControlRight",r[r.AltLeft=49]="AltLeft",r[r.AltRight=50]="AltRight",r[r.MetaLeft=51]="MetaLeft",r[r.MetaRight=52]="MetaRight",r[r.CapsLock=53]="CapsLock",r[r.Delete=54]="Delete",r[r.Insert=55]="Insert",r[r.Home=56]="Home",r[r.End=57]="End",r[r.PageUp=58]="PageUp",r[r.PageDown=59]="PageDown",r[r.F1=60]="F1",r[r.F2=61]="F2",r[r.F3=62]="F3",r[r.F4=63]="F4",r[r.F5=64]="F5",r[r.F6=65]="F6",r[r.F7=66]="F7",r[r.F8=67]="F8",r[r.F9=68]="F9",r[r.F10=69]="F10",r[r.F11=70]="F11",r[r.F12=71]="F12",r[r.Minus=72]="Minus",r[r.Equal=73]="Equal",r[r.BracketLeft=74]="BracketLeft",r[r.BracketRight=75]="BracketRight",r[r.Backslash=76]="Backslash",r[r.Semicolon=77]="Semicolon",r[r.Quote=78]="Quote",r[r.Comma=79]="Comma",r[r.Period=80]="Period",r[r.Slash=81]="Slash",r[r.Backquote=82]="Backquote",r[r.Numpad0=91]="Numpad0",r[r.Numpad1=92]="Numpad1",r[r.Numpad2=93]="Numpad2",r[r.Numpad3=94]="Numpad3",r[r.Numpad4=95]="Numpad4",r[r.Numpad5=96]="Numpad5",r[r.Numpad6=97]="Numpad6",r[r.Numpad7=98]="Numpad7",r[r.Numpad8=99]="Numpad8",r[r.Numpad9=100]="Numpad9",r[r.NumpadAdd=101]="NumpadAdd",r[r.NumpadSubtract=102]="NumpadSubtract",r[r.NumpadMultiply=103]="NumpadMultiply",r[r.NumpadDivide=104]="NumpadDivide",r[r.NumpadDecimal=105]="NumpadDecimal",r[r.NumpadEnter=106]="NumpadEnter",r[r.NumLock=107]="NumLock",r[r.PrintScreen=111]="PrintScreen",r[r.ScrollLock=112]="ScrollLock",r[r.Pause=113]="Pause",r[r.ContextMenu=114]="ContextMenu",r))(Ai||{});function DS(r){let e=Ai[r];return e!==void 0?e:null}Ye(DS,"keyCodeToKeyboardInput");function OS(r){return Ai[r]}Ye(OS,"keyboardInputToKeyCode");var Nt=(r=>(r[r.LeftButton=0]="LeftButton",r[r.MiddleButton=1]="MiddleButton",r[r.RightButton=2]="RightButton",r[r.Button4=3]="Button4",r[r.Button5=4]="Button5",r[r.PositionX=100]="PositionX",r[r.PositionY=101]="PositionY",r[r.DeltaX=102]="DeltaX",r[r.DeltaY=103]="DeltaY",r[r.WheelDeltaY=104]="WheelDeltaY",r[r.WheelDeltaX=105]="WheelDeltaX",r))(Nt||{});function FS(r){return r<100}Ye(FS,"isMouseButton");function LS(r){return r>=100}Ye(LS,"isMouseAxis");var Cf=(r=>(r[r.ButtonA=0]="ButtonA",r[r.ButtonB=1]="ButtonB",r[r.ButtonX=2]="ButtonX",r[r.ButtonY=3]="ButtonY",r[r.LeftShoulder=4]="LeftShoulder",r[r.RightShoulder=5]="RightShoulder",r[r.LeftTrigger=6]="LeftTrigger",r[r.RightTrigger=7]="RightTrigger",r[r.Select=8]="Select",r[r.Start=9]="Start",r[r.LeftStick=10]="LeftStick",r[r.RightStick=11]="RightStick",r[r.DPadUp=12]="DPadUp",r[r.DPadDown=13]="DPadDown",r[r.DPadLeft=14]="DPadLeft",r[r.DPadRight=15]="DPadRight",r[r.Home=16]="Home",r[r.Touchpad=17]="Touchpad",r[r.LeftStickX=100]="LeftStickX",r[r.LeftStickY=101]="LeftStickY",r[r.RightStickX=102]="RightStickX",r[r.RightStickY=103]="RightStickY",r[r.LeftTriggerAxis=104]="LeftTriggerAxis",r[r.RightTriggerAxis=105]="RightTriggerAxis",r))(Cf||{});function _S(r){return r<100}Ye(_S,"isGamepadButton");function $S(r){return r>=100}Ye($S,"isGamepadAxis");function NS(r){return r>=0&&r<=19?r:null}Ye(NS,"gamepadButtonIndexToInput");function VS(r){return{0:100,1:101,2:102,3:103}[r]??null}Ye(VS,"gamepadAxisIndexToInput");var bf=(r=>(r[r.Touch0=0]="Touch0",r[r.Touch1=1]="Touch1",r[r.Touch2=2]="Touch2",r[r.Touch3=3]="Touch3",r[r.Touch4=4]="Touch4",r[r.Touch5=5]="Touch5",r[r.Touch6=6]="Touch6",r[r.Touch7=7]="Touch7",r[r.Touch8=8]="Touch8",r[r.Touch9=9]="Touch9",r[r.Touch0X=100]="Touch0X",r[r.Touch0Y=101]="Touch0Y",r[r.Touch1X=102]="Touch1X",r[r.Touch1Y=103]="Touch1Y",r[r.Touch2X=104]="Touch2X",r[r.Touch2Y=105]="Touch2Y",r[r.Touch3X=106]="Touch3X",r[r.Touch3Y=107]="Touch3Y",r[r.Touch4X=108]="Touch4X",r[r.Touch4Y=109]="Touch4Y",r[r.Touch5X=110]="Touch5X",r[r.Touch5Y=111]="Touch5Y",r[r.Touch6X=112]="Touch6X",r[r.Touch6Y=113]="Touch6Y",r[r.Touch7X=114]="Touch7X",r[r.Touch7Y=115]="Touch7Y",r[r.Touch8X=116]="Touch8X",r[r.Touch8Y=117]="Touch8Y",r[r.Touch9X=118]="Touch9X",r[r.Touch9Y=119]="Touch9Y",r[r.PinchScale=200]="PinchScale",r[r.RotationAngle=201]="RotationAngle",r[r.SwipeVelocityX=202]="SwipeVelocityX",r[r.SwipeVelocityY=203]="SwipeVelocityY",r))(bf||{});function HS(r){return r<100}Ye(HS,"isTouchButton");function jS(r){return r>=100&&r<200}Ye(jS,"isTouchPosition");function YS(r){return r>=200}Ye(YS,"isTouchGesture");function WS(r){return r<0||r>9?null:100+r*2}Ye(WS,"getTouchXAxis");function GS(r){return r<0||r>9?null:101+r*2}Ye(GS,"getTouchYAxis");var Sf=(r=>(r[r.Zone0=0]="Zone0",r[r.Zone1=1]="Zone1",r[r.Zone2=2]="Zone2",r[r.Zone3=3]="Zone3",r[r.Zone4=4]="Zone4",r[r.Zone5=5]="Zone5",r[r.Zone6=6]="Zone6",r[r.Zone7=7]="Zone7",r[r.Zone8=8]="Zone8",r[r.Zone9=9]="Zone9",r[r.Zone10=10]="Zone10",r[r.Zone11=11]="Zone11",r[r.Zone12=12]="Zone12",r[r.Zone13=13]="Zone13",r[r.Zone14=14]="Zone14",r[r.Zone15=15]="Zone15",r[r.Zone16=16]="Zone16",r[r.Zone17=17]="Zone17",r[r.Zone18=18]="Zone18",r[r.Zone19=19]="Zone19",r[r.Zone20=20]="Zone20",r[r.Zone21=21]="Zone21",r[r.Zone22=22]="Zone22",r[r.Zone23=23]="Zone23",r[r.Zone24=24]="Zone24",r[r.Zone25=25]="Zone25",r[r.Zone26=26]="Zone26",r[r.Zone27=27]="Zone27",r[r.Zone28=28]="Zone28",r[r.Zone29=29]="Zone29",r[r.Zone30=30]="Zone30",r[r.Zone31=31]="Zone31",r[r.Zone0X=100]="Zone0X",r[r.Zone0Y=101]="Zone0Y",r[r.Zone1X=102]="Zone1X",r[r.Zone1Y=103]="Zone1Y",r[r.Zone2X=104]="Zone2X",r[r.Zone2Y=105]="Zone2Y",r[r.Zone3X=106]="Zone3X",r[r.Zone3Y=107]="Zone3Y",r[r.Zone4X=108]="Zone4X",r[r.Zone4Y=109]="Zone4Y",r[r.Zone5X=110]="Zone5X",r[r.Zone5Y=111]="Zone5Y",r[r.Zone6X=112]="Zone6X",r[r.Zone6Y=113]="Zone6Y",r[r.Zone7X=114]="Zone7X",r[r.Zone7Y=115]="Zone7Y",r[r.Zone8X=116]="Zone8X",r[r.Zone8Y=117]="Zone8Y",r[r.Zone9X=118]="Zone9X",r[r.Zone9Y=119]="Zone9Y",r[r.Zone10X=120]="Zone10X",r[r.Zone10Y=121]="Zone10Y",r[r.Zone11X=122]="Zone11X",r[r.Zone11Y=123]="Zone11Y",r[r.Zone12X=124]="Zone12X",r[r.Zone12Y=125]="Zone12Y",r[r.Zone13X=126]="Zone13X",r[r.Zone13Y=127]="Zone13Y",r[r.Zone14X=128]="Zone14X",r[r.Zone14Y=129]="Zone14Y",r[r.Zone15X=130]="Zone15X",r[r.Zone15Y=131]="Zone15Y",r[r.Zone16X=132]="Zone16X",r[r.Zone16Y=133]="Zone16Y",r[r.Zone17X=134]="Zone17X",r[r.Zone17Y=135]="Zone17Y",r[r.Zone18X=136]="Zone18X",r[r.Zone18Y=137]="Zone18Y",r[r.Zone19X=138]="Zone19X",r[r.Zone19Y=139]="Zone19Y",r[r.Zone20X=140]="Zone20X",r[r.Zone20Y=141]="Zone20Y",r[r.Zone21X=142]="Zone21X",r[r.Zone21Y=143]="Zone21Y",r[r.Zone22X=144]="Zone22X",r[r.Zone22Y=145]="Zone22Y",r[r.Zone23X=146]="Zone23X",r[r.Zone23Y=147]="Zone23Y",r[r.Zone24X=148]="Zone24X",r[r.Zone24Y=149]="Zone24Y",r[r.Zone25X=150]="Zone25X",r[r.Zone25Y=151]="Zone25Y",r[r.Zone26X=152]="Zone26X",r[r.Zone26Y=153]="Zone26Y",r[r.Zone27X=154]="Zone27X",r[r.Zone27Y=155]="Zone27Y",r[r.Zone28X=156]="Zone28X",r[r.Zone28Y=157]="Zone28Y",r[r.Zone29X=158]="Zone29X",r[r.Zone29Y=159]="Zone29Y",r[r.Zone30X=160]="Zone30X",r[r.Zone30Y=161]="Zone30Y",r[r.Zone31X=162]="Zone31X",r[r.Zone31Y=163]="Zone31Y",r))(Sf||{});function XS(r){return r<100}Ye(XS,"isTouchZoneButton");function KS(r){return r>=100}Ye(KS,"isTouchZonePosition");function ZS(r){return r<0||r>31?null:100+r*2}Ye(ZS,"getTouchZoneXAxis");function qS(r){return r<0||r>31?null:101+r*2}Ye(qS,"getTouchZoneYAxis");var xf=(r=>(r[r.DPadUp=0]="DPadUp",r[r.DPadDown=1]="DPadDown",r[r.DPadLeft=2]="DPadLeft",r[r.DPadRight=3]="DPadRight",r[r.DPadCenter=4]="DPadCenter",r[r.Play=5]="Play",r[r.Pause=6]="Pause",r[r.PlayPause=7]="PlayPause",r[r.Stop=8]="Stop",r[r.Rewind=9]="Rewind",r[r.FastForward=10]="FastForward",r[r.Previous=11]="Previous",r[r.Next=12]="Next",r[r.Record=13]="Record",r[r.VolumeUp=15]="VolumeUp",r[r.VolumeDown=16]="VolumeDown",r[r.Mute=17]="Mute",r[r.ChannelUp=18]="ChannelUp",r[r.ChannelDown=19]="ChannelDown",r[r.Back=20]="Back",r[r.Home=21]="Home",r[r.Menu=22]="Menu",r[r.Info=23]="Info",r[r.Guide=24]="Guide",r[r.Exit=25]="Exit",r[r.Red=30]="Red",r[r.Green=31]="Green",r[r.Yellow=32]="Yellow",r[r.Blue=33]="Blue",r[r.Digit0=40]="Digit0",r[r.Digit1=41]="Digit1",r[r.Digit2=42]="Digit2",r[r.Digit3=43]="Digit3",r[r.Digit4=44]="Digit4",r[r.Digit5=45]="Digit5",r[r.Digit6=46]="Digit6",r[r.Digit7=47]="Digit7",r[r.Digit8=48]="Digit8",r[r.Digit9=49]="Digit9",r[r.Input=50]="Input",r[r.Settings=51]="Settings",r[r.Subtitle=52]="Subtitle",r[r.Audio=53]="Audio",r[r.Power=54]="Power",r[r.PointerX=100]="PointerX",r[r.PointerY=101]="PointerY",r[r.GyroX=102]="GyroX",r[r.GyroY=103]="GyroY",r[r.GyroZ=104]="GyroZ",r))(xf||{});function QS(r){return r<100}Ye(QS,"isTVRemoteButton");function JS(r){return r>=100}Ye(JS,"isTVRemoteAxis");function ex(r,e){return{device:r,input:e}}Ye(ex,"createInputDescriptor");function aa(r){switch(r.device){case 0:return!0;case 1:return r.input<100;case 2:return r.input<100;case 3:return r.input<100;case 7:return r.input<100;case 4:return r.input<100;default:return!1}}Ye(aa,"isButton");function I1(r){return!aa(r)}Ye(I1,"isAxis");function tx(r){let e=new Uint8Array(3);return e[0]=r.device,e[1]=r.input&255,e[2]=r.input>>8&255,e}Ye(tx,"serializeInputDescriptor");function rx(r,e=0){let t=r[e],n=r[e+1]|r[e+2]<<8;return{device:t,input:n}}Ye(rx,"deserializeInputDescriptor");function nx(r){let e=ce[r.device],t;switch(r.device){case 0:t=Ai[r.input];break;case 1:t=Nt[r.input];break;case 2:t=Cf[r.input];break;case 3:t=bf[r.input];break;case 7:t=Sf[r.input];break;case 4:t=xf[r.input];break;default:t="Unknown"}return`${e}:${t}`}Ye(nx,"inputDescriptorToString");function ix(r){var s;let[e,t]=r.split(":");if(!e||!t)return null;let n=(s=Object.entries(ce).find(([o,a])=>o.toLowerCase()===e.toLowerCase()&&typeof a=="number"))==null?void 0:s[1];if(n===void 0)return null;let i;switch(n){case 0:i=Ai[t];break;case 1:i=Nt[t];break;case 2:i=Cf[t];break;case 3:i=bf[t];break;case 4:i=xf[t];break;case 7:i=Sf[t];break}return i===void 0?null:{device:n,input:i}}Ye(ix,"parseInputDescriptor");var k1=class Ir{constructor(e=0,t=0){oa(this,"x"),oa(this,"y"),this.x=e,this.y=t}static zero(){return new Ir(0,0)}static one(){return new Ir(1,1)}static up(){return new Ir(0,-1)}static down(){return new Ir(0,1)}static left(){return new Ir(-1,0)}static right(){return new Ir(1,0)}add(e){return new Ir(this.x+e.x,this.y+e.y)}subtract(e){return new Ir(this.x-e.x,this.y-e.y)}multiply(e){return new Ir(this.x*e,this.y*e)}divide(e){if(e===0)throw new Error("Division by zero");return new Ir(this.x/e,this.y/e)}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){let e=this.length();return e===0?Ir.zero():this.divide(e)}distance(e){return this.subtract(e).length()}distanceSquared(e){return this.subtract(e).lengthSquared()}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}rotate(e){let t=Math.cos(e),n=Math.sin(e);return new Ir(this.x*t-this.y*n,this.x*n+this.y*t)}lerp(e,t){return new Ir(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)}clone(){return new Ir(this.x,this.y)}equals(e){return this.x===e.x&&this.y===e.y}toString(){return`Vector2(${this.x}, ${this.y})`}toArray(){return[this.x,this.y]}set(e,t){return this.x=e,this.y=t,this}copy(e){return this.x=e.x,this.y=e.y,this}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e,this.y*=e,this}divideInPlace(e){if(e===0)throw new Error("Division by zero");return this.x/=e,this.y/=e,this}normalizeInPlace(){let e=this.length();return e===0?(this.x=0,this.y=0):(this.x/=e,this.y/=e),this}};Ye(k1,"Vector2");var Yt=k1,sx=class or{constructor(e=0,t=0,n=0){oa(this,"x"),oa(this,"y"),oa(this,"z"),this.x=e,this.y=t,this.z=n}static zero(){return new or(0,0,0)}static one(){return new or(1,1,1)}static up(){return new or(0,1,0)}static down(){return new or(0,-1,0)}static left(){return new or(-1,0,0)}static right(){return new or(1,0,0)}static forward(){return new or(0,0,1)}static back(){return new or(0,0,-1)}add(e){return new or(this.x+e.x,this.y+e.y,this.z+e.z)}subtract(e){return new or(this.x-e.x,this.y-e.y,this.z-e.z)}multiply(e){return new or(this.x*e,this.y*e,this.z*e)}divide(e){if(e===0)throw new Error("Division by zero");return new or(this.x/e,this.y/e,this.z/e)}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z}normalize(){let e=this.length();return e===0?or.zero():this.divide(e)}distance(e){return this.subtract(e).length()}distanceSquared(e){return this.subtract(e).lengthSquared()}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}cross(e){return new or(this.y*e.z-this.z*e.y,this.z*e.x-this.x*e.z,this.x*e.y-this.y*e.x)}lerp(e,t){return new or(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t,this.z+(e.z-this.z)*t)}clone(){return new or(this.x,this.y,this.z)}equals(e){return this.x===e.x&&this.y===e.y&&this.z===e.z}toString(){return`Vector3(${this.x}, ${this.y}, ${this.z})`}toArray(){return[this.x,this.y,this.z]}set(e,t,n){return this.x=e,this.y=t,this.z=n,this}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}addInPlace(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}multiplyInPlace(e){return this.x*=e,this.y*=e,this.z*=e,this}divideInPlace(e){if(e===0)throw new Error("Division by zero");return this.x/=e,this.y/=e,this.z/=e,this}normalizeInPlace(){let e=this.length();return e===0?(this.x=0,this.y=0,this.z=0):(this.x/=e,this.y/=e,this.z/=e),this}};Ye(sx,"Vector3");var Ge={scanlines:{opacity:.15,pattern:"horizontal",color:{r:0,g:0,b:0}},ambientEffect:{blur:30,scale:1.3,opacity:.7}},js={color:"rgba(144, 24, 24, 1)",lineWidth:1},Vt=(r=>(r.None="none",r.Eighth="eighth",r.Quarter="quarter",r.Half="half",r.Integer="integer",r.Responsive="responsive",r))(Vt||{}),ox=(r=>(r[r.None=0]="None",r[r.Eighth=1]="Eighth",r[r.Quarter=2]="Quarter",r[r.Half=3]="Half",r[r.Integer=4]="Integer",r[r.Responsive=5]="Responsive",r))(ox||{});function E1(r){switch(r){case"none":return 0;case"eighth":return 1;case"quarter":return 2;case"half":return 3;case"integer":return 4;case"responsive":return 5;default:return 0}}Ye(E1,"scalingModeToValue");function If(r){switch(r){case 0:return"none";case 1:return"eighth";case 2:return"quarter";case 3:return"half";case 4:return"integer";case 5:return"responsive";default:return"none"}}Ye(If,"valueToScalingMode");var yt=(r=>(r[r.Disconnected=0]="Disconnected",r[r.Connecting=1]="Connecting",r[r.Connected=2]="Connected",r[r.Reconnecting=3]="Reconnecting",r[r.Error=4]="Error",r))(yt||{}),ax=(r=>(r.SocketIO="socketio",r.WebRTC="webrtc",r))(ax||{}),M1=(r=>(r[r.Ping=0]="Ping",r[r.Pong=1]="Pong",r[r.Join=2]="Join",r[r.JoinResponse=3]="JoinResponse",r[r.SystemMessage=4]="SystemMessage",r[r.Input=16]="Input",r[r.Update=17]="Update",r[r.Audio=18]="Audio",r[r.Vibration=19]="Vibration",r[r.Load=48]="Load",r[r.Asset=49]="Asset",r))(M1||{});function lx(r){return r in M1}Ye(lx,"isNetworkEvent");var Oa=Object.defineProperty,ux=Object.getOwnPropertyDescriptor,cx=Object.getOwnPropertyNames,dx=Object.prototype.hasOwnProperty,hx=(r,e,t)=>e in r?Oa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,J=(r,e)=>Oa(r,"name",{value:e,configurable:!0}),ll=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')}),Uu=(r,e)=>()=>(r&&(e=r(r=0)),e),Au=(r,e)=>{for(var t in e)Oa(r,t,{get:e[t],enumerable:!0})},fx=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of cx(e))!dx.call(r,i)&&i!==t&&Oa(r,i,{get:()=>e[i],enumerable:!(n=ux(e,i))||n.enumerable});return r},ul=r=>fx(Oa({},"__esModule",{value:!0}),r),D=(r,e,t)=>(hx(r,typeof e!="symbol"?e+"":e,t),t),U1={};Au(U1,{VibrationOrderType:()=>Xd});var Xd,A1=Uu(()=>{Xd=(r=>(r[r.MobileVibrate=1]="MobileVibrate",r[r.MobileCancel=2]="MobileCancel",r[r.GamepadVibrate=16]="GamepadVibrate",r[r.GamepadCancel=17]="GamepadCancel",r))(Xd||{})}),T1={};Au(T1,{GamepadVibrateFlags:()=>Zd,MobileVibrateFlags:()=>Kd});var Kd,Zd,R1=Uu(()=>{Kd=(r=>(r[r.HasIntensity=1]="HasIntensity",r))(Kd||{}),Zd=(r=>(r[r.HasStartDelay=1]="HasStartDelay",r[r.AllGamepads=2]="AllGamepads",r))(Zd||{})}),P1={};Au(P1,{AudioOrderType:()=>qd,AudioTargetType:()=>Qd,getAudioOrderTypeName:()=>z1,isValidAudioOrderType:()=>B1});function B1(r){return r>=1&&r<=9}function z1(r){switch(r){case 1:return"PlaySound";case 2:return"PlayGlobalSound";case 3:return"StopSound";case 4:return"FadeOutSound";case 5:return"PauseSound";case 6:return"ResumeSound";case 7:return"SetListenerPosition";case 8:return"ConfigureSpatial";case 9:return"SetSoundEffects";default:return`UnknownAudio(0x${r.toString(16)})`}}var qd,Qd,D1=Uu(()=>{qd=(r=>(r[r.PlaySound=1]="PlaySound",r[r.PlayGlobalSound=2]="PlayGlobalSound",r[r.StopSound=3]="StopSound",r[r.FadeOutSound=4]="FadeOutSound",r[r.PauseSound=5]="PauseSound",r[r.ResumeSound=6]="ResumeSound",r[r.SetListenerPosition=7]="SetListenerPosition",r[r.ConfigureSpatial=8]="ConfigureSpatial",r[r.SetSoundEffects=9]="SetSoundEffects",r))(qd||{}),Qd=(r=>(r[r.InstanceId=0]="InstanceId",r[r.SoundId=1]="SoundId",r[r.All=2]="All",r))(Qd||{}),J(B1,"isValidAudioOrderType"),J(z1,"getAudioOrderTypeName")}),O1={};Au(O1,{PlaySoundFlags:()=>Jd,SoundEffectsFlags:()=>eh});var Jd,eh,F1=Uu(()=>{Jd=(r=>(r[r.Loop=1]="Loop",r[r.HasVolume=2]="HasVolume",r[r.HasPitch=4]="HasPitch",r[r.HasFadeIn=8]="HasFadeIn",r[r.HasPosition=16]="HasPosition",r[r.HasLowpass=32]="HasLowpass",r[r.HasHighpass=64]="HasHighpass",r[r.HasReverb=128]="HasReverb",r))(Jd||{}),eh=(r=>(r[r.HasLowpass=1]="HasLowpass",r[r.HasHighpass=2]="HasHighpass",r[r.HasReverb=4]="HasReverb",r))(eh||{})}),L1=class{constructor(e=0,t=60,n=40){if(D(this,"id"),D(this,"origin"),D(this,"size"),D(this,"commandSink"),D(this,"previousOrigin",new Yt(0,0)),D(this,"previousSize",new Yt(0,0)),D(this,"renderPasses"),e<0||e>255)throw new Error(`Display ID must be between 0 and 255, got ${e}`);if(t<1||t>256)throw new Error(`Display sizeX must be between 1 and 256, got ${t}`);if(n<1||n>256)throw new Error(`Display sizeY must be between 1 and 256, got ${n}`);this.id=e,this.origin=new Yt(0,0),this.size=new Yt(t,n)}getId(){return this.id}setCommandSink(e){this.commandSink=e}getOrigin(){return this.origin}setOrigin(e){this.origin=e}moveOrigin(e,t){this.origin.x+=e,this.origin.y+=t}hasOriginChanged(){return this.origin.x!==this.previousOrigin.x||this.origin.y!==this.previousOrigin.y}hasSizeChanged(){return this.size.x!==this.previousSize.x||this.size.y!==this.previousSize.y}hasChanged(){return this.hasOriginChanged()||this.hasSizeChanged()}resetChangeTracking(){this.previousOrigin.x=this.origin.x,this.previousOrigin.y=this.origin.y,this.previousSize.x=this.size.x,this.previousSize.y=this.size.y}getSize(){return this.size}setSize(e){if(e.x<1||e.x>256)throw new Error(`Display sizeX must be between 1 and 256, got ${e.x}`);if(e.y<1||e.y>256)throw new Error(`Display sizeY must be between 1 and 256, got ${e.y}`);this.size=e}getSink(){if(!this.commandSink)throw new Error("Display is not attached to a User");return this.commandSink}setPostProcess(e){this.getSink().setPostProcess(this.id,e)}setScanlinesEnabled(e){this.getSink().setScanlinesEnabled(this.id,e)}setScanlinesOpacity(e){this.getSink().setScanlinesOpacity(this.id,e)}setScanlinesPattern(e){this.getSink().setScanlinesPattern(this.id,e)}setAmbientEffect(e){this.getSink().setAmbientEffect(this.id,e)}setAmbientEffectEnabled(e){this.getSink().setAmbientEffectEnabled(this.id,e)}setAmbientEffectBlur(e){this.getSink().setAmbientEffectBlur(this.id,e)}setAmbientEffectScale(e){this.getSink().setAmbientEffectScale(this.id,e)}isAmbientEffectEnabled(){return this.getSink().isAmbientEffectEnabled(this.id)}getAmbientEffectConfig(){return this.getSink().getAmbientEffectConfig(this.id)}getPostProcessConfig(){return this.getSink().getPostProcessConfig(this.id)}setScalingMode(e){this.getSink().setScalingMode(this.id,e)}getScalingMode(){return this.getSink().getScalingMode(this.id)}setCellSize(e,t){this.getSink().setCellSize(this.id,e,t)}getCellSize(){return this.getSink().getCellSize(this.id)}setGrid(e){this.getSink().setGrid(this.id,e)}setGridEnabled(e){this.getSink().setGridEnabled(this.id,e)}isGridEnabled(){return this.getSink().isGridEnabled(this.id)}getGridConfig(){return this.getSink().getGridConfig(this.id)}switchPalette(e){this.getSink().switchPalette(this.id,e)}getCurrentPaletteSlotId(){return this.getSink().getCurrentPaletteSlotId(this.id)}getRenderPasses(){return this.renderPasses}setRenderPasses(e){if(!e||e.length===0){this.renderPasses=void 0;return}if(e.length>4)throw new Error(`renderPasses supports up to 4 entries, got ${e.length}`);this.renderPasses=e.map(t=>this.normalizePass(t))}normalizePass(e){let t=Math.max(0,Math.min(255,e.zMin)),n=Math.max(0,Math.min(255,e.zMax));if(t>n){let i=t;t=n,n=i}return{id:e.id,zMin:t,zMax:n,enabled:e.enabled!==!1}}getDebugInfo(){return{id:this.id,origin:{x:this.origin.x,y:this.origin.y},size:{x:this.size.x,y:this.size.y},renderPasses:this.renderPasses}}};J(L1,"Display");var px=L1,_1=J(r=>r?2:1,"charCodeByteSize"),gx=6,mx=6,yx=6,vx=7,wx=5,Cx=3,bx=1,Sx=6,xx=4,Ix=5,kx=2,Ex=8,Mx=7,Ux=7,Ax=8,Tx=10,Rx=6,Px=3,Bx=9,zx=15,Dx=51,Ox=5,Fx=6,Lx=4,_x=3,$x=3,Nx=4,Vx=5,Hx=4,jx=2,Yx=5,Wx=5,zg=5,Dg=5,Gx=3,Og=8,Fg=6,Lg=3,_g=8,$g=3,Ng=4,$1=class{constructor(e=65536,t=!1){D(this,"charCodes"),D(this,"fgColors"),D(this,"bgColors"),D(this,"size"),D(this,"is16bit"),this.size=e,this.is16bit=t,this.charCodes=t?new Uint16Array(e):new Uint8Array(e),this.fgColors=new Uint8Array(e),this.bgColors=new Uint8Array(e),this.clear()}clear(){this.charCodes.fill(0),this.fgColors.fill(255),this.bgColors.fill(255)}clearWithColor(e,t,n){let i=this.is16bit?e:e&255;this.charCodes.fill(i),this.fgColors.fill(t),this.bgColors.fill(n)}set(e,t,n,i){this.charCodes[e]=this.is16bit?t:t&255,this.fgColors[e]=n,this.bgColors[e]=i}fillCharsUniform(e,t,n,i){let s=this.is16bit?t:t&255;for(let o=0;o<e.length;o++){let a=e[o];this.charCodes[a]=s,this.fgColors[a]=n,this.bgColors[a]=i}}get(e){return{charCode:this.charCodes[e],fgColorCode:this.fgColors[e],bgColorCode:this.bgColors[e]}}setCharOnly(e,t){this.charCodes[e]=this.is16bit?t:t&255}setColorsOnly(e,t,n){this.fgColors[e]=t,this.bgColors[e]=n}getCharCode(e){return this.charCodes[e]}getFgColorCode(e){return this.fgColors[e]}getBgColorCode(e){return this.bgColors[e]}getRawCharCodes(){return this.charCodes}getRawFgColors(){return this.fgColors}getRawBgColors(){return this.bgColors}getSize(){return this.size}is16BitMode(){return this.is16bit}};J($1,"CellBuffer");var th=$1,N1=class{constructor(e){D(this,"data"),D(this,"size"),this.size=e,this.data=new Uint16Array(e)}clear(){this.data.fill(0)}set(e,t){this.data[e]=t}get(e){return this.data[e]}getRawData(){return this.data}getSize(){return this.size}};J(N1,"CharCodeBuffer");var Vg=N1,Xx=(r=>(r[r.Rectangle=1]="Rectangle",r[r.Circle=2]="Circle",r[r.Line=3]="Line",r[r.Ellipse=4]="Ellipse",r[r.Triangle=5]="Triangle",r))(Xx||{}),V1=class{constructor(){D(this,"currentWidth",256),D(this,"currentHeight",256)}rasterizeOrders(e,t,n,i,s){this.currentWidth=n,this.currentHeight=i,this.clearBuffer(t);for(let o of e)this.rasterizeOrder(o,t,s)}clearBuffer(e){e.clear()}rasterizeOrder(e,t,n){switch(e.type){case 1:this.rasterizeChar(e,t);break;case 2:this.rasterizeText(e,t);break;case 23:this.rasterizeTextMultiline(e,t);break;case 3:this.rasterizeSubFrame(e,t);break;case 4:this.rasterizeSubFrameMultiColor(e,t);break;case 5:this.rasterizeFullFrame(e,t);break;case 6:this.rasterizeFullFrameMultiColor(e,t);break;case 7:this.rasterizeSprite(e,t,n);break;case 8:this.rasterizeSpriteMultiColor(e,t,n);break;case 9:this.rasterizeColorMap(e,t);break;case 10:this.rasterizeShape(e,t);break;case 11:this.rasterizeDotCloud(e,t);break;case 12:this.rasterizeDotCloudMultiColor(e,t);break;case 17:this.rasterizeBitmask(e,t);break;case 18:this.rasterizeBitmask4(e,t);break;case 24:this.rasterizeBitmask16(e,t);break;case 25:this.rasterizePolyline(e,t);break;case 13:this.rasterizeSpriteCloud(e,t,n);break;case 14:this.rasterizeSpriteCloudMultiColor(e,t,n);break;case 15:this.rasterizeSpriteCloudVaried(e,t,n);break;case 16:this.rasterizeSpriteCloudVariedMultiColor(e,t,n);break;case 19:this.rasterizeFill(e,t);break;case 20:this.rasterizeFillChar(e,t);break;case 21:this.rasterizeFillSprite(e,t,n);break;case 22:this.rasterizeFillSpriteMultiColor(e,t,n);break}}rasterizeChar(e,t){let{posX:n,posY:i,charCode:s,bgColorCode:o,fgColorCode:a}=e;if(!this.isInBounds(n,i))return;let l=i*this.currentWidth+n;t.set(l,s,a,o)}rasterizeText(e,t){let{posX:n,posY:i,text:s,bgColorCode:o,fgColorCode:a}=e;if(this.isInBounds(n,i))for(let l=0;l<s.length;l++){let u=n+l;if(u>=this.currentWidth)break;let c=i*this.currentWidth+u,d=s.charCodeAt(l);t.set(c,d,a,o)}}rasterizeTextMultiline(e,t){let{posX:n,posY:i,text:s,bgColorCode:o,fgColorCode:a}=e,l=s.split(`
|
|
41
|
-
`),u=i;for(let c of l){if(u>=this.currentHeight)break;if(u>=0&&this.isInBounds(n,u))for(let d=0;d<c.length;d++){let h=n+d;if(h>=this.currentWidth)break;let f=u*this.currentWidth+h,p=c.charCodeAt(d);t.set(f,p,a,o)}u++}}rasterizeSubFrame(e,t){let{posX:n,posY:i,sizeX:s,sizeY:o,frame:a,bgColorCode:l,fgColorCode:u}=e;for(let c=0;c<o;c++){let d=i+c;if(!(d<0||d>=this.currentHeight))for(let h=0;h<s;h++){let f=n+h;if(f<0||f>=this.currentWidth)continue;let p=c*s+h;if(p>=a.length)break;let m=d*this.currentWidth+f;t.set(m,a[p],u,l)}}}rasterizeSubFrameMultiColor(e,t){let{posX:n,posY:i,sizeX:s,sizeY:o,frame:a}=e;for(let l=0;l<o;l++){let u=i+l;if(!(u<0||u>=this.currentHeight))for(let c=0;c<s;c++){let d=n+c;if(d<0||d>=this.currentWidth)continue;let h=l*s+c;if(h>=a.length)break;let f=a[h],p=u*this.currentWidth+d;t.set(p,f.charCode,f.fgColorCode,f.bgColorCode)}}}rasterizeFullFrame(e,t){let{frame:n,bgColorCode:i,fgColorCode:s}=e,o=this.currentWidth*this.currentHeight;for(let a=0;a<o&&a<n.length;a++)t.set(a,n[a],s,i)}rasterizeFullFrameMultiColor(e,t){let{frame:n}=e,i=this.currentWidth*this.currentHeight;for(let s=0;s<i&&s<n.length;s++){let o=n[s];t.set(s,o.charCode,o.fgColorCode,o.bgColorCode)}}rasterizeColorMap(e,t){let{posX:n,posY:i,sizeX:s,sizeY:o,colorData:a}=e;for(let l=0;l<o;l++){let u=i+l;if(!(u<0||u>=this.currentHeight))for(let c=0;c<s;c++){let d=n+c;if(d<0||d>=this.currentWidth)continue;let h=l*s+c;if(h>=a.length)break;let f=u*this.currentWidth+d,p=a[h];t.setColorsOnly(f,p.fgColorCode,p.bgColorCode)}}}rasterizeShape(e,t){let{shapeType:n,shapeData:i}=e;switch(n){case 1:this.rasterizeRectangle(i,t);break;case 2:this.rasterizeCircle(i,t);break;case 3:this.rasterizeLine(i,t);break;case 4:this.rasterizeEllipse(i,t);break;case 5:this.rasterizeTriangle(i,t);break}}rasterizeRectangle(e,t){let{posX:n,posY:i,width:s,height:o,filled:a,charCode:l,bgColorCode:u,fgColorCode:c}=e;if(a)for(let d=0;d<o;d++){let h=i+d;if(!(h<0||h>=this.currentHeight))for(let f=0;f<s;f++){let p=n+f;if(p<0||p>=this.currentWidth)continue;let m=h*this.currentWidth+p;t.set(m,l,c,u)}}else{for(let d=0;d<s;d++)this.setCell(n+d,i,l,u,c,t),this.setCell(n+d,i+o-1,l,u,c,t);for(let d=0;d<o;d++)this.setCell(n,i+d,l,u,c,t),this.setCell(n+s-1,i+d,l,u,c,t)}}rasterizeCircle(e,t){let{centerX:n,centerY:i,radius:s,filled:o,charCode:a,bgColorCode:l,fgColorCode:u}=e;if(o)for(let c=-s;c<=s;c++){let d=i+c;if(!(d<0||d>=this.currentHeight))for(let h=-s;h<=s;h++){let f=n+h;if(!(f<0||f>=this.currentWidth)&&h*h+c*c<=s*s){let p=d*this.currentWidth+f;t.set(p,a,u,l)}}}else{let c=s,d=0,h=0;for(;c>=d;)this.setCell(n+c,i+d,a,l,u,t),this.setCell(n+d,i+c,a,l,u,t),this.setCell(n-d,i+c,a,l,u,t),this.setCell(n-c,i+d,a,l,u,t),this.setCell(n-c,i-d,a,l,u,t),this.setCell(n-d,i-c,a,l,u,t),this.setCell(n+d,i-c,a,l,u,t),this.setCell(n+c,i-d,a,l,u,t),h<=0&&(d+=1,h+=2*d+1),h>0&&(c-=1,h-=2*c+1)}}rasterizeLine(e,t){let{x1:n,y1:i,x2:s,y2:o,charCode:a,bgColorCode:l,fgColorCode:u}=e,c=Math.abs(s-n),d=Math.abs(o-i),h=n<s?1:-1,f=i<o?1:-1,p=c-d,m=n,S=i;for(;this.setCell(m,S,a,l,u,t),!(m===s&&S===o);){let w=2*p;w>-d&&(p-=d,m+=h),w<c&&(p+=c,S+=f)}}rasterizePolyline(e,t){let{charCode:n,fgColorCode:i,bgColorCode:s,points:o}=e;if(o.length<2){o.length===1&&this.setCell(o[0].x,o[0].y,n,s,i,t);return}for(let a=0;a<o.length-1;a++){let l=o[a],u=o[a+1];this.rasterizeLineSegment(l.x,l.y,u.x,u.y,n,s,i,t)}}rasterizeLineSegment(e,t,n,i,s,o,a,l){let u=Math.abs(n-e),c=Math.abs(i-t),d=e<n?1:-1,h=t<i?1:-1,f=u-c,p=e,m=t;for(;this.setCell(p,m,s,o,a,l),!(p===n&&m===i);){let S=2*f;S>-c&&(f-=c,p+=d),S<u&&(f+=u,m+=h)}}rasterizeEllipse(e,t){let{centerX:n,centerY:i,radiusX:s,radiusY:o,filled:a,charCode:l,bgColorCode:u,fgColorCode:c}=e;if(a)for(let d=-o;d<=o;d++){let h=i+d;if(!(h<0||h>=this.currentHeight))for(let f=-s;f<=s;f++){let p=n+f;if(!(p<0||p>=this.currentWidth)&&f*f/(s*s)+d*d/(o*o)<=1){let m=h*this.currentWidth+p;t.set(m,l,c,u)}}}else{let d=Math.max(s,o)*8;for(let h=0;h<d;h++){let f=2*Math.PI*h/d,p=Math.round(n+s*Math.cos(f)),m=Math.round(i+o*Math.sin(f));this.setCell(p,m,l,u,c,t)}}}rasterizeTriangle(e,t){let{x1:n,y1:i,x2:s,y2:o,x3:a,y3:l,filled:u,charCode:c,bgColorCode:d,fgColorCode:h}=e;if(u){let f=[{x:n,y:i},{x:s,y:o},{x:a,y:l}].sort((y,C)=>y.y-C.y),[p,m,S]=f,w=J((y,C,x)=>{let I=Math.round(Math.min(C,x)),E=Math.round(Math.max(C,x));for(let A=I;A<=E;A++)if(A>=0&&A<this.currentWidth&&y>=0&&y<this.currentHeight){let R=y*this.currentWidth+A;t.set(R,c,h,d)}},"drawLine"),g=J((y,C,x,I,E)=>I===C?x:x+(y-C)*(E-x)/(I-C),"interpolate");for(let y=p.y;y<=m.y;y++){let C=g(y,p.y,p.x,S.y,S.x),x=g(y,p.y,p.x,m.y,m.x);w(y,C,x)}for(let y=m.y+1;y<=S.y;y++){let C=g(y,p.y,p.x,S.y,S.x),x=g(y,m.y,m.x,S.y,S.x);w(y,C,x)}}else this.drawLineSegment(n,i,s,o,c,d,h,t),this.drawLineSegment(s,o,a,l,c,d,h,t),this.drawLineSegment(a,l,n,i,c,d,h,t)}drawLineSegment(e,t,n,i,s,o,a,l){let u=Math.abs(n-e),c=Math.abs(i-t),d=e<n?1:-1,h=t<i?1:-1,f=u-c,p=e,m=t;for(;this.setCell(p,m,s,o,a,l),!(p===n&&m===i);){let S=2*f;S>-c&&(f-=c,p+=d),S<u&&(f+=u,m+=h)}}rasterizeDotCloud(e,t){let{charCode:n,bgColorCode:i,fgColorCode:s,positions:o}=e,a=this.currentWidth;for(let l=0;l<o.length;l++){let u=o[l];if(u.posX<0||u.posX>=a||u.posY<0||u.posY>=this.currentHeight)continue;let c=u.posY*a+u.posX;t.set(c,n,s,i)}}rasterizeDotCloudMultiColor(e,t){let{dots:n}=e;for(let i of n)this.setCell(i.posX,i.posY,i.charCode,i.bgColorCode,i.fgColorCode,t)}rasterizeBitmask(e,t){let{posX:n,posY:i,sizeX:s,sizeY:o,charCode:a,bgColorCode:l,fgColorCode:u,override:c,mask:d}=e;for(let h=0;h<o;h++){let f=i+h;if(!(f<0||f>=this.currentHeight))for(let p=0;p<s;p++){let m=n+p;if(m<0||m>=this.currentWidth)continue;let S=h*s+p,w=Math.floor(S/8),g=S%8,y=(d[w]&1<<g)!==0,C=f*this.currentWidth+m;y?t.set(C,a,u,l):c&&t.set(C,255,255,255)}}}rasterizeBitmask4(e,t){let{posX:n,posY:i,sizeX:s,sizeY:o,override:a,variants:l,mask:u}=e;for(let c=0;c<o;c++){let d=i+c;if(!(d<0||d>=this.currentHeight))for(let h=0;h<s;h++){let f=n+h;if(f<0||f>=this.currentWidth)continue;let p=c*s+h,m=Math.floor(p/4),S=p%4*2,w=u[m]>>S&3,g=d*this.currentWidth+f;if(w>0){let y=l[w-1];t.set(g,y.charCode,y.fgColorCode,y.bgColorCode)}else a&&t.set(g,255,255,255)}}}rasterizeBitmask16(e,t){let{posX:n,posY:i,sizeX:s,sizeY:o,override:a,variants:l,mask:u}=e;for(let c=0;c<o;c++){let d=i+c;if(!(d<0||d>=this.currentHeight))for(let h=0;h<s;h++){let f=n+h;if(f<0||f>=this.currentWidth)continue;let p=c*s+h,m=Math.floor(p/2),S=p%2*4,w=u[m]>>S&15,g=d*this.currentWidth+f;if(w>0){let y=l[w-1];t.set(g,y.charCode,y.fgColorCode,y.bgColorCode)}else a&&t.set(g,255,255,255)}}}rasterizeFill(e,t){let{charCode:n,bgColorCode:i,fgColorCode:s}=e;t.clearWithColor(n,s,i)}rasterizeFillChar(e,t){let{patternWidth:n,patternHeight:i,pattern:s,bgColorCode:o,fgColorCode:a}=e;for(let l=0;l<this.currentHeight;l++)for(let u=0;u<this.currentWidth;u++){let c=u%n,d=l%i*n+c;if(d<s.length){let h=l*this.currentWidth+u;t.set(h,s[d],a,o)}}}rasterizeSprite(e,t,n){if(!n)return;let{posX:i,posY:s,spriteIndex:o,bgColorCode:a,fgColorCode:l}=e,u=n.getUnicolorSprite(o);if(!u)return;let c=u.data;for(let d=0;d<u.sizeY;d++)for(let h=0;h<u.sizeX;h++){let f=i+h,p=s+d;if(!this.isInBounds(f,p))continue;let m=d*u.sizeX+h,S=c.get(m);this.setCell(f,p,S,a,l,t)}}rasterizeSpriteMultiColor(e,t,n){if(!n)return;let{posX:i,posY:s,spriteIndex:o}=e,a=n.getMulticolorSprite(o);if(!a)return;let l=a.data;for(let u=0;u<a.sizeY;u++)for(let c=0;c<a.sizeX;c++){let d=i+c,h=s+u;if(!this.isInBounds(d,h))continue;let f=u*a.sizeX+c,p=l.getCharCode(f),m=l.getFgColorCode(f),S=l.getBgColorCode(f);this.setCell(d,h,p,S,m,t)}}rasterizeSpriteCloud(e,t,n){if(!n)return;let{spriteIndex:i,bgColorCode:s,fgColorCode:o,positions:a}=e,l=n.getUnicolorSprite(i);if(l){if(l.sizeX===1&&l.sizeY===1){let u=l.data.get(0),c=this.currentWidth;for(let d=0;d<a.length;d++){let h=a[d];if(h.posX<0||h.posX>=c||h.posY<0||h.posY>=this.currentHeight)continue;let f=h.posY*c+h.posX;t.set(f,u,o,s)}return}for(let u=0;u<a.length;u++){let c=l.data;for(let d=0;d<l.sizeY;d++)for(let h=0;h<l.sizeX;h++){let f=a[u].posX+h,p=a[u].posY+d;if(!this.isInBounds(f,p))continue;let m=d*l.sizeX+h,S=c.get(m);this.setCell(f,p,S,s,o,t)}}}}rasterizeSpriteCloudMultiColor(e,t,n){if(!n)return;let{spriteIndex:i,positions:s}=e,o=n.getMulticolorSprite(i);if(o)for(let a=0;a<s.length;a++){let l=o.data;for(let u=0;u<o.sizeY;u++)for(let c=0;c<o.sizeX;c++){let d=s[a].posX+c,h=s[a].posY+u;if(!this.isInBounds(d,h))continue;let f=u*o.sizeX+c,p=l.getCharCode(f),m=l.getFgColorCode(f),S=l.getBgColorCode(f);this.setCell(d,h,p,S,m,t)}}}rasterizeSpriteCloudVaried(e,t,n){if(!n)return;let{sprites:i}=e;for(let s=0;s<i.length;s++){let o=i[s],a=n.getUnicolorSprite(o.spriteIndex);if(!a)continue;let l=a.data;for(let u=0;u<a.sizeY;u++)for(let c=0;c<a.sizeX;c++){let d=o.posX+c,h=o.posY+u;if(!this.isInBounds(d,h))continue;let f=u*a.sizeX+c,p=l.get(f);this.setCell(d,h,p,o.bgColorCode,o.fgColorCode,t)}}}rasterizeSpriteCloudVariedMultiColor(e,t,n){if(!n)return;let{sprites:i}=e;for(let s=0;s<i.length;s++){let o=i[s],a=n.getMulticolorSprite(o.spriteIndex);if(!a)continue;let l=a.data;for(let u=0;u<a.sizeY;u++)for(let c=0;c<a.sizeX;c++){let d=o.posX+c,h=o.posY+u;if(!this.isInBounds(d,h))continue;let f=u*a.sizeX+c,p=l.getCharCode(f),m=l.getFgColorCode(f),S=l.getBgColorCode(f);this.setCell(d,h,p,S,m,t)}}}rasterizeFillSprite(e,t,n){if(!n)return;let{spriteIndex:i,bgColorCode:s,fgColorCode:o}=e,a=n.getUnicolorSprite(i);if(!a)return;let l=a.data;for(let u=0;u<this.currentHeight;u++)for(let c=0;c<this.currentWidth;c++){let d=c%a.sizeX,h=u%a.sizeY*a.sizeX+d,f=l.get(h),p=u*this.currentWidth+c;t.set(p,f,o,s)}}rasterizeFillSpriteMultiColor(e,t,n){if(!n)return;let{spriteIndex:i}=e,s=n.getMulticolorSprite(i);if(!s)return;let o=s.data;for(let a=0;a<this.currentHeight;a++)for(let l=0;l<this.currentWidth;l++){let u=l%s.sizeX,c=a%s.sizeY*s.sizeX+u,d=o.getCharCode(c),h=o.getFgColorCode(c),f=o.getBgColorCode(c),p=a*this.currentWidth+l;t.set(p,d,h,f)}}setCell(e,t,n,i,s,o){if(!this.isInBounds(e,t))return;let a=t*this.currentWidth+e;o.set(a,n,s,i)}isInBounds(e,t){return e>=0&&e<this.currentWidth&&t>=0&&t<this.currentHeight}};J(V1,"LayerRasterizer");var Kx=V1,Oc=255,rh=class Yo{constructor(e,t,n,i,s){if(D(this,"id",0),D(this,"name"),D(this,"isMacroLayer"),D(this,"origin"),D(this,"orders",[]),D(this,"zOrder",0),D(this,"data"),D(this,"width"),D(this,"height"),D(this,"mustBeReliable",!1),D(this,"spriteRegistry"),D(this,"mode","server"),D(this,"charCodeMode"),D(this,"previousOrigin"),D(this,"previousZOrder"),D(this,"enabled",!0),D(this,"useSetMode",!1),D(this,"needsCommit",!1),n<1||n>256||i<1||i>256)throw new Error(`Layer size must be 1-256, got ${n}×${i}`);let o={};typeof s=="boolean"?o={mustBeReliable:s}:s&&(o=s),this.origin=e,this.zOrder=t,this.name=o.name,this.width=n,this.height=i,this.mustBeReliable=o.mustBeReliable??!1,this.isMacroLayer=o.isMacroLayer??!1,this.charCodeMode=o.charCodeMode??"8bit";let a=this.charCodeMode==="16bit";this.data=new th(n*i,a),this.previousOrigin=new Yt(e.x,e.y),this.previousZOrder=t}getIsMacroLayer(){return this.isMacroLayer}getCharCodeMode(){return this.charCodeMode}setMode(e){this.mode=e}setSpriteRegistry(e){this.spriteRegistry=e}getOrders(){return this.orders}addOrders(e){this.orders.push(...e),this.useSetMode=!1,(this.mode==="client"||this.mode==="standalone")&&Yo.rasterizer.rasterizeOrders(this.orders,this.data,this.width,this.height,this.spriteRegistry)}addTemporaryOrders(e){(this.mode==="client"||this.mode==="standalone")&&Yo.rasterizer.rasterizeOrders(e,this.data,this.width,this.height,this.spriteRegistry)}setOrders(e){this.orders=e,this.useSetMode=!0,(this.mode==="client"||this.mode==="standalone")&&Yo.rasterizer.rasterizeOrders(e,this.data,this.width,this.height,this.spriteRegistry)}clearOrders(){this.orders=[],(this.mode==="client"||this.mode==="standalone")&&Yo.rasterizer.clearBuffer(this.data)}getOrigin(){return this.origin}setOrigin(e){this.origin=e}getZOrder(){return this.zOrder}setZOrder(e){this.zOrder=e}getId(){return this.id}getName(){return this.name}setName(e){let t=typeof e=="string"?e.trim():void 0;this.name=t&&t.length>0?t:void 0}getDebugInfo(){return{id:this.id,name:this.name,z:this.zOrder,mustBeReliable:this.mustBeReliable,charCodeMode:this.charCodeMode,width:this.width,height:this.height,origin:{x:this.origin.x,y:this.origin.y},enabled:this.enabled,useSetMode:this.useSetMode,needsCommit:this.needsCommit,ordersCount:this.orders.length}}setIdInternal(e){this.id=e}getData(){return this.data}getWidth(){return this.width}getHeight(){return this.height}getCellAt(e,t){return e<0||e>=this.width||t<0||t>=this.height?null:this.data.get(t*this.width+e)}setMustBeReliable(e){this.mustBeReliable=e}getMustBeReliable(){return this.mustBeReliable}setEnabled(e){this.enabled=e}isEnabled(){return this.enabled}hasOriginChanged(){return this.origin.x!==this.previousOrigin.x||this.origin.y!==this.previousOrigin.y}hasZOrderChanged(){return this.zOrder!==this.previousZOrder}calculateUpdateFlags(){if(!this.enabled)return 0;let e=1;return this.useSetMode&&(e|=2),this.hasOriginChanged()&&(e|=4),this.hasZOrderChanged()&&(e|=8),(this.orders.length>0||this.needsCommit&&this.useSetMode)&&(e|=4),e}resetChangeTracking(){this.previousOrigin.x=this.origin.x,this.previousOrigin.y=this.origin.y,this.previousZOrder=this.zOrder}commit(){this.orders.length>Oc&&(console.error(`[UTSP] ⚠️ CRITICAL: Layer ${this.id} has ${this.orders.length} orders, but max is ${Oc}!
|
|
40
|
+
`+s.stack}return{value:r,source:e,stack:i,digest:null}}function Pc(r,e,t){return{value:r,source:null,stack:t??null,digest:e??null}}function zd(r,e){try{console.error(e.value)}catch(t){setTimeout(function(){throw t})}}var lS=typeof WeakMap=="function"?WeakMap:Map;function K0(r,e,t){t=Jn(-1,t),t.tag=3,t.payload={element:null};var n=e.value;return t.callback=function(){tu||(tu=!0,jd=n),zd(r,e)},t}function Z0(r,e,t){t=Jn(-1,t),t.tag=3;var n=r.type.getDerivedStateFromError;if(typeof n=="function"){var i=e.value;t.payload=function(){return n(i)},t.callback=function(){zd(r,e)}}var s=r.stateNode;return s!==null&&typeof s.componentDidCatch=="function"&&(t.callback=function(){zd(r,e),typeof n!="function"&&(Ei===null?Ei=new Set([this]):Ei.add(this));var o=e.stack;this.componentDidCatch(e.value,{componentStack:o!==null?o:""})}),t}function gg(r,e,t){var n=r.pingCache;if(n===null){n=r.pingCache=new lS;var i=new Set;n.set(e,i)}else i=n.get(e),i===void 0&&(i=new Set,n.set(e,i));i.has(t)||(i.add(t),r=SS.bind(null,r,e,t),e.then(r,r))}function mg(r){do{var e;if((e=r.tag===13)&&(e=r.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return r;r=r.return}while(r!==null);return null}function yg(r,e,t,n,i){return r.mode&1?(r.flags|=65536,r.lanes=i,r):(r===e?r.flags|=65536:(r.flags|=128,t.flags|=131072,t.flags&=-52805,t.tag===1&&(t.alternate===null?t.tag=17:(e=Jn(-1,1),e.tag=2,ki(t,e,1))),t.lanes|=1),r)}var uS=oi.ReactCurrentOwner,Fr=!1;function kr(r,e,t,n){e.child=r===null?k0(e,null,t,n):no(e,r.child,t,n)}function vg(r,e,t,n,i){t=t.render;var s=e.ref;return Zs(e,i),n=nf(r,e,t,n,s,i),t=sf(),r!==null&&!Fr?(e.updateQueue=r.updateQueue,e.flags&=-2053,r.lanes&=~i,si(r,e,i)):(vt&&t&&Yh(e),e.flags|=1,kr(r,e,n,i),e.child)}function wg(r,e,t,n,i){if(r===null){var s=t.type;return typeof s=="function"&&!gf(s)&&s.defaultProps===void 0&&t.compare===null&&t.defaultProps===void 0?(e.tag=15,e.type=s,q0(r,e,s,n,i)):(r=Tl(t.type,null,n,e,e.mode,i),r.ref=e.ref,r.return=e,e.child=r)}if(s=r.child,!(r.lanes&i)){var o=s.memoizedProps;if(t=t.compare,t=t!==null?t:wa,t(o,n)&&r.ref===e.ref)return si(r,e,i)}return e.flags|=1,r=Ui(s,n),r.ref=e.ref,r.return=e,e.child=r}function q0(r,e,t,n,i){if(r!==null){var s=r.memoizedProps;if(wa(s,n)&&r.ref===e.ref)if(Fr=!1,e.pendingProps=n=s,(r.lanes&i)!==0)r.flags&131072&&(Fr=!0);else return e.lanes=r.lanes,si(r,e,i)}return Od(r,e,t,n,i)}function Q0(r,e,t){var n=e.pendingProps,i=n.children,s=r!==null?r.memoizedState:null;if(n.mode==="hidden")if(!(e.mode&1))e.memoizedState={baseLanes:0,cachePool:null,transitions:null},rt(Hs,Gr),Gr|=t;else{if(!(t&1073741824))return r=s!==null?s.baseLanes|t:t,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:r,cachePool:null,transitions:null},e.updateQueue=null,rt(Hs,Gr),Gr|=r,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=s!==null?s.baseLanes:t,rt(Hs,Gr),Gr|=n}else s!==null?(n=s.baseLanes|t,e.memoizedState=null):n=t,rt(Hs,Gr),Gr|=n;return kr(r,e,i,t),e.child}function J0(r,e){var t=e.ref;(r===null&&t!==null||r!==null&&r.ref!==t)&&(e.flags|=512,e.flags|=2097152)}function Od(r,e,t,n,i){var s=_r(t)?os:vr.current;return s=to(e,s),Zs(e,i),t=nf(r,e,t,n,s,i),n=sf(),r!==null&&!Fr?(e.updateQueue=r.updateQueue,e.flags&=-2053,r.lanes&=~i,si(r,e,i)):(vt&&n&&Yh(e),e.flags|=1,kr(r,e,t,i),e.child)}function Cg(r,e,t,n,i){if(_r(t)){var s=!0;Yl(e)}else s=!1;if(Zs(e,i),e.stateNode===null)Ml(r,e),X0(e,t,n),Bd(e,t,n,i),n=!0;else if(r===null){var o=e.stateNode,a=e.memoizedProps;o.props=a;var l=o.context,u=t.contextType;typeof u=="object"&&u!==null?u=fn(u):(u=_r(t)?os:vr.current,u=to(e,u));var c=t.getDerivedStateFromProps,d=typeof c=="function"||typeof o.getSnapshotBeforeUpdate=="function";d||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==n||l!==u)&&pg(e,o,n,u),gi=!1;var h=e.memoizedState;o.state=h,Zl(e,n,o,i),l=e.memoizedState,a!==n||h!==l||Lr.current||gi?(typeof c=="function"&&(Pd(e,t,c,n),l=e.memoizedState),(a=gi||fg(e,t,a,n,h,l,u))?(d||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount=="function"&&(e.flags|=4194308)):(typeof o.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=n,e.memoizedState=l),o.props=n,o.state=l,o.context=u,n=a):(typeof o.componentDidMount=="function"&&(e.flags|=4194308),n=!1)}else{o=e.stateNode,M0(r,e),a=e.memoizedProps,u=e.type===e.elementType?a:bn(e.type,a),o.props=u,d=e.pendingProps,h=o.context,l=t.contextType,typeof l=="object"&&l!==null?l=fn(l):(l=_r(t)?os:vr.current,l=to(e,l));var f=t.getDerivedStateFromProps;(c=typeof f=="function"||typeof o.getSnapshotBeforeUpdate=="function")||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==d||h!==l)&&pg(e,o,n,l),gi=!1,h=e.memoizedState,o.state=h,Zl(e,n,o,i);var p=e.memoizedState;a!==d||h!==p||Lr.current||gi?(typeof f=="function"&&(Pd(e,t,f,n),p=e.memoizedState),(u=gi||fg(e,t,u,n,h,p,l)||!1)?(c||typeof o.UNSAFE_componentWillUpdate!="function"&&typeof o.componentWillUpdate!="function"||(typeof o.componentWillUpdate=="function"&&o.componentWillUpdate(n,p,l),typeof o.UNSAFE_componentWillUpdate=="function"&&o.UNSAFE_componentWillUpdate(n,p,l)),typeof o.componentDidUpdate=="function"&&(e.flags|=4),typeof o.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof o.componentDidUpdate!="function"||a===r.memoizedProps&&h===r.memoizedState||(e.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||a===r.memoizedProps&&h===r.memoizedState||(e.flags|=1024),e.memoizedProps=n,e.memoizedState=p),o.props=n,o.state=p,o.context=l,n=u):(typeof o.componentDidUpdate!="function"||a===r.memoizedProps&&h===r.memoizedState||(e.flags|=4),typeof o.getSnapshotBeforeUpdate!="function"||a===r.memoizedProps&&h===r.memoizedState||(e.flags|=1024),n=!1)}return Dd(r,e,t,n,s,i)}function Dd(r,e,t,n,i,s){J0(r,e);var o=(e.flags&128)!==0;if(!n&&!o)return i&&sg(e,t,!1),si(r,e,s);n=e.stateNode,uS.current=e;var a=o&&typeof t.getDerivedStateFromError!="function"?null:n.render();return e.flags|=1,r!==null&&o?(e.child=no(e,r.child,null,s),e.child=no(e,null,a,s)):kr(r,e,a,s),e.memoizedState=n.state,i&&sg(e,t,!0),e.child}function e1(r){var e=r.stateNode;e.pendingContext?ig(r,e.pendingContext,e.pendingContext!==e.context):e.context&&ig(r,e.context,!1),Jh(r,e.containerInfo)}function bg(r,e,t,n,i){return ro(),Gh(i),e.flags|=256,kr(r,e,t,n),e.child}var Fd={dehydrated:null,treeContext:null,retryLane:0};function Ld(r){return{baseLanes:r,cachePool:null,transitions:null}}function t1(r,e,t){var n=e.pendingProps,i=St.current,s=!1,o=(e.flags&128)!==0,a;if((a=o)||(a=r!==null&&r.memoizedState===null?!1:(i&2)!==0),a?(s=!0,e.flags&=-129):(r===null||r.memoizedState!==null)&&(i|=1),rt(St,i&1),r===null)return Td(e),r=e.memoizedState,r!==null&&(r=r.dehydrated,r!==null)?(e.mode&1?r.data==="$!"?e.lanes=8:e.lanes=1073741824:e.lanes=1,null):(o=n.children,r=n.fallback,s?(n=e.mode,s=e.child,o={mode:"hidden",children:o},!(n&1)&&s!==null?(s.childLanes=0,s.pendingProps=o):s=xu(o,n,0,null),r=is(r,n,t,null),s.return=e,r.return=e,s.sibling=r,e.child=s,e.child.memoizedState=Ld(t),e.memoizedState=Fd,r):lf(e,o));if(i=r.memoizedState,i!==null&&(a=i.dehydrated,a!==null))return cS(r,e,o,n,a,i,t);if(s){s=n.fallback,o=e.mode,i=r.child,a=i.sibling;var l={mode:"hidden",children:n.children};return!(o&1)&&e.child!==i?(n=e.child,n.childLanes=0,n.pendingProps=l,e.deletions=null):(n=Ui(i,l),n.subtreeFlags=i.subtreeFlags&14680064),a!==null?s=Ui(a,s):(s=is(s,o,t,null),s.flags|=2),s.return=e,n.return=e,n.sibling=s,e.child=n,n=s,s=e.child,o=r.child.memoizedState,o=o===null?Ld(t):{baseLanes:o.baseLanes|t,cachePool:null,transitions:o.transitions},s.memoizedState=o,s.childLanes=r.childLanes&~t,e.memoizedState=Fd,n}return s=r.child,r=s.sibling,n=Ui(s,{mode:"visible",children:n.children}),!(e.mode&1)&&(n.lanes=t),n.return=e,n.sibling=null,r!==null&&(t=e.deletions,t===null?(e.deletions=[r],e.flags|=16):t.push(r)),e.child=n,e.memoizedState=null,n}function lf(r,e){return e=xu({mode:"visible",children:e},r.mode,0,null),e.return=r,r.child=e}function il(r,e,t,n){return n!==null&&Gh(n),no(e,r.child,null,t),r=lf(e,e.pendingProps.children),r.flags|=2,e.memoizedState=null,r}function cS(r,e,t,n,i,s,o){if(t)return e.flags&256?(e.flags&=-257,n=Pc(Error(te(422))),il(r,e,o,n)):e.memoizedState!==null?(e.child=r.child,e.flags|=128,null):(s=n.fallback,i=e.mode,n=xu({mode:"visible",children:n.children},i,0,null),s=is(s,i,o,null),s.flags|=2,n.return=e,s.return=e,n.sibling=s,e.child=n,e.mode&1&&no(e,r.child,null,o),e.child.memoizedState=Ld(o),e.memoizedState=Fd,s);if(!(e.mode&1))return il(r,e,o,null);if(i.data==="$!"){if(n=i.nextSibling&&i.nextSibling.dataset,n)var a=n.dgst;return n=a,s=Error(te(419)),n=Pc(s,n,void 0),il(r,e,o,n)}if(a=(o&r.childLanes)!==0,Fr||a){if(n=nr,n!==null){switch(o&-o){case 4:i=2;break;case 16:i=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}i=i&(n.suspendedLanes|o)?0:i,i!==0&&i!==s.retryLane&&(s.retryLane=i,ii(r,i),Un(n,r,i,-1))}return pf(),n=Pc(Error(te(421))),il(r,e,o,n)}return i.data==="$?"?(e.flags|=128,e.child=r.child,e=xS.bind(null,r),i._reactRetry=e,null):(r=s.treeContext,Zr=Ii(i.nextSibling),qr=e,vt=!0,kn=null,r!==null&&(ln[un++]=qn,ln[un++]=Qn,ln[un++]=as,qn=r.id,Qn=r.overflow,as=e),e=lf(e,n.children),e.flags|=4096,e)}function Sg(r,e,t){r.lanes|=e;var n=r.alternate;n!==null&&(n.lanes|=e),Rd(r.return,e,t)}function Bc(r,e,t,n,i){var s=r.memoizedState;s===null?r.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:n,tail:t,tailMode:i}:(s.isBackwards=e,s.rendering=null,s.renderingStartTime=0,s.last=n,s.tail=t,s.tailMode=i)}function r1(r,e,t){var n=e.pendingProps,i=n.revealOrder,s=n.tail;if(kr(r,e,n.children,t),n=St.current,n&2)n=n&1|2,e.flags|=128;else{if(r!==null&&r.flags&128)e:for(r=e.child;r!==null;){if(r.tag===13)r.memoizedState!==null&&Sg(r,t,e);else if(r.tag===19)Sg(r,t,e);else if(r.child!==null){r.child.return=r,r=r.child;continue}if(r===e)break e;for(;r.sibling===null;){if(r.return===null||r.return===e)break e;r=r.return}r.sibling.return=r.return,r=r.sibling}n&=1}if(rt(St,n),!(e.mode&1))e.memoizedState=null;else switch(i){case"forwards":for(t=e.child,i=null;t!==null;)r=t.alternate,r!==null&&ql(r)===null&&(i=t),t=t.sibling;t=i,t===null?(i=e.child,e.child=null):(i=t.sibling,t.sibling=null),Bc(e,!1,i,t,s);break;case"backwards":for(t=null,i=e.child,e.child=null;i!==null;){if(r=i.alternate,r!==null&&ql(r)===null){e.child=i;break}r=i.sibling,i.sibling=t,t=i,i=r}Bc(e,!0,t,null,s);break;case"together":Bc(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function Ml(r,e){!(e.mode&1)&&r!==null&&(r.alternate=null,e.alternate=null,e.flags|=2)}function si(r,e,t){if(r!==null&&(e.dependencies=r.dependencies),us|=e.lanes,!(t&e.childLanes))return null;if(r!==null&&e.child!==r.child)throw Error(te(153));if(e.child!==null){for(r=e.child,t=Ui(r,r.pendingProps),e.child=t,t.return=e;r.sibling!==null;)r=r.sibling,t=t.sibling=Ui(r,r.pendingProps),t.return=e;t.sibling=null}return e.child}function dS(r,e,t){switch(e.tag){case 3:e1(e),ro();break;case 5:U0(e);break;case 1:_r(e.type)&&Yl(e);break;case 4:Jh(e,e.stateNode.containerInfo);break;case 10:var n=e.type._context,i=e.memoizedProps.value;rt(Xl,n._currentValue),n._currentValue=i;break;case 13:if(n=e.memoizedState,n!==null)return n.dehydrated!==null?(rt(St,St.current&1),e.flags|=128,null):t&e.child.childLanes?t1(r,e,t):(rt(St,St.current&1),r=si(r,e,t),r!==null?r.sibling:null);rt(St,St.current&1);break;case 19:if(n=(t&e.childLanes)!==0,r.flags&128){if(n)return r1(r,e,t);e.flags|=128}if(i=e.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),rt(St,St.current),n)break;return null;case 22:case 23:return e.lanes=0,Q0(r,e,t)}return si(r,e,t)}var n1,_d,i1,s1;n1=function(r,e){for(var t=e.child;t!==null;){if(t.tag===5||t.tag===6)r.appendChild(t.stateNode);else if(t.tag!==4&&t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return;t=t.return}t.sibling.return=t.return,t=t.sibling}};_d=function(){};i1=function(r,e,t,n){var i=r.memoizedProps;if(i!==n){r=e.stateNode,rs(Hn.current);var s=null;switch(t){case"input":i=ad(r,i),n=ad(r,n),s=[];break;case"select":i=It({},i,{value:void 0}),n=It({},n,{value:void 0}),s=[];break;case"textarea":i=cd(r,i),n=cd(r,n),s=[];break;default:typeof i.onClick!="function"&&typeof n.onClick=="function"&&(r.onclick=Hl)}hd(t,n);var o;t=null;for(u in i)if(!n.hasOwnProperty(u)&&i.hasOwnProperty(u)&&i[u]!=null)if(u==="style"){var a=i[u];for(o in a)a.hasOwnProperty(o)&&(t||(t={}),t[o]="")}else u!=="dangerouslySetInnerHTML"&&u!=="children"&&u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&u!=="autoFocus"&&(ha.hasOwnProperty(u)?s||(s=[]):(s=s||[]).push(u,null));for(u in n){var l=n[u];if(a=i!=null?i[u]:void 0,n.hasOwnProperty(u)&&l!==a&&(l!=null||a!=null))if(u==="style")if(a){for(o in a)!a.hasOwnProperty(o)||l&&l.hasOwnProperty(o)||(t||(t={}),t[o]="");for(o in l)l.hasOwnProperty(o)&&a[o]!==l[o]&&(t||(t={}),t[o]=l[o])}else t||(s||(s=[]),s.push(u,t)),t=l;else u==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,a=a?a.__html:void 0,l!=null&&a!==l&&(s=s||[]).push(u,l)):u==="children"?typeof l!="string"&&typeof l!="number"||(s=s||[]).push(u,""+l):u!=="suppressContentEditableWarning"&&u!=="suppressHydrationWarning"&&(ha.hasOwnProperty(u)?(l!=null&&u==="onScroll"&&at("scroll",r),s||a===l||(s=[])):(s=s||[]).push(u,l))}t&&(s=s||[]).push("style",t);var u=s;(e.updateQueue=u)&&(e.flags|=4)}};s1=function(r,e,t,n){t!==n&&(e.flags|=4)};function zo(r,e){if(!vt)switch(r.tailMode){case"hidden":e=r.tail;for(var t=null;e!==null;)e.alternate!==null&&(t=e),e=e.sibling;t===null?r.tail=null:t.sibling=null;break;case"collapsed":t=r.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e||r.tail===null?r.tail=null:r.tail.sibling=null:n.sibling=null}}function pr(r){var e=r.alternate!==null&&r.alternate.child===r.child,t=0,n=0;if(e)for(var i=r.child;i!==null;)t|=i.lanes|i.childLanes,n|=i.subtreeFlags&14680064,n|=i.flags&14680064,i.return=r,i=i.sibling;else for(i=r.child;i!==null;)t|=i.lanes|i.childLanes,n|=i.subtreeFlags,n|=i.flags,i.return=r,i=i.sibling;return r.subtreeFlags|=n,r.childLanes=t,e}function hS(r,e,t){var n=e.pendingProps;switch(Wh(e),e.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return pr(e),null;case 1:return _r(e.type)&&jl(),pr(e),null;case 3:return n=e.stateNode,io(),ct(Lr),ct(vr),tf(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(r===null||r.child===null)&&(rl(e)?e.flags|=4:r===null||r.memoizedState.isDehydrated&&!(e.flags&256)||(e.flags|=1024,kn!==null&&(Gd(kn),kn=null))),_d(r,e),pr(e),null;case 5:ef(e);var i=rs(Ia.current);if(t=e.type,r!==null&&e.stateNode!=null)i1(r,e,t,n,i),r.ref!==e.ref&&(e.flags|=512,e.flags|=2097152);else{if(!n){if(e.stateNode===null)throw Error(te(166));return pr(e),null}if(r=rs(Hn.current),rl(e)){n=e.stateNode,t=e.type;var s=e.memoizedProps;switch(n[Nn]=e,n[Sa]=s,r=(e.mode&1)!==0,t){case"dialog":at("cancel",n),at("close",n);break;case"iframe":case"object":case"embed":at("load",n);break;case"video":case"audio":for(i=0;i<jo.length;i++)at(jo[i],n);break;case"source":at("error",n);break;case"img":case"image":case"link":at("error",n),at("load",n);break;case"details":at("toggle",n);break;case"input":Rp(n,s),at("invalid",n);break;case"select":n._wrapperState={wasMultiple:!!s.multiple},at("invalid",n);break;case"textarea":Bp(n,s),at("invalid",n)}hd(t,s),i=null;for(var o in s)if(s.hasOwnProperty(o)){var a=s[o];o==="children"?typeof a=="string"?n.textContent!==a&&(s.suppressHydrationWarning!==!0&&tl(n.textContent,a,r),i=["children",a]):typeof a=="number"&&n.textContent!==""+a&&(s.suppressHydrationWarning!==!0&&tl(n.textContent,a,r),i=["children",""+a]):ha.hasOwnProperty(o)&&a!=null&&o==="onScroll"&&at("scroll",n)}switch(t){case"input":Ga(n),Pp(n,s,!0);break;case"textarea":Ga(n),zp(n);break;case"select":case"option":break;default:typeof s.onClick=="function"&&(n.onclick=Hl)}n=i,e.updateQueue=n,n!==null&&(e.flags|=4)}else{o=i.nodeType===9?i:i.ownerDocument,r==="http://www.w3.org/1999/xhtml"&&(r=By(t)),r==="http://www.w3.org/1999/xhtml"?t==="script"?(r=o.createElement("div"),r.innerHTML="<script><\/script>",r=r.removeChild(r.firstChild)):typeof n.is=="string"?r=o.createElement(t,{is:n.is}):(r=o.createElement(t),t==="select"&&(o=r,n.multiple?o.multiple=!0:n.size&&(o.size=n.size))):r=o.createElementNS(r,t),r[Nn]=e,r[Sa]=n,n1(r,e,!1,!1),e.stateNode=r;e:{switch(o=fd(t,n),t){case"dialog":at("cancel",r),at("close",r),i=n;break;case"iframe":case"object":case"embed":at("load",r),i=n;break;case"video":case"audio":for(i=0;i<jo.length;i++)at(jo[i],r);i=n;break;case"source":at("error",r),i=n;break;case"img":case"image":case"link":at("error",r),at("load",r),i=n;break;case"details":at("toggle",r),i=n;break;case"input":Rp(r,n),i=ad(r,n),at("invalid",r);break;case"option":i=n;break;case"select":r._wrapperState={wasMultiple:!!n.multiple},i=It({},n,{value:void 0}),at("invalid",r);break;case"textarea":Bp(r,n),i=cd(r,n),at("invalid",r);break;default:i=n}hd(t,i),a=i;for(s in a)if(a.hasOwnProperty(s)){var l=a[s];s==="style"?Dy(r,l):s==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,l!=null&&zy(r,l)):s==="children"?typeof l=="string"?(t!=="textarea"||l!=="")&&fa(r,l):typeof l=="number"&&fa(r,""+l):s!=="suppressContentEditableWarning"&&s!=="suppressHydrationWarning"&&s!=="autoFocus"&&(ha.hasOwnProperty(s)?l!=null&&s==="onScroll"&&at("scroll",r):l!=null&&Rh(r,s,l,o))}switch(t){case"input":Ga(r),Pp(r,n,!1);break;case"textarea":Ga(r),zp(r);break;case"option":n.value!=null&&r.setAttribute("value",""+Pi(n.value));break;case"select":r.multiple=!!n.multiple,s=n.value,s!=null?Ws(r,!!n.multiple,s,!1):n.defaultValue!=null&&Ws(r,!!n.multiple,n.defaultValue,!0);break;default:typeof i.onClick=="function"&&(r.onclick=Hl)}switch(t){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break e;case"img":n=!0;break e;default:n=!1}}n&&(e.flags|=4)}e.ref!==null&&(e.flags|=512,e.flags|=2097152)}return pr(e),null;case 6:if(r&&e.stateNode!=null)s1(r,e,r.memoizedProps,n);else{if(typeof n!="string"&&e.stateNode===null)throw Error(te(166));if(t=rs(Ia.current),rs(Hn.current),rl(e)){if(n=e.stateNode,t=e.memoizedProps,n[Nn]=e,(s=n.nodeValue!==t)&&(r=qr,r!==null))switch(r.tag){case 3:tl(n.nodeValue,t,(r.mode&1)!==0);break;case 5:r.memoizedProps.suppressHydrationWarning!==!0&&tl(n.nodeValue,t,(r.mode&1)!==0)}s&&(e.flags|=4)}else n=(t.nodeType===9?t:t.ownerDocument).createTextNode(n),n[Nn]=e,e.stateNode=n}return pr(e),null;case 13:if(ct(St),n=e.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(vt&&Zr!==null&&e.mode&1&&!(e.flags&128))x0(),ro(),e.flags|=98560,s=!1;else if(s=rl(e),n!==null&&n.dehydrated!==null){if(r===null){if(!s)throw Error(te(318));if(s=e.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(te(317));s[Nn]=e}else ro(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;pr(e),s=!1}else kn!==null&&(Gd(kn),kn=null),s=!0;if(!s)return e.flags&65536?e:null}return e.flags&128?(e.lanes=t,e):(n=n!==null,n!==(r!==null&&r.memoizedState!==null)&&n&&(e.child.flags|=8192,e.mode&1&&(r===null||St.current&1?Wt===0&&(Wt=3):pf())),e.updateQueue!==null&&(e.flags|=4),pr(e),null);case 4:return io(),_d(r,e),r===null&&Ca(e.stateNode.containerInfo),pr(e),null;case 10:return Zh(e.type._context),pr(e),null;case 17:return _r(e.type)&&jl(),pr(e),null;case 19:if(ct(St),s=e.memoizedState,s===null)return pr(e),null;if(n=(e.flags&128)!==0,o=s.rendering,o===null)if(n)zo(s,!1);else{if(Wt!==0||r!==null&&r.flags&128)for(r=e.child;r!==null;){if(o=ql(r),o!==null){for(e.flags|=128,zo(s,!1),n=o.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),e.subtreeFlags=0,n=t,t=e.child;t!==null;)s=t,r=n,s.flags&=14680066,o=s.alternate,o===null?(s.childLanes=0,s.lanes=r,s.child=null,s.subtreeFlags=0,s.memoizedProps=null,s.memoizedState=null,s.updateQueue=null,s.dependencies=null,s.stateNode=null):(s.childLanes=o.childLanes,s.lanes=o.lanes,s.child=o.child,s.subtreeFlags=0,s.deletions=null,s.memoizedProps=o.memoizedProps,s.memoizedState=o.memoizedState,s.updateQueue=o.updateQueue,s.type=o.type,r=o.dependencies,s.dependencies=r===null?null:{lanes:r.lanes,firstContext:r.firstContext}),t=t.sibling;return rt(St,St.current&1|2),e.child}r=r.sibling}s.tail!==null&&Rt()>oo&&(e.flags|=128,n=!0,zo(s,!1),e.lanes=4194304)}else{if(!n)if(r=ql(o),r!==null){if(e.flags|=128,n=!0,t=r.updateQueue,t!==null&&(e.updateQueue=t,e.flags|=4),zo(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!vt)return pr(e),null}else 2*Rt()-s.renderingStartTime>oo&&t!==1073741824&&(e.flags|=128,n=!0,zo(s,!1),e.lanes=4194304);s.isBackwards?(o.sibling=e.child,e.child=o):(t=s.last,t!==null?t.sibling=o:e.child=o,s.last=o)}return s.tail!==null?(e=s.tail,s.rendering=e,s.tail=e.sibling,s.renderingStartTime=Rt(),e.sibling=null,t=St.current,rt(St,n?t&1|2:t&1),e):(pr(e),null);case 22:case 23:return ff(),n=e.memoizedState!==null,r!==null&&r.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?Gr&1073741824&&(pr(e),e.subtreeFlags&6&&(e.flags|=8192)):pr(e),null;case 24:return null;case 25:return null}throw Error(te(156,e.tag))}function fS(r,e){switch(Wh(e),e.tag){case 1:return _r(e.type)&&jl(),r=e.flags,r&65536?(e.flags=r&-65537|128,e):null;case 3:return io(),ct(Lr),ct(vr),tf(),r=e.flags,r&65536&&!(r&128)?(e.flags=r&-65537|128,e):null;case 5:return ef(e),null;case 13:if(ct(St),r=e.memoizedState,r!==null&&r.dehydrated!==null){if(e.alternate===null)throw Error(te(340));ro()}return r=e.flags,r&65536?(e.flags=r&-65537|128,e):null;case 19:return ct(St),null;case 4:return io(),null;case 10:return Zh(e.type._context),null;case 22:case 23:return ff(),null;case 24:return null;default:return null}}var sl=!1,mr=!1,pS=typeof WeakSet=="function"?WeakSet:Set,fe=null;function Vs(r,e){var t=r.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(n){Ut(r,e,n)}else t.current=null}function $d(r,e,t){try{t()}catch(n){Ut(r,e,n)}}var xg=!1;function gS(r,e){if(xd=$l,r=c0(),jh(r)){if("selectionStart"in r)var t={start:r.selectionStart,end:r.selectionEnd};else e:{t=(t=r.ownerDocument)&&t.defaultView||window;var n=t.getSelection&&t.getSelection();if(n&&n.rangeCount!==0){t=n.anchorNode;var i=n.anchorOffset,s=n.focusNode;n=n.focusOffset;try{t.nodeType,s.nodeType}catch{t=null;break e}var o=0,a=-1,l=-1,u=0,c=0,d=r,h=null;t:for(;;){for(var f;d!==t||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),(f=d.firstChild)!==null;)h=d,d=f;for(;;){if(d===r)break t;if(h===t&&++u===i&&(a=o),h===s&&++c===n&&(l=o),(f=d.nextSibling)!==null)break;d=h,h=d.parentNode}d=f}t=a===-1||l===-1?null:{start:a,end:l}}else t=null}t=t||{start:0,end:0}}else t=null;for(Id={focusedElem:r,selectionRange:t},$l=!1,fe=e;fe!==null;)if(e=fe,r=e.child,(e.subtreeFlags&1028)!==0&&r!==null)r.return=e,fe=r;else for(;fe!==null;){e=fe;try{var p=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(p!==null){var m=p.memoizedProps,S=p.memoizedState,w=e.stateNode,g=w.getSnapshotBeforeUpdate(e.elementType===e.type?m:bn(e.type,m),S);w.__reactInternalSnapshotBeforeUpdate=g}break;case 3:var y=e.stateNode.containerInfo;y.nodeType===1?y.textContent="":y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(te(163))}}catch(C){Ut(e,e.return,C)}if(r=e.sibling,r!==null){r.return=e.return,fe=r;break}fe=e.return}return p=xg,xg=!1,p}function na(r,e,t){var n=e.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var i=n=n.next;do{if((i.tag&r)===r){var s=i.destroy;i.destroy=void 0,s!==void 0&&$d(e,t,s)}i=i.next}while(i!==n)}}function bu(r,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var t=e=e.next;do{if((t.tag&r)===r){var n=t.create;t.destroy=n()}t=t.next}while(t!==e)}}function Nd(r){var e=r.ref;if(e!==null){var t=r.stateNode;switch(r.tag){case 5:r=t;break;default:r=t}typeof e=="function"?e(r):e.current=r}}function o1(r){var e=r.alternate;e!==null&&(r.alternate=null,o1(e)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(e=r.stateNode,e!==null&&(delete e[Nn],delete e[Sa],delete e[Md],delete e[q2],delete e[Q2])),r.stateNode=null,r.return=null,r.dependencies=null,r.memoizedProps=null,r.memoizedState=null,r.pendingProps=null,r.stateNode=null,r.updateQueue=null}function a1(r){return r.tag===5||r.tag===3||r.tag===4}function Ig(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||a1(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function Vd(r,e,t){var n=r.tag;if(n===5||n===6)r=r.stateNode,e?t.nodeType===8?t.parentNode.insertBefore(r,e):t.insertBefore(r,e):(t.nodeType===8?(e=t.parentNode,e.insertBefore(r,t)):(e=t,e.appendChild(r)),t=t._reactRootContainer,t!=null||e.onclick!==null||(e.onclick=Hl));else if(n!==4&&(r=r.child,r!==null))for(Vd(r,e,t),r=r.sibling;r!==null;)Vd(r,e,t),r=r.sibling}function Hd(r,e,t){var n=r.tag;if(n===5||n===6)r=r.stateNode,e?t.insertBefore(r,e):t.appendChild(r);else if(n!==4&&(r=r.child,r!==null))for(Hd(r,e,t),r=r.sibling;r!==null;)Hd(r,e,t),r=r.sibling}var ar=null,Sn=!1;function fi(r,e,t){for(t=t.child;t!==null;)l1(r,e,t),t=t.sibling}function l1(r,e,t){if(Vn&&typeof Vn.onCommitFiberUnmount=="function")try{Vn.onCommitFiberUnmount(fu,t)}catch{}switch(t.tag){case 5:mr||Vs(t,e);case 6:var n=ar,i=Sn;ar=null,fi(r,e,t),ar=n,Sn=i,ar!==null&&(Sn?(r=ar,t=t.stateNode,r.nodeType===8?r.parentNode.removeChild(t):r.removeChild(t)):ar.removeChild(t.stateNode));break;case 18:ar!==null&&(Sn?(r=ar,t=t.stateNode,r.nodeType===8?Ec(r.parentNode,t):r.nodeType===1&&Ec(r,t),ya(r)):Ec(ar,t.stateNode));break;case 4:n=ar,i=Sn,ar=t.stateNode.containerInfo,Sn=!0,fi(r,e,t),ar=n,Sn=i;break;case 0:case 11:case 14:case 15:if(!mr&&(n=t.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)&&$d(t,e,o),i=i.next}while(i!==n)}fi(r,e,t);break;case 1:if(!mr&&(Vs(t,e),n=t.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=t.memoizedProps,n.state=t.memoizedState,n.componentWillUnmount()}catch(a){Ut(t,e,a)}fi(r,e,t);break;case 21:fi(r,e,t);break;case 22:t.mode&1?(mr=(n=mr)||t.memoizedState!==null,fi(r,e,t),mr=n):fi(r,e,t);break;default:fi(r,e,t)}}function kg(r){var e=r.updateQueue;if(e!==null){r.updateQueue=null;var t=r.stateNode;t===null&&(t=r.stateNode=new pS),e.forEach(function(n){var i=IS.bind(null,r,n);t.has(n)||(t.add(n),n.then(i,i))})}}function vn(r,e){var t=e.deletions;if(t!==null)for(var n=0;n<t.length;n++){var i=t[n];try{var s=r,o=e,a=o;e:for(;a!==null;){switch(a.tag){case 5:ar=a.stateNode,Sn=!1;break e;case 3:ar=a.stateNode.containerInfo,Sn=!0;break e;case 4:ar=a.stateNode.containerInfo,Sn=!0;break e}a=a.return}if(ar===null)throw Error(te(160));l1(s,o,i),ar=null,Sn=!1;var l=i.alternate;l!==null&&(l.return=null),i.return=null}catch(u){Ut(i,e,u)}}if(e.subtreeFlags&12854)for(e=e.child;e!==null;)u1(e,r),e=e.sibling}function u1(r,e){var t=r.alternate,n=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:if(vn(e,r),Ln(r),n&4){try{na(3,r,r.return),bu(3,r)}catch(m){Ut(r,r.return,m)}try{na(5,r,r.return)}catch(m){Ut(r,r.return,m)}}break;case 1:vn(e,r),Ln(r),n&512&&t!==null&&Vs(t,t.return);break;case 5:if(vn(e,r),Ln(r),n&512&&t!==null&&Vs(t,t.return),r.flags&32){var i=r.stateNode;try{fa(i,"")}catch(m){Ut(r,r.return,m)}}if(n&4&&(i=r.stateNode,i!=null)){var s=r.memoizedProps,o=t!==null?t.memoizedProps:s,a=r.type,l=r.updateQueue;if(r.updateQueue=null,l!==null)try{a==="input"&&s.type==="radio"&&s.name!=null&&Ry(i,s),fd(a,o);var u=fd(a,s);for(o=0;o<l.length;o+=2){var c=l[o],d=l[o+1];c==="style"?Dy(i,d):c==="dangerouslySetInnerHTML"?zy(i,d):c==="children"?fa(i,d):Rh(i,c,d,u)}switch(a){case"input":ld(i,s);break;case"textarea":Py(i,s);break;case"select":var h=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!s.multiple;var f=s.value;f!=null?Ws(i,!!s.multiple,f,!1):h!==!!s.multiple&&(s.defaultValue!=null?Ws(i,!!s.multiple,s.defaultValue,!0):Ws(i,!!s.multiple,s.multiple?[]:"",!1))}i[Sa]=s}catch(m){Ut(r,r.return,m)}}break;case 6:if(vn(e,r),Ln(r),n&4){if(r.stateNode===null)throw Error(te(162));i=r.stateNode,s=r.memoizedProps;try{i.nodeValue=s}catch(m){Ut(r,r.return,m)}}break;case 3:if(vn(e,r),Ln(r),n&4&&t!==null&&t.memoizedState.isDehydrated)try{ya(e.containerInfo)}catch(m){Ut(r,r.return,m)}break;case 4:vn(e,r),Ln(r);break;case 13:vn(e,r),Ln(r),i=r.child,i.flags&8192&&(s=i.memoizedState!==null,i.stateNode.isHidden=s,!s||i.alternate!==null&&i.alternate.memoizedState!==null||(df=Rt())),n&4&&kg(r);break;case 22:if(c=t!==null&&t.memoizedState!==null,r.mode&1?(mr=(u=mr)||c,vn(e,r),mr=u):vn(e,r),Ln(r),n&8192){if(u=r.memoizedState!==null,(r.stateNode.isHidden=u)&&!c&&r.mode&1)for(fe=r,c=r.child;c!==null;){for(d=fe=c;fe!==null;){switch(h=fe,f=h.child,h.tag){case 0:case 11:case 14:case 15:na(4,h,h.return);break;case 1:Vs(h,h.return);var p=h.stateNode;if(typeof p.componentWillUnmount=="function"){n=h,t=h.return;try{e=n,p.props=e.memoizedProps,p.state=e.memoizedState,p.componentWillUnmount()}catch(m){Ut(n,t,m)}}break;case 5:Vs(h,h.return);break;case 22:if(h.memoizedState!==null){Mg(d);continue}}f!==null?(f.return=h,fe=f):Mg(d)}c=c.sibling}e:for(c=null,d=r;;){if(d.tag===5){if(c===null){c=d;try{i=d.stateNode,u?(s=i.style,typeof s.setProperty=="function"?s.setProperty("display","none","important"):s.display="none"):(a=d.stateNode,l=d.memoizedProps.style,o=l!=null&&l.hasOwnProperty("display")?l.display:null,a.style.display=Oy("display",o))}catch(m){Ut(r,r.return,m)}}}else if(d.tag===6){if(c===null)try{d.stateNode.nodeValue=u?"":d.memoizedProps}catch(m){Ut(r,r.return,m)}}else if((d.tag!==22&&d.tag!==23||d.memoizedState===null||d===r)&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===r)break e;for(;d.sibling===null;){if(d.return===null||d.return===r)break e;c===d&&(c=null),d=d.return}c===d&&(c=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:vn(e,r),Ln(r),n&4&&kg(r);break;case 21:break;default:vn(e,r),Ln(r)}}function Ln(r){var e=r.flags;if(e&2){try{e:{for(var t=r.return;t!==null;){if(a1(t)){var n=t;break e}t=t.return}throw Error(te(160))}switch(n.tag){case 5:var i=n.stateNode;n.flags&32&&(fa(i,""),n.flags&=-33);var s=Ig(r);Hd(r,s,i);break;case 3:case 4:var o=n.stateNode.containerInfo,a=Ig(r);Vd(r,a,o);break;default:throw Error(te(161))}}catch(l){Ut(r,r.return,l)}r.flags&=-3}e&4096&&(r.flags&=-4097)}function mS(r,e,t){fe=r,c1(r)}function c1(r,e,t){for(var n=(r.mode&1)!==0;fe!==null;){var i=fe,s=i.child;if(i.tag===22&&n){var o=i.memoizedState!==null||sl;if(!o){var a=i.alternate,l=a!==null&&a.memoizedState!==null||mr;a=sl;var u=mr;if(sl=o,(mr=l)&&!u)for(fe=i;fe!==null;)o=fe,l=o.child,o.tag===22&&o.memoizedState!==null?Ug(i):l!==null?(l.return=o,fe=l):Ug(i);for(;s!==null;)fe=s,c1(s),s=s.sibling;fe=i,sl=a,mr=u}Eg(r)}else i.subtreeFlags&8772&&s!==null?(s.return=i,fe=s):Eg(r)}}function Eg(r){for(;fe!==null;){var e=fe;if(e.flags&8772){var t=e.alternate;try{if(e.flags&8772)switch(e.tag){case 0:case 11:case 15:mr||bu(5,e);break;case 1:var n=e.stateNode;if(e.flags&4&&!mr)if(t===null)n.componentDidMount();else{var i=e.elementType===e.type?t.memoizedProps:bn(e.type,t.memoizedProps);n.componentDidUpdate(i,t.memoizedState,n.__reactInternalSnapshotBeforeUpdate)}var s=e.updateQueue;s!==null&&cg(e,s,n);break;case 3:var o=e.updateQueue;if(o!==null){if(t=null,e.child!==null)switch(e.child.tag){case 5:t=e.child.stateNode;break;case 1:t=e.child.stateNode}cg(e,o,t)}break;case 5:var a=e.stateNode;if(t===null&&e.flags&4){t=a;var l=e.memoizedProps;switch(e.type){case"button":case"input":case"select":case"textarea":l.autoFocus&&t.focus();break;case"img":l.src&&(t.src=l.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(e.memoizedState===null){var u=e.alternate;if(u!==null){var c=u.memoizedState;if(c!==null){var d=c.dehydrated;d!==null&&ya(d)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(te(163))}mr||e.flags&512&&Nd(e)}catch(h){Ut(e,e.return,h)}}if(e===r){fe=null;break}if(t=e.sibling,t!==null){t.return=e.return,fe=t;break}fe=e.return}}function Mg(r){for(;fe!==null;){var e=fe;if(e===r){fe=null;break}var t=e.sibling;if(t!==null){t.return=e.return,fe=t;break}fe=e.return}}function Ug(r){for(;fe!==null;){var e=fe;try{switch(e.tag){case 0:case 11:case 15:var t=e.return;try{bu(4,e)}catch(l){Ut(e,t,l)}break;case 1:var n=e.stateNode;if(typeof n.componentDidMount=="function"){var i=e.return;try{n.componentDidMount()}catch(l){Ut(e,i,l)}}var s=e.return;try{Nd(e)}catch(l){Ut(e,s,l)}break;case 5:var o=e.return;try{Nd(e)}catch(l){Ut(e,o,l)}}}catch(l){Ut(e,e.return,l)}if(e===r){fe=null;break}var a=e.sibling;if(a!==null){a.return=e.return,fe=a;break}fe=e.return}}var yS=Math.ceil,eu=oi.ReactCurrentDispatcher,uf=oi.ReactCurrentOwner,hn=oi.ReactCurrentBatchConfig,Oe=0,nr=null,Ot=null,lr=0,Gr=0,Hs=Di(0),Wt=0,Ua=null,us=0,Su=0,cf=0,ia=null,Dr=null,df=0,oo=1/0,Kn=null,tu=!1,jd=null,Ei=null,ol=!1,Ci=null,ru=0,sa=0,Yd=null,Ul=-1,Al=0;function Ur(){return Oe&6?Rt():Ul!==-1?Ul:Ul=Rt()}function Mi(r){return r.mode&1?Oe&2&&lr!==0?lr&-lr:eS.transition!==null?(Al===0&&(Al=Xy()),Al):(r=Xe,r!==0||(r=window.event,r=r===void 0?16:t0(r.type)),r):1}function Un(r,e,t,n){if(50<sa)throw sa=0,Yd=null,Error(te(185));Pa(r,t,n),(!(Oe&2)||r!==nr)&&(r===nr&&(!(Oe&2)&&(Su|=t),Wt===4&&vi(r,lr)),$r(r,n),t===1&&Oe===0&&!(e.mode&1)&&(oo=Rt()+500,vu&&Fi()))}function $r(r,e){var t=r.callbackNode;e2(r,e);var n=_l(r,r===nr?lr:0);if(n===0)t!==null&&Fp(t),r.callbackNode=null,r.callbackPriority=0;else if(e=n&-n,r.callbackPriority!==e){if(t!=null&&Fp(t),e===1)r.tag===0?J2(Ag.bind(null,r)):C0(Ag.bind(null,r)),K2(function(){!(Oe&6)&&Fi()}),t=null;else{switch(Ky(n)){case 1:t=Dh;break;case 4:t=Wy;break;case 16:t=Ll;break;case 536870912:t=Gy;break;default:t=Ll}t=v1(t,d1.bind(null,r))}r.callbackPriority=e,r.callbackNode=t}}function d1(r,e){if(Ul=-1,Al=0,Oe&6)throw Error(te(327));var t=r.callbackNode;if(qs()&&r.callbackNode!==t)return null;var n=_l(r,r===nr?lr:0);if(n===0)return null;if(n&30||n&r.expiredLanes||e)e=nu(r,n);else{e=n;var i=Oe;Oe|=2;var s=f1();(nr!==r||lr!==e)&&(Kn=null,oo=Rt()+500,ns(r,e));do try{CS();break}catch(a){h1(r,a)}while(!0);Kh(),eu.current=s,Oe=i,Ot!==null?e=0:(nr=null,lr=0,e=Wt)}if(e!==0){if(e===2&&(i=vd(r),i!==0&&(n=i,e=Wd(r,i))),e===1)throw t=Ua,ns(r,0),vi(r,n),$r(r,Rt()),t;if(e===6)vi(r,n);else{if(i=r.current.alternate,!(n&30)&&!vS(i)&&(e=nu(r,n),e===2&&(s=vd(r),s!==0&&(n=s,e=Wd(r,s))),e===1))throw t=Ua,ns(r,0),vi(r,n),$r(r,Rt()),t;switch(r.finishedWork=i,r.finishedLanes=n,e){case 0:case 1:throw Error(te(345));case 2:Xi(r,Dr,Kn);break;case 3:if(vi(r,n),(n&130023424)===n&&(e=df+500-Rt(),10<e)){if(_l(r,0)!==0)break;if(i=r.suspendedLanes,(i&n)!==n){Ur(),r.pingedLanes|=r.suspendedLanes&i;break}r.timeoutHandle=Ed(Xi.bind(null,r,Dr,Kn),e);break}Xi(r,Dr,Kn);break;case 4:if(vi(r,n),(n&4194240)===n)break;for(e=r.eventTimes,i=-1;0<n;){var o=31-Mn(n);s=1<<o,o=e[o],o>i&&(i=o),n&=~s}if(n=i,n=Rt()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*yS(n/1960))-n,10<n){r.timeoutHandle=Ed(Xi.bind(null,r,Dr,Kn),n);break}Xi(r,Dr,Kn);break;case 5:Xi(r,Dr,Kn);break;default:throw Error(te(329))}}}return $r(r,Rt()),r.callbackNode===t?d1.bind(null,r):null}function Wd(r,e){var t=ia;return r.current.memoizedState.isDehydrated&&(ns(r,e).flags|=256),r=nu(r,e),r!==2&&(e=Dr,Dr=t,e!==null&&Gd(e)),r}function Gd(r){Dr===null?Dr=r:Dr.push.apply(Dr,r)}function vS(r){for(var e=r;;){if(e.flags&16384){var t=e.updateQueue;if(t!==null&&(t=t.stores,t!==null))for(var n=0;n<t.length;n++){var i=t[n],s=i.getSnapshot;i=i.value;try{if(!An(s(),i))return!1}catch{return!1}}}if(t=e.child,e.subtreeFlags&16384&&t!==null)t.return=e,e=t;else{if(e===r)break;for(;e.sibling===null;){if(e.return===null||e.return===r)return!0;e=e.return}e.sibling.return=e.return,e=e.sibling}}return!0}function vi(r,e){for(e&=~cf,e&=~Su,r.suspendedLanes|=e,r.pingedLanes&=~e,r=r.expirationTimes;0<e;){var t=31-Mn(e),n=1<<t;r[t]=-1,e&=~n}}function Ag(r){if(Oe&6)throw Error(te(327));qs();var e=_l(r,0);if(!(e&1))return $r(r,Rt()),null;var t=nu(r,e);if(r.tag!==0&&t===2){var n=vd(r);n!==0&&(e=n,t=Wd(r,n))}if(t===1)throw t=Ua,ns(r,0),vi(r,e),$r(r,Rt()),t;if(t===6)throw Error(te(345));return r.finishedWork=r.current.alternate,r.finishedLanes=e,Xi(r,Dr,Kn),$r(r,Rt()),null}function hf(r,e){var t=Oe;Oe|=1;try{return r(e)}finally{Oe=t,Oe===0&&(oo=Rt()+500,vu&&Fi())}}function cs(r){Ci!==null&&Ci.tag===0&&!(Oe&6)&&qs();var e=Oe;Oe|=1;var t=hn.transition,n=Xe;try{if(hn.transition=null,Xe=1,r)return r()}finally{Xe=n,hn.transition=t,Oe=e,!(Oe&6)&&Fi()}}function ff(){Gr=Hs.current,ct(Hs)}function ns(r,e){r.finishedWork=null,r.finishedLanes=0;var t=r.timeoutHandle;if(t!==-1&&(r.timeoutHandle=-1,X2(t)),Ot!==null)for(t=Ot.return;t!==null;){var n=t;switch(Wh(n),n.tag){case 1:n=n.type.childContextTypes,n!=null&&jl();break;case 3:io(),ct(Lr),ct(vr),tf();break;case 5:ef(n);break;case 4:io();break;case 13:ct(St);break;case 19:ct(St);break;case 10:Zh(n.type._context);break;case 22:case 23:ff()}t=t.return}if(nr=r,Ot=r=Ui(r.current,null),lr=Gr=e,Wt=0,Ua=null,cf=Su=us=0,Dr=ia=null,ts!==null){for(e=0;e<ts.length;e++)if(t=ts[e],n=t.interleaved,n!==null){t.interleaved=null;var i=n.next,s=t.pending;if(s!==null){var o=s.next;s.next=i,n.next=o}t.pending=n}ts=null}return r}function h1(r,e){do{var t=Ot;try{if(Kh(),kl.current=Jl,Ql){for(var n=xt.memoizedState;n!==null;){var i=n.queue;i!==null&&(i.pending=null),n=n.next}Ql=!1}if(ls=0,rr=Ht=xt=null,ra=!1,ka=0,uf.current=null,t===null||t.return===null){Wt=1,Ua=e,Ot=null;break}e:{var s=r,o=t.return,a=t,l=e;if(e=lr,a.flags|=32768,l!==null&&typeof l=="object"&&typeof l.then=="function"){var u=l,c=a,d=c.tag;if(!(c.mode&1)&&(d===0||d===11||d===15)){var h=c.alternate;h?(c.updateQueue=h.updateQueue,c.memoizedState=h.memoizedState,c.lanes=h.lanes):(c.updateQueue=null,c.memoizedState=null)}var f=mg(o);if(f!==null){f.flags&=-257,yg(f,o,a,s,e),f.mode&1&&gg(s,u,e),e=f,l=u;var p=e.updateQueue;if(p===null){var m=new Set;m.add(l),e.updateQueue=m}else p.add(l);break e}else{if(!(e&1)){gg(s,u,e),pf();break e}l=Error(te(426))}}else if(vt&&a.mode&1){var S=mg(o);if(S!==null){!(S.flags&65536)&&(S.flags|=256),yg(S,o,a,s,e),Gh(so(l,a));break e}}s=l=so(l,a),Wt!==4&&(Wt=2),ia===null?ia=[s]:ia.push(s),s=o;do{switch(s.tag){case 3:s.flags|=65536,e&=-e,s.lanes|=e;var w=K0(s,l,e);ug(s,w);break e;case 1:a=l;var g=s.type,y=s.stateNode;if(!(s.flags&128)&&(typeof g.getDerivedStateFromError=="function"||y!==null&&typeof y.componentDidCatch=="function"&&(Ei===null||!Ei.has(y)))){s.flags|=65536,e&=-e,s.lanes|=e;var C=Z0(s,a,e);ug(s,C);break e}}s=s.return}while(s!==null)}g1(t)}catch(x){e=x,Ot===t&&t!==null&&(Ot=t=t.return);continue}break}while(!0)}function f1(){var r=eu.current;return eu.current=Jl,r===null?Jl:r}function pf(){(Wt===0||Wt===3||Wt===2)&&(Wt=4),nr===null||!(us&268435455)&&!(Su&268435455)||vi(nr,lr)}function nu(r,e){var t=Oe;Oe|=2;var n=f1();(nr!==r||lr!==e)&&(Kn=null,ns(r,e));do try{wS();break}catch(i){h1(r,i)}while(!0);if(Kh(),Oe=t,eu.current=n,Ot!==null)throw Error(te(261));return nr=null,lr=0,Wt}function wS(){for(;Ot!==null;)p1(Ot)}function CS(){for(;Ot!==null&&!Yb();)p1(Ot)}function p1(r){var e=y1(r.alternate,r,Gr);r.memoizedProps=r.pendingProps,e===null?g1(r):Ot=e,uf.current=null}function g1(r){var e=r;do{var t=e.alternate;if(r=e.return,e.flags&32768){if(t=fS(t,e),t!==null){t.flags&=32767,Ot=t;return}if(r!==null)r.flags|=32768,r.subtreeFlags=0,r.deletions=null;else{Wt=6,Ot=null;return}}else if(t=hS(t,e,Gr),t!==null){Ot=t;return}if(e=e.sibling,e!==null){Ot=e;return}Ot=e=r}while(e!==null);Wt===0&&(Wt=5)}function Xi(r,e,t){var n=Xe,i=hn.transition;try{hn.transition=null,Xe=1,bS(r,e,t,n)}finally{hn.transition=i,Xe=n}return null}function bS(r,e,t,n){do qs();while(Ci!==null);if(Oe&6)throw Error(te(327));t=r.finishedWork;var i=r.finishedLanes;if(t===null)return null;if(r.finishedWork=null,r.finishedLanes=0,t===r.current)throw Error(te(177));r.callbackNode=null,r.callbackPriority=0;var s=t.lanes|t.childLanes;if(t2(r,s),r===nr&&(Ot=nr=null,lr=0),!(t.subtreeFlags&2064)&&!(t.flags&2064)||ol||(ol=!0,v1(Ll,function(){return qs(),null})),s=(t.flags&15990)!==0,t.subtreeFlags&15990||s){s=hn.transition,hn.transition=null;var o=Xe;Xe=1;var a=Oe;Oe|=4,uf.current=null,gS(r,t),u1(t,r),N2(Id),$l=!!xd,Id=xd=null,r.current=t,mS(t),Wb(),Oe=a,Xe=o,hn.transition=s}else r.current=t;if(ol&&(ol=!1,Ci=r,ru=i),s=r.pendingLanes,s===0&&(Ei=null),Kb(t.stateNode),$r(r,Rt()),e!==null)for(n=r.onRecoverableError,t=0;t<e.length;t++)i=e[t],n(i.value,{componentStack:i.stack,digest:i.digest});if(tu)throw tu=!1,r=jd,jd=null,r;return ru&1&&r.tag!==0&&qs(),s=r.pendingLanes,s&1?r===Yd?sa++:(sa=0,Yd=r):sa=0,Fi(),null}function qs(){if(Ci!==null){var r=Ky(ru),e=hn.transition,t=Xe;try{if(hn.transition=null,Xe=16>r?16:r,Ci===null)var n=!1;else{if(r=Ci,Ci=null,ru=0,Oe&6)throw Error(te(331));var i=Oe;for(Oe|=4,fe=r.current;fe!==null;){var s=fe,o=s.child;if(fe.flags&16){var a=s.deletions;if(a!==null){for(var l=0;l<a.length;l++){var u=a[l];for(fe=u;fe!==null;){var c=fe;switch(c.tag){case 0:case 11:case 15:na(8,c,s)}var d=c.child;if(d!==null)d.return=c,fe=d;else for(;fe!==null;){c=fe;var h=c.sibling,f=c.return;if(o1(c),c===u){fe=null;break}if(h!==null){h.return=f,fe=h;break}fe=f}}}var p=s.alternate;if(p!==null){var m=p.child;if(m!==null){p.child=null;do{var S=m.sibling;m.sibling=null,m=S}while(m!==null)}}fe=s}}if(s.subtreeFlags&2064&&o!==null)o.return=s,fe=o;else e:for(;fe!==null;){if(s=fe,s.flags&2048)switch(s.tag){case 0:case 11:case 15:na(9,s,s.return)}var w=s.sibling;if(w!==null){w.return=s.return,fe=w;break e}fe=s.return}}var g=r.current;for(fe=g;fe!==null;){o=fe;var y=o.child;if(o.subtreeFlags&2064&&y!==null)y.return=o,fe=y;else e:for(o=g;fe!==null;){if(a=fe,a.flags&2048)try{switch(a.tag){case 0:case 11:case 15:bu(9,a)}}catch(x){Ut(a,a.return,x)}if(a===o){fe=null;break e}var C=a.sibling;if(C!==null){C.return=a.return,fe=C;break e}fe=a.return}}if(Oe=i,Fi(),Vn&&typeof Vn.onPostCommitFiberRoot=="function")try{Vn.onPostCommitFiberRoot(fu,r)}catch{}n=!0}return n}finally{Xe=t,hn.transition=e}}return!1}function Tg(r,e,t){e=so(t,e),e=K0(r,e,1),r=ki(r,e,1),e=Ur(),r!==null&&(Pa(r,1,e),$r(r,e))}function Ut(r,e,t){if(r.tag===3)Tg(r,r,t);else for(;e!==null;){if(e.tag===3){Tg(e,r,t);break}else if(e.tag===1){var n=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(Ei===null||!Ei.has(n))){r=so(t,r),r=Z0(e,r,1),e=ki(e,r,1),r=Ur(),e!==null&&(Pa(e,1,r),$r(e,r));break}}e=e.return}}function SS(r,e,t){var n=r.pingCache;n!==null&&n.delete(e),e=Ur(),r.pingedLanes|=r.suspendedLanes&t,nr===r&&(lr&t)===t&&(Wt===4||Wt===3&&(lr&130023424)===lr&&500>Rt()-df?ns(r,0):cf|=t),$r(r,e)}function m1(r,e){e===0&&(r.mode&1?(e=Za,Za<<=1,!(Za&130023424)&&(Za=4194304)):e=1);var t=Ur();r=ii(r,e),r!==null&&(Pa(r,e,t),$r(r,t))}function xS(r){var e=r.memoizedState,t=0;e!==null&&(t=e.retryLane),m1(r,t)}function IS(r,e){var t=0;switch(r.tag){case 13:var n=r.stateNode,i=r.memoizedState;i!==null&&(t=i.retryLane);break;case 19:n=r.stateNode;break;default:throw Error(te(314))}n!==null&&n.delete(e),m1(r,t)}var y1;y1=function(r,e,t){if(r!==null)if(r.memoizedProps!==e.pendingProps||Lr.current)Fr=!0;else{if(!(r.lanes&t)&&!(e.flags&128))return Fr=!1,dS(r,e,t);Fr=!!(r.flags&131072)}else Fr=!1,vt&&e.flags&1048576&&b0(e,Gl,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;Ml(r,e),r=e.pendingProps;var i=to(e,vr.current);Zs(e,t),i=nf(null,e,n,r,i,t);var s=sf();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,_r(n)?(s=!0,Yl(e)):s=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,Qh(e),i.updater=Cu,e.stateNode=i,i._reactInternals=e,Bd(e,n,r,t),e=Dd(null,e,n,!0,s,t)):(e.tag=0,vt&&s&&Yh(e),kr(null,e,i,t),e=e.child),e;case 16:n=e.elementType;e:{switch(Ml(r,e),r=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=ES(n),r=bn(n,r),i){case 0:e=Od(null,e,n,r,t);break e;case 1:e=Cg(null,e,n,r,t);break e;case 11:e=vg(null,e,n,r,t);break e;case 14:e=wg(null,e,n,bn(n.type,r),t);break e}throw Error(te(306,n,""))}return e;case 0:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:bn(n,i),Od(r,e,n,i,t);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:bn(n,i),Cg(r,e,n,i,t);case 3:e:{if(e1(e),r===null)throw Error(te(387));n=e.pendingProps,s=e.memoizedState,i=s.element,M0(r,e),Zl(e,n,null,t);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=so(Error(te(423)),e),e=bg(r,e,n,t,i);break e}else if(n!==i){i=so(Error(te(424)),e),e=bg(r,e,n,t,i);break e}else for(Zr=Ii(e.stateNode.containerInfo.firstChild),qr=e,vt=!0,kn=null,t=k0(e,null,n,t),e.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(ro(),n===i){e=si(r,e,t);break e}kr(r,e,n,t)}e=e.child}return e;case 5:return U0(e),r===null&&Td(e),n=e.type,i=e.pendingProps,s=r!==null?r.memoizedProps:null,o=i.children,kd(n,i)?o=null:s!==null&&kd(n,s)&&(e.flags|=32),J0(r,e),kr(r,e,o,t),e.child;case 6:return r===null&&Td(e),null;case 13:return t1(r,e,t);case 4:return Jh(e,e.stateNode.containerInfo),n=e.pendingProps,r===null?e.child=no(e,null,n,t):kr(r,e,n,t),e.child;case 11:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:bn(n,i),vg(r,e,n,i,t);case 7:return kr(r,e,e.pendingProps,t),e.child;case 8:return kr(r,e,e.pendingProps.children,t),e.child;case 12:return kr(r,e,e.pendingProps.children,t),e.child;case 10:e:{if(n=e.type._context,i=e.pendingProps,s=e.memoizedProps,o=i.value,rt(Xl,n._currentValue),n._currentValue=o,s!==null)if(An(s.value,o)){if(s.children===i.children&&!Lr.current){e=si(r,e,t);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=Jn(-1,t&-t),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|=t,l=s.alternate,l!==null&&(l.lanes|=t),Rd(s.return,t,e),a.lanes|=t;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(te(341));o.lanes|=t,a=o.alternate,a!==null&&(a.lanes|=t),Rd(o,t,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}kr(r,e,i.children,t),e=e.child}return e;case 9:return i=e.type,n=e.pendingProps.children,Zs(e,t),i=fn(i),n=n(i),e.flags|=1,kr(r,e,n,t),e.child;case 14:return n=e.type,i=bn(n,e.pendingProps),i=bn(n.type,i),wg(r,e,n,i,t);case 15:return q0(r,e,e.type,e.pendingProps,t);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:bn(n,i),Ml(r,e),e.tag=1,_r(n)?(r=!0,Yl(e)):r=!1,Zs(e,t),X0(e,n,i),Bd(e,n,i,t),Dd(null,e,n,!0,r,t);case 19:return r1(r,e,t);case 22:return Q0(r,e,t)}throw Error(te(156,e.tag))};function v1(r,e){return Yy(r,e)}function kS(r,e,t,n){this.tag=r,this.key=t,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 dn(r,e,t,n){return new kS(r,e,t,n)}function gf(r){return r=r.prototype,!(!r||!r.isReactComponent)}function ES(r){if(typeof r=="function")return gf(r)?1:0;if(r!=null){if(r=r.$$typeof,r===Bh)return 11;if(r===zh)return 14}return 2}function Ui(r,e){var t=r.alternate;return t===null?(t=dn(r.tag,e,r.key,r.mode),t.elementType=r.elementType,t.type=r.type,t.stateNode=r.stateNode,t.alternate=r,r.alternate=t):(t.pendingProps=e,t.type=r.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=r.flags&14680064,t.childLanes=r.childLanes,t.lanes=r.lanes,t.child=r.child,t.memoizedProps=r.memoizedProps,t.memoizedState=r.memoizedState,t.updateQueue=r.updateQueue,e=r.dependencies,t.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},t.sibling=r.sibling,t.index=r.index,t.ref=r.ref,t}function Tl(r,e,t,n,i,s){var o=2;if(n=r,typeof r=="function")gf(r)&&(o=1);else if(typeof r=="string")o=5;else e:switch(r){case Bs:return is(t.children,i,s,e);case Ph:o=8,i|=8;break;case nd:return r=dn(12,t,e,i|2),r.elementType=nd,r.lanes=s,r;case id:return r=dn(13,t,e,i),r.elementType=id,r.lanes=s,r;case sd:return r=dn(19,t,e,i),r.elementType=sd,r.lanes=s,r;case Uy:return xu(t,i,s,e);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case Ey:o=10;break e;case My:o=9;break e;case Bh:o=11;break e;case zh:o=14;break e;case pi:o=16,n=null;break e}throw Error(te(130,r==null?r:typeof r,""))}return e=dn(o,t,e,i),e.elementType=r,e.type=n,e.lanes=s,e}function is(r,e,t,n){return r=dn(7,r,n,e),r.lanes=t,r}function xu(r,e,t,n){return r=dn(22,r,n,e),r.elementType=Uy,r.lanes=t,r.stateNode={isHidden:!1},r}function zc(r,e,t){return r=dn(6,r,null,e),r.lanes=t,r}function Oc(r,e,t){return e=dn(4,r.children!==null?r.children:[],r.key,e),e.lanes=t,e.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},e}function MS(r,e,t,n,i){this.tag=e,this.containerInfo=r,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=gc(0),this.expirationTimes=gc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=gc(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function mf(r,e,t,n,i,s,o,a,l){return r=new MS(r,e,t,a,l),e===1?(e=1,s===!0&&(e|=8)):e=0,s=dn(3,null,null,e),r.current=s,s.stateNode=r,s.memoizedState={element:n,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},Qh(s),r}function US(r,e,t){var n=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Ps,key:n==null?null:""+n,children:r,containerInfo:e,implementation:t}}function w1(r){if(!r)return Bi;r=r._reactInternals;e:{if(fs(r)!==r||r.tag!==1)throw Error(te(170));var e=r;do{switch(e.tag){case 3:e=e.stateNode.context;break e;case 1:if(_r(e.type)){e=e.stateNode.__reactInternalMemoizedMergedChildContext;break e}}e=e.return}while(e!==null);throw Error(te(171))}if(r.tag===1){var t=r.type;if(_r(t))return w0(r,t,e)}return e}function C1(r,e,t,n,i,s,o,a,l){return r=mf(t,n,!0,r,i,s,o,a,l),r.context=w1(null),t=r.current,n=Ur(),i=Mi(t),s=Jn(n,i),s.callback=e??null,ki(t,s,i),r.current.lanes=i,Pa(r,i,n),$r(r,n),r}function Iu(r,e,t,n){var i=e.current,s=Ur(),o=Mi(i);return t=w1(t),e.context===null?e.context=t:e.pendingContext=t,e=Jn(s,o),e.payload={element:r},n=n===void 0?null:n,n!==null&&(e.callback=n),r=ki(i,e,o),r!==null&&(Un(r,i,o,s),Il(r,i,o)),o}function iu(r){if(r=r.current,!r.child)return null;switch(r.child.tag){case 5:return r.child.stateNode;default:return r.child.stateNode}}function Rg(r,e){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var t=r.retryLane;r.retryLane=t!==0&&t<e?t:e}}function yf(r,e){Rg(r,e),(r=r.alternate)&&Rg(r,e)}function AS(){return null}var b1=typeof reportError=="function"?reportError:function(r){console.error(r)};function vf(r){this._internalRoot=r}ku.prototype.render=vf.prototype.render=function(r){var e=this._internalRoot;if(e===null)throw Error(te(409));Iu(r,e,null,null)};ku.prototype.unmount=vf.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var e=r.containerInfo;cs(function(){Iu(null,r,null,null)}),e[ni]=null}};function ku(r){this._internalRoot=r}ku.prototype.unstable_scheduleHydration=function(r){if(r){var e=Qy();r={blockedOn:null,target:r,priority:e};for(var t=0;t<yi.length&&e!==0&&e<yi[t].priority;t++);yi.splice(t,0,r),t===0&&e0(r)}};function wf(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function Eu(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11&&(r.nodeType!==8||r.nodeValue!==" react-mount-point-unstable "))}function Pg(){}function TS(r,e,t,n,i){if(i){if(typeof n=="function"){var s=n;n=function(){var u=iu(o);s.call(u)}}var o=C1(e,n,r,0,null,!1,!1,"",Pg);return r._reactRootContainer=o,r[ni]=o.current,Ca(r.nodeType===8?r.parentNode:r),cs(),o}for(;i=r.lastChild;)r.removeChild(i);if(typeof n=="function"){var a=n;n=function(){var u=iu(l);a.call(u)}}var l=mf(r,0,!1,null,null,!1,!1,"",Pg);return r._reactRootContainer=l,r[ni]=l.current,Ca(r.nodeType===8?r.parentNode:r),cs(function(){Iu(e,l,t,n)}),l}function Mu(r,e,t,n,i){var s=t._reactRootContainer;if(s){var o=s;if(typeof i=="function"){var a=i;i=function(){var l=iu(o);a.call(l)}}Iu(e,o,r,i)}else o=TS(t,e,r,i,n);return iu(o)}Zy=function(r){switch(r.tag){case 3:var e=r.stateNode;if(e.current.memoizedState.isDehydrated){var t=Ho(e.pendingLanes);t!==0&&(Fh(e,t|1),$r(e,Rt()),!(Oe&6)&&(oo=Rt()+500,Fi()))}break;case 13:cs(function(){var n=ii(r,1);if(n!==null){var i=Ur();Un(n,r,1,i)}}),yf(r,1)}};Lh=function(r){if(r.tag===13){var e=ii(r,134217728);if(e!==null){var t=Ur();Un(e,r,134217728,t)}yf(r,134217728)}};qy=function(r){if(r.tag===13){var e=Mi(r),t=ii(r,e);if(t!==null){var n=Ur();Un(t,r,e,n)}yf(r,e)}};Qy=function(){return Xe};Jy=function(r,e){var t=Xe;try{return Xe=r,e()}finally{Xe=t}};gd=function(r,e,t){switch(e){case"input":if(ld(r,t),e=t.name,t.type==="radio"&&e!=null){for(t=r;t.parentNode;)t=t.parentNode;for(t=t.querySelectorAll("input[name="+JSON.stringify(""+e)+'][type="radio"]'),e=0;e<t.length;e++){var n=t[e];if(n!==r&&n.form===r.form){var i=yu(n);if(!i)throw Error(te(90));Ty(n),ld(n,i)}}}break;case"textarea":Py(r,t);break;case"select":e=t.value,e!=null&&Ws(r,!!t.multiple,e,!1)}};_y=hf;$y=cs;var RS={usingClientEntryPoint:!1,Events:[za,Fs,yu,Fy,Ly,hf]},Oo={findFiberByHostInstance:es,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},PS={bundleType:Oo.bundleType,version:Oo.version,rendererPackageName:Oo.rendererPackageName,rendererConfig:Oo.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:oi.ReactCurrentDispatcher,findHostInstanceByFiber:function(r){return r=Hy(r),r===null?null:r.stateNode},findFiberByHostInstance:Oo.findFiberByHostInstance||AS,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var al=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!al.isDisabled&&al.supportsFiber)try{fu=al.inject(PS),Vn=al}catch{}}en.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=RS;en.createPortal=function(r,e){var t=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!wf(e))throw Error(te(200));return US(r,e,null,t)};en.createRoot=function(r,e){if(!wf(r))throw Error(te(299));var t=!1,n="",i=b1;return e!=null&&(e.unstable_strictMode===!0&&(t=!0),e.identifierPrefix!==void 0&&(n=e.identifierPrefix),e.onRecoverableError!==void 0&&(i=e.onRecoverableError)),e=mf(r,1,!1,null,null,t,!1,n,i),r[ni]=e.current,Ca(r.nodeType===8?r.parentNode:r),new vf(e)};en.findDOMNode=function(r){if(r==null)return null;if(r.nodeType===1)return r;var e=r._reactInternals;if(e===void 0)throw typeof r.render=="function"?Error(te(188)):(r=Object.keys(r).join(","),Error(te(268,r)));return r=Hy(e),r=r===null?null:r.stateNode,r};en.flushSync=function(r){return cs(r)};en.hydrate=function(r,e,t){if(!Eu(e))throw Error(te(200));return Mu(null,r,e,!0,t)};en.hydrateRoot=function(r,e,t){if(!wf(r))throw Error(te(405));var n=t!=null&&t.hydratedSources||null,i=!1,s="",o=b1;if(t!=null&&(t.unstable_strictMode===!0&&(i=!0),t.identifierPrefix!==void 0&&(s=t.identifierPrefix),t.onRecoverableError!==void 0&&(o=t.onRecoverableError)),e=C1(e,null,r,1,t??null,i,!1,s,o),r[ni]=e.current,Ca(r),n)for(r=0;r<n.length;r++)t=n[r],i=t._getVersion,i=i(t._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[t,i]:e.mutableSourceEagerHydrationData.push(t,i);return new ku(e)};en.render=function(r,e,t){if(!Eu(e))throw Error(te(200));return Mu(null,r,e,!1,t)};en.unmountComponentAtNode=function(r){if(!Eu(r))throw Error(te(40));return r._reactRootContainer?(cs(function(){Mu(null,null,r,!1,function(){r._reactRootContainer=null,r[ni]=null})}),!0):!1};en.unstable_batchedUpdates=hf;en.unstable_renderSubtreeIntoContainer=function(r,e,t,n){if(!Eu(t))throw Error(te(200));if(r==null||r._reactInternals===void 0)throw Error(te(38));return Mu(r,e,t,!1,n)};en.version="18.3.1-next-f1338f8080-20240426";function S1(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(S1)}catch(r){console.error(r)}}S1(),Sy.exports=en;var BS=Sy.exports,Bg=BS;td.createRoot=Bg.createRoot,td.hydrateRoot=Bg.hydrateRoot;var x1=Object.defineProperty,zS=(r,e,t)=>e in r?x1(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ye=(r,e)=>x1(r,"name",{value:e,configurable:!0}),oa=(r,e,t)=>(zS(r,typeof e!="symbol"?e+"":e,t),t),ce=(r=>(r[r.Keyboard=0]="Keyboard",r[r.Mouse=1]="Mouse",r[r.Gamepad=2]="Gamepad",r[r.Touch=3]="Touch",r[r.TVRemote=4]="TVRemote",r[r.TextInput=5]="TextInput",r[r.Motion=6]="Motion",r[r.TouchZone=7]="TouchZone",r))(ce||{}),Ai=(r=>(r[r.KeyA=0]="KeyA",r[r.KeyB=1]="KeyB",r[r.KeyC=2]="KeyC",r[r.KeyD=3]="KeyD",r[r.KeyE=4]="KeyE",r[r.KeyF=5]="KeyF",r[r.KeyG=6]="KeyG",r[r.KeyH=7]="KeyH",r[r.KeyI=8]="KeyI",r[r.KeyJ=9]="KeyJ",r[r.KeyK=10]="KeyK",r[r.KeyL=11]="KeyL",r[r.KeyM=12]="KeyM",r[r.KeyN=13]="KeyN",r[r.KeyO=14]="KeyO",r[r.KeyP=15]="KeyP",r[r.KeyQ=16]="KeyQ",r[r.KeyR=17]="KeyR",r[r.KeyS=18]="KeyS",r[r.KeyT=19]="KeyT",r[r.KeyU=20]="KeyU",r[r.KeyV=21]="KeyV",r[r.KeyW=22]="KeyW",r[r.KeyX=23]="KeyX",r[r.KeyY=24]="KeyY",r[r.KeyZ=25]="KeyZ",r[r.Digit0=26]="Digit0",r[r.Digit1=27]="Digit1",r[r.Digit2=28]="Digit2",r[r.Digit3=29]="Digit3",r[r.Digit4=30]="Digit4",r[r.Digit5=31]="Digit5",r[r.Digit6=32]="Digit6",r[r.Digit7=33]="Digit7",r[r.Digit8=34]="Digit8",r[r.Digit9=35]="Digit9",r[r.ArrowUp=36]="ArrowUp",r[r.ArrowDown=37]="ArrowDown",r[r.ArrowLeft=38]="ArrowLeft",r[r.ArrowRight=39]="ArrowRight",r[r.Space=40]="Space",r[r.Enter=41]="Enter",r[r.Escape=42]="Escape",r[r.Backspace=43]="Backspace",r[r.Tab=44]="Tab",r[r.ShiftLeft=45]="ShiftLeft",r[r.ShiftRight=46]="ShiftRight",r[r.ControlLeft=47]="ControlLeft",r[r.ControlRight=48]="ControlRight",r[r.AltLeft=49]="AltLeft",r[r.AltRight=50]="AltRight",r[r.MetaLeft=51]="MetaLeft",r[r.MetaRight=52]="MetaRight",r[r.CapsLock=53]="CapsLock",r[r.Delete=54]="Delete",r[r.Insert=55]="Insert",r[r.Home=56]="Home",r[r.End=57]="End",r[r.PageUp=58]="PageUp",r[r.PageDown=59]="PageDown",r[r.F1=60]="F1",r[r.F2=61]="F2",r[r.F3=62]="F3",r[r.F4=63]="F4",r[r.F5=64]="F5",r[r.F6=65]="F6",r[r.F7=66]="F7",r[r.F8=67]="F8",r[r.F9=68]="F9",r[r.F10=69]="F10",r[r.F11=70]="F11",r[r.F12=71]="F12",r[r.Minus=72]="Minus",r[r.Equal=73]="Equal",r[r.BracketLeft=74]="BracketLeft",r[r.BracketRight=75]="BracketRight",r[r.Backslash=76]="Backslash",r[r.Semicolon=77]="Semicolon",r[r.Quote=78]="Quote",r[r.Comma=79]="Comma",r[r.Period=80]="Period",r[r.Slash=81]="Slash",r[r.Backquote=82]="Backquote",r[r.Numpad0=91]="Numpad0",r[r.Numpad1=92]="Numpad1",r[r.Numpad2=93]="Numpad2",r[r.Numpad3=94]="Numpad3",r[r.Numpad4=95]="Numpad4",r[r.Numpad5=96]="Numpad5",r[r.Numpad6=97]="Numpad6",r[r.Numpad7=98]="Numpad7",r[r.Numpad8=99]="Numpad8",r[r.Numpad9=100]="Numpad9",r[r.NumpadAdd=101]="NumpadAdd",r[r.NumpadSubtract=102]="NumpadSubtract",r[r.NumpadMultiply=103]="NumpadMultiply",r[r.NumpadDivide=104]="NumpadDivide",r[r.NumpadDecimal=105]="NumpadDecimal",r[r.NumpadEnter=106]="NumpadEnter",r[r.NumLock=107]="NumLock",r[r.PrintScreen=111]="PrintScreen",r[r.ScrollLock=112]="ScrollLock",r[r.Pause=113]="Pause",r[r.ContextMenu=114]="ContextMenu",r))(Ai||{});function OS(r){let e=Ai[r];return e!==void 0?e:null}Ye(OS,"keyCodeToKeyboardInput");function DS(r){return Ai[r]}Ye(DS,"keyboardInputToKeyCode");var Nt=(r=>(r[r.LeftButton=0]="LeftButton",r[r.MiddleButton=1]="MiddleButton",r[r.RightButton=2]="RightButton",r[r.Button4=3]="Button4",r[r.Button5=4]="Button5",r[r.PositionX=100]="PositionX",r[r.PositionY=101]="PositionY",r[r.DeltaX=102]="DeltaX",r[r.DeltaY=103]="DeltaY",r[r.WheelDeltaY=104]="WheelDeltaY",r[r.WheelDeltaX=105]="WheelDeltaX",r))(Nt||{});function FS(r){return r<100}Ye(FS,"isMouseButton");function LS(r){return r>=100}Ye(LS,"isMouseAxis");var Cf=(r=>(r[r.ButtonA=0]="ButtonA",r[r.ButtonB=1]="ButtonB",r[r.ButtonX=2]="ButtonX",r[r.ButtonY=3]="ButtonY",r[r.LeftShoulder=4]="LeftShoulder",r[r.RightShoulder=5]="RightShoulder",r[r.LeftTrigger=6]="LeftTrigger",r[r.RightTrigger=7]="RightTrigger",r[r.Select=8]="Select",r[r.Start=9]="Start",r[r.LeftStick=10]="LeftStick",r[r.RightStick=11]="RightStick",r[r.DPadUp=12]="DPadUp",r[r.DPadDown=13]="DPadDown",r[r.DPadLeft=14]="DPadLeft",r[r.DPadRight=15]="DPadRight",r[r.Home=16]="Home",r[r.Touchpad=17]="Touchpad",r[r.LeftStickX=100]="LeftStickX",r[r.LeftStickY=101]="LeftStickY",r[r.RightStickX=102]="RightStickX",r[r.RightStickY=103]="RightStickY",r[r.LeftTriggerAxis=104]="LeftTriggerAxis",r[r.RightTriggerAxis=105]="RightTriggerAxis",r))(Cf||{});function _S(r){return r<100}Ye(_S,"isGamepadButton");function $S(r){return r>=100}Ye($S,"isGamepadAxis");function NS(r){return r>=0&&r<=19?r:null}Ye(NS,"gamepadButtonIndexToInput");function VS(r){return{0:100,1:101,2:102,3:103}[r]??null}Ye(VS,"gamepadAxisIndexToInput");var bf=(r=>(r[r.Touch0=0]="Touch0",r[r.Touch1=1]="Touch1",r[r.Touch2=2]="Touch2",r[r.Touch3=3]="Touch3",r[r.Touch4=4]="Touch4",r[r.Touch5=5]="Touch5",r[r.Touch6=6]="Touch6",r[r.Touch7=7]="Touch7",r[r.Touch8=8]="Touch8",r[r.Touch9=9]="Touch9",r[r.Touch0X=100]="Touch0X",r[r.Touch0Y=101]="Touch0Y",r[r.Touch1X=102]="Touch1X",r[r.Touch1Y=103]="Touch1Y",r[r.Touch2X=104]="Touch2X",r[r.Touch2Y=105]="Touch2Y",r[r.Touch3X=106]="Touch3X",r[r.Touch3Y=107]="Touch3Y",r[r.Touch4X=108]="Touch4X",r[r.Touch4Y=109]="Touch4Y",r[r.Touch5X=110]="Touch5X",r[r.Touch5Y=111]="Touch5Y",r[r.Touch6X=112]="Touch6X",r[r.Touch6Y=113]="Touch6Y",r[r.Touch7X=114]="Touch7X",r[r.Touch7Y=115]="Touch7Y",r[r.Touch8X=116]="Touch8X",r[r.Touch8Y=117]="Touch8Y",r[r.Touch9X=118]="Touch9X",r[r.Touch9Y=119]="Touch9Y",r[r.PinchScale=200]="PinchScale",r[r.RotationAngle=201]="RotationAngle",r[r.SwipeVelocityX=202]="SwipeVelocityX",r[r.SwipeVelocityY=203]="SwipeVelocityY",r))(bf||{});function HS(r){return r<100}Ye(HS,"isTouchButton");function jS(r){return r>=100&&r<200}Ye(jS,"isTouchPosition");function YS(r){return r>=200}Ye(YS,"isTouchGesture");function WS(r){return r<0||r>9?null:100+r*2}Ye(WS,"getTouchXAxis");function GS(r){return r<0||r>9?null:101+r*2}Ye(GS,"getTouchYAxis");var Sf=(r=>(r[r.Zone0=0]="Zone0",r[r.Zone1=1]="Zone1",r[r.Zone2=2]="Zone2",r[r.Zone3=3]="Zone3",r[r.Zone4=4]="Zone4",r[r.Zone5=5]="Zone5",r[r.Zone6=6]="Zone6",r[r.Zone7=7]="Zone7",r[r.Zone8=8]="Zone8",r[r.Zone9=9]="Zone9",r[r.Zone10=10]="Zone10",r[r.Zone11=11]="Zone11",r[r.Zone12=12]="Zone12",r[r.Zone13=13]="Zone13",r[r.Zone14=14]="Zone14",r[r.Zone15=15]="Zone15",r[r.Zone16=16]="Zone16",r[r.Zone17=17]="Zone17",r[r.Zone18=18]="Zone18",r[r.Zone19=19]="Zone19",r[r.Zone20=20]="Zone20",r[r.Zone21=21]="Zone21",r[r.Zone22=22]="Zone22",r[r.Zone23=23]="Zone23",r[r.Zone24=24]="Zone24",r[r.Zone25=25]="Zone25",r[r.Zone26=26]="Zone26",r[r.Zone27=27]="Zone27",r[r.Zone28=28]="Zone28",r[r.Zone29=29]="Zone29",r[r.Zone30=30]="Zone30",r[r.Zone31=31]="Zone31",r[r.Zone0X=100]="Zone0X",r[r.Zone0Y=101]="Zone0Y",r[r.Zone1X=102]="Zone1X",r[r.Zone1Y=103]="Zone1Y",r[r.Zone2X=104]="Zone2X",r[r.Zone2Y=105]="Zone2Y",r[r.Zone3X=106]="Zone3X",r[r.Zone3Y=107]="Zone3Y",r[r.Zone4X=108]="Zone4X",r[r.Zone4Y=109]="Zone4Y",r[r.Zone5X=110]="Zone5X",r[r.Zone5Y=111]="Zone5Y",r[r.Zone6X=112]="Zone6X",r[r.Zone6Y=113]="Zone6Y",r[r.Zone7X=114]="Zone7X",r[r.Zone7Y=115]="Zone7Y",r[r.Zone8X=116]="Zone8X",r[r.Zone8Y=117]="Zone8Y",r[r.Zone9X=118]="Zone9X",r[r.Zone9Y=119]="Zone9Y",r[r.Zone10X=120]="Zone10X",r[r.Zone10Y=121]="Zone10Y",r[r.Zone11X=122]="Zone11X",r[r.Zone11Y=123]="Zone11Y",r[r.Zone12X=124]="Zone12X",r[r.Zone12Y=125]="Zone12Y",r[r.Zone13X=126]="Zone13X",r[r.Zone13Y=127]="Zone13Y",r[r.Zone14X=128]="Zone14X",r[r.Zone14Y=129]="Zone14Y",r[r.Zone15X=130]="Zone15X",r[r.Zone15Y=131]="Zone15Y",r[r.Zone16X=132]="Zone16X",r[r.Zone16Y=133]="Zone16Y",r[r.Zone17X=134]="Zone17X",r[r.Zone17Y=135]="Zone17Y",r[r.Zone18X=136]="Zone18X",r[r.Zone18Y=137]="Zone18Y",r[r.Zone19X=138]="Zone19X",r[r.Zone19Y=139]="Zone19Y",r[r.Zone20X=140]="Zone20X",r[r.Zone20Y=141]="Zone20Y",r[r.Zone21X=142]="Zone21X",r[r.Zone21Y=143]="Zone21Y",r[r.Zone22X=144]="Zone22X",r[r.Zone22Y=145]="Zone22Y",r[r.Zone23X=146]="Zone23X",r[r.Zone23Y=147]="Zone23Y",r[r.Zone24X=148]="Zone24X",r[r.Zone24Y=149]="Zone24Y",r[r.Zone25X=150]="Zone25X",r[r.Zone25Y=151]="Zone25Y",r[r.Zone26X=152]="Zone26X",r[r.Zone26Y=153]="Zone26Y",r[r.Zone27X=154]="Zone27X",r[r.Zone27Y=155]="Zone27Y",r[r.Zone28X=156]="Zone28X",r[r.Zone28Y=157]="Zone28Y",r[r.Zone29X=158]="Zone29X",r[r.Zone29Y=159]="Zone29Y",r[r.Zone30X=160]="Zone30X",r[r.Zone30Y=161]="Zone30Y",r[r.Zone31X=162]="Zone31X",r[r.Zone31Y=163]="Zone31Y",r))(Sf||{});function XS(r){return r<100}Ye(XS,"isTouchZoneButton");function KS(r){return r>=100}Ye(KS,"isTouchZonePosition");function ZS(r){return r<0||r>31?null:100+r*2}Ye(ZS,"getTouchZoneXAxis");function qS(r){return r<0||r>31?null:101+r*2}Ye(qS,"getTouchZoneYAxis");var xf=(r=>(r[r.DPadUp=0]="DPadUp",r[r.DPadDown=1]="DPadDown",r[r.DPadLeft=2]="DPadLeft",r[r.DPadRight=3]="DPadRight",r[r.DPadCenter=4]="DPadCenter",r[r.Play=5]="Play",r[r.Pause=6]="Pause",r[r.PlayPause=7]="PlayPause",r[r.Stop=8]="Stop",r[r.Rewind=9]="Rewind",r[r.FastForward=10]="FastForward",r[r.Previous=11]="Previous",r[r.Next=12]="Next",r[r.Record=13]="Record",r[r.VolumeUp=15]="VolumeUp",r[r.VolumeDown=16]="VolumeDown",r[r.Mute=17]="Mute",r[r.ChannelUp=18]="ChannelUp",r[r.ChannelDown=19]="ChannelDown",r[r.Back=20]="Back",r[r.Home=21]="Home",r[r.Menu=22]="Menu",r[r.Info=23]="Info",r[r.Guide=24]="Guide",r[r.Exit=25]="Exit",r[r.Red=30]="Red",r[r.Green=31]="Green",r[r.Yellow=32]="Yellow",r[r.Blue=33]="Blue",r[r.Digit0=40]="Digit0",r[r.Digit1=41]="Digit1",r[r.Digit2=42]="Digit2",r[r.Digit3=43]="Digit3",r[r.Digit4=44]="Digit4",r[r.Digit5=45]="Digit5",r[r.Digit6=46]="Digit6",r[r.Digit7=47]="Digit7",r[r.Digit8=48]="Digit8",r[r.Digit9=49]="Digit9",r[r.Input=50]="Input",r[r.Settings=51]="Settings",r[r.Subtitle=52]="Subtitle",r[r.Audio=53]="Audio",r[r.Power=54]="Power",r[r.PointerX=100]="PointerX",r[r.PointerY=101]="PointerY",r[r.GyroX=102]="GyroX",r[r.GyroY=103]="GyroY",r[r.GyroZ=104]="GyroZ",r))(xf||{});function QS(r){return r<100}Ye(QS,"isTVRemoteButton");function JS(r){return r>=100}Ye(JS,"isTVRemoteAxis");function ex(r,e){return{device:r,input:e}}Ye(ex,"createInputDescriptor");function aa(r){switch(r.device){case 0:return!0;case 1:return r.input<100;case 2:return r.input<100;case 3:return r.input<100;case 7:return r.input<100;case 4:return r.input<100;default:return!1}}Ye(aa,"isButton");function I1(r){return!aa(r)}Ye(I1,"isAxis");function tx(r){let e=new Uint8Array(3);return e[0]=r.device,e[1]=r.input&255,e[2]=r.input>>8&255,e}Ye(tx,"serializeInputDescriptor");function rx(r,e=0){let t=r[e],n=r[e+1]|r[e+2]<<8;return{device:t,input:n}}Ye(rx,"deserializeInputDescriptor");function nx(r){let e=ce[r.device],t;switch(r.device){case 0:t=Ai[r.input];break;case 1:t=Nt[r.input];break;case 2:t=Cf[r.input];break;case 3:t=bf[r.input];break;case 7:t=Sf[r.input];break;case 4:t=xf[r.input];break;default:t="Unknown"}return`${e}:${t}`}Ye(nx,"inputDescriptorToString");function ix(r){var s;let[e,t]=r.split(":");if(!e||!t)return null;let n=(s=Object.entries(ce).find(([o,a])=>o.toLowerCase()===e.toLowerCase()&&typeof a=="number"))==null?void 0:s[1];if(n===void 0)return null;let i;switch(n){case 0:i=Ai[t];break;case 1:i=Nt[t];break;case 2:i=Cf[t];break;case 3:i=bf[t];break;case 4:i=xf[t];break;case 7:i=Sf[t];break}return i===void 0?null:{device:n,input:i}}Ye(ix,"parseInputDescriptor");var k1=class Ir{constructor(e=0,t=0){oa(this,"x"),oa(this,"y"),this.x=e,this.y=t}static zero(){return new Ir(0,0)}static one(){return new Ir(1,1)}static up(){return new Ir(0,-1)}static down(){return new Ir(0,1)}static left(){return new Ir(-1,0)}static right(){return new Ir(1,0)}add(e){return new Ir(this.x+e.x,this.y+e.y)}subtract(e){return new Ir(this.x-e.x,this.y-e.y)}multiply(e){return new Ir(this.x*e,this.y*e)}divide(e){if(e===0)throw new Error("Division by zero");return new Ir(this.x/e,this.y/e)}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){let e=this.length();return e===0?Ir.zero():this.divide(e)}distance(e){return this.subtract(e).length()}distanceSquared(e){return this.subtract(e).lengthSquared()}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}angle(){return Math.atan2(this.y,this.x)}angleTo(e){return Math.atan2(e.y-this.y,e.x-this.x)}rotate(e){let t=Math.cos(e),n=Math.sin(e);return new Ir(this.x*t-this.y*n,this.x*n+this.y*t)}lerp(e,t){return new Ir(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)}clone(){return new Ir(this.x,this.y)}equals(e){return this.x===e.x&&this.y===e.y}toString(){return`Vector2(${this.x}, ${this.y})`}toArray(){return[this.x,this.y]}set(e,t){return this.x=e,this.y=t,this}copy(e){return this.x=e.x,this.y=e.y,this}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e,this.y*=e,this}divideInPlace(e){if(e===0)throw new Error("Division by zero");return this.x/=e,this.y/=e,this}normalizeInPlace(){let e=this.length();return e===0?(this.x=0,this.y=0):(this.x/=e,this.y/=e),this}};Ye(k1,"Vector2");var Yt=k1,sx=class or{constructor(e=0,t=0,n=0){oa(this,"x"),oa(this,"y"),oa(this,"z"),this.x=e,this.y=t,this.z=n}static zero(){return new or(0,0,0)}static one(){return new or(1,1,1)}static up(){return new or(0,1,0)}static down(){return new or(0,-1,0)}static left(){return new or(-1,0,0)}static right(){return new or(1,0,0)}static forward(){return new or(0,0,1)}static back(){return new or(0,0,-1)}add(e){return new or(this.x+e.x,this.y+e.y,this.z+e.z)}subtract(e){return new or(this.x-e.x,this.y-e.y,this.z-e.z)}multiply(e){return new or(this.x*e,this.y*e,this.z*e)}divide(e){if(e===0)throw new Error("Division by zero");return new or(this.x/e,this.y/e,this.z/e)}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z}normalize(){let e=this.length();return e===0?or.zero():this.divide(e)}distance(e){return this.subtract(e).length()}distanceSquared(e){return this.subtract(e).lengthSquared()}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}cross(e){return new or(this.y*e.z-this.z*e.y,this.z*e.x-this.x*e.z,this.x*e.y-this.y*e.x)}lerp(e,t){return new or(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t,this.z+(e.z-this.z)*t)}clone(){return new or(this.x,this.y,this.z)}equals(e){return this.x===e.x&&this.y===e.y&&this.z===e.z}toString(){return`Vector3(${this.x}, ${this.y}, ${this.z})`}toArray(){return[this.x,this.y,this.z]}set(e,t,n){return this.x=e,this.y=t,this.z=n,this}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}addInPlace(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}multiplyInPlace(e){return this.x*=e,this.y*=e,this.z*=e,this}divideInPlace(e){if(e===0)throw new Error("Division by zero");return this.x/=e,this.y/=e,this.z/=e,this}normalizeInPlace(){let e=this.length();return e===0?(this.x=0,this.y=0,this.z=0):(this.x/=e,this.y/=e,this.z/=e),this}};Ye(sx,"Vector3");var Ge={scanlines:{opacity:.15,pattern:"horizontal",color:{r:0,g:0,b:0}},ambientEffect:{blur:30,scale:1.3,opacity:.7}},js={color:"rgba(144, 24, 24, 1)",lineWidth:1},Vt=(r=>(r.None="none",r.Eighth="eighth",r.Quarter="quarter",r.Half="half",r.Integer="integer",r.Responsive="responsive",r))(Vt||{}),ox=(r=>(r[r.None=0]="None",r[r.Eighth=1]="Eighth",r[r.Quarter=2]="Quarter",r[r.Half=3]="Half",r[r.Integer=4]="Integer",r[r.Responsive=5]="Responsive",r))(ox||{});function E1(r){switch(r){case"none":return 0;case"eighth":return 1;case"quarter":return 2;case"half":return 3;case"integer":return 4;case"responsive":return 5;default:return 0}}Ye(E1,"scalingModeToValue");function If(r){switch(r){case 0:return"none";case 1:return"eighth";case 2:return"quarter";case 3:return"half";case 4:return"integer";case 5:return"responsive";default:return"none"}}Ye(If,"valueToScalingMode");var yt=(r=>(r[r.Disconnected=0]="Disconnected",r[r.Connecting=1]="Connecting",r[r.Connected=2]="Connected",r[r.Reconnecting=3]="Reconnecting",r[r.Error=4]="Error",r))(yt||{}),ax=(r=>(r.SocketIO="socketio",r.WebRTC="webrtc",r))(ax||{}),M1=(r=>(r[r.Ping=0]="Ping",r[r.Pong=1]="Pong",r[r.Join=2]="Join",r[r.JoinResponse=3]="JoinResponse",r[r.SystemMessage=4]="SystemMessage",r[r.Input=16]="Input",r[r.Update=17]="Update",r[r.Audio=18]="Audio",r[r.Vibration=19]="Vibration",r[r.Load=48]="Load",r[r.Asset=49]="Asset",r))(M1||{});function lx(r){return r in M1}Ye(lx,"isNetworkEvent");var Da=Object.defineProperty,ux=Object.getOwnPropertyDescriptor,cx=Object.getOwnPropertyNames,dx=Object.prototype.hasOwnProperty,hx=(r,e,t)=>e in r?Da(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,J=(r,e)=>Da(r,"name",{value:e,configurable:!0}),ll=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')}),Uu=(r,e)=>()=>(r&&(e=r(r=0)),e),Au=(r,e)=>{for(var t in e)Da(r,t,{get:e[t],enumerable:!0})},fx=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of cx(e))!dx.call(r,i)&&i!==t&&Da(r,i,{get:()=>e[i],enumerable:!(n=ux(e,i))||n.enumerable});return r},ul=r=>fx(Da({},"__esModule",{value:!0}),r),O=(r,e,t)=>(hx(r,typeof e!="symbol"?e+"":e,t),t),U1={};Au(U1,{VibrationOrderType:()=>Xd});var Xd,A1=Uu(()=>{Xd=(r=>(r[r.MobileVibrate=1]="MobileVibrate",r[r.MobileCancel=2]="MobileCancel",r[r.GamepadVibrate=16]="GamepadVibrate",r[r.GamepadCancel=17]="GamepadCancel",r))(Xd||{})}),T1={};Au(T1,{GamepadVibrateFlags:()=>Zd,MobileVibrateFlags:()=>Kd});var Kd,Zd,R1=Uu(()=>{Kd=(r=>(r[r.HasIntensity=1]="HasIntensity",r))(Kd||{}),Zd=(r=>(r[r.HasStartDelay=1]="HasStartDelay",r[r.AllGamepads=2]="AllGamepads",r))(Zd||{})}),P1={};Au(P1,{AudioOrderType:()=>qd,AudioTargetType:()=>Qd,getAudioOrderTypeName:()=>z1,isValidAudioOrderType:()=>B1});function B1(r){return r>=1&&r<=9}function z1(r){switch(r){case 1:return"PlaySound";case 2:return"PlayGlobalSound";case 3:return"StopSound";case 4:return"FadeOutSound";case 5:return"PauseSound";case 6:return"ResumeSound";case 7:return"SetListenerPosition";case 8:return"ConfigureSpatial";case 9:return"SetSoundEffects";default:return`UnknownAudio(0x${r.toString(16)})`}}var qd,Qd,O1=Uu(()=>{qd=(r=>(r[r.PlaySound=1]="PlaySound",r[r.PlayGlobalSound=2]="PlayGlobalSound",r[r.StopSound=3]="StopSound",r[r.FadeOutSound=4]="FadeOutSound",r[r.PauseSound=5]="PauseSound",r[r.ResumeSound=6]="ResumeSound",r[r.SetListenerPosition=7]="SetListenerPosition",r[r.ConfigureSpatial=8]="ConfigureSpatial",r[r.SetSoundEffects=9]="SetSoundEffects",r))(qd||{}),Qd=(r=>(r[r.InstanceId=0]="InstanceId",r[r.SoundId=1]="SoundId",r[r.All=2]="All",r))(Qd||{}),J(B1,"isValidAudioOrderType"),J(z1,"getAudioOrderTypeName")}),D1={};Au(D1,{PlaySoundFlags:()=>Jd,SoundEffectsFlags:()=>eh});var Jd,eh,F1=Uu(()=>{Jd=(r=>(r[r.Loop=1]="Loop",r[r.HasVolume=2]="HasVolume",r[r.HasPitch=4]="HasPitch",r[r.HasFadeIn=8]="HasFadeIn",r[r.HasPosition=16]="HasPosition",r[r.HasLowpass=32]="HasLowpass",r[r.HasHighpass=64]="HasHighpass",r[r.HasReverb=128]="HasReverb",r))(Jd||{}),eh=(r=>(r[r.HasLowpass=1]="HasLowpass",r[r.HasHighpass=2]="HasHighpass",r[r.HasReverb=4]="HasReverb",r))(eh||{})}),L1=class{constructor(e=0,t=60,n=40){if(O(this,"id"),O(this,"origin"),O(this,"size"),O(this,"commandSink"),O(this,"previousOrigin",new Yt(0,0)),O(this,"previousSize",new Yt(0,0)),O(this,"renderPasses"),e<0||e>255)throw new Error(`Display ID must be between 0 and 255, got ${e}`);if(t<1||t>256)throw new Error(`Display sizeX must be between 1 and 256, got ${t}`);if(n<1||n>256)throw new Error(`Display sizeY must be between 1 and 256, got ${n}`);this.id=e,this.origin=new Yt(0,0),this.size=new Yt(t,n)}getId(){return this.id}setCommandSink(e){this.commandSink=e}getOrigin(){return this.origin}setOrigin(e){this.origin=e}moveOrigin(e,t){this.origin.x+=e,this.origin.y+=t}hasOriginChanged(){return this.origin.x!==this.previousOrigin.x||this.origin.y!==this.previousOrigin.y}hasSizeChanged(){return this.size.x!==this.previousSize.x||this.size.y!==this.previousSize.y}hasChanged(){return this.hasOriginChanged()||this.hasSizeChanged()}resetChangeTracking(){this.previousOrigin.x=this.origin.x,this.previousOrigin.y=this.origin.y,this.previousSize.x=this.size.x,this.previousSize.y=this.size.y}getSize(){return this.size}setSize(e){if(e.x<1||e.x>256)throw new Error(`Display sizeX must be between 1 and 256, got ${e.x}`);if(e.y<1||e.y>256)throw new Error(`Display sizeY must be between 1 and 256, got ${e.y}`);this.size=e}getSink(){if(!this.commandSink)throw new Error("Display is not attached to a User");return this.commandSink}setPostProcess(e){this.getSink().setPostProcess(this.id,e)}setScanlinesEnabled(e){this.getSink().setScanlinesEnabled(this.id,e)}setScanlinesOpacity(e){this.getSink().setScanlinesOpacity(this.id,e)}setScanlinesPattern(e){this.getSink().setScanlinesPattern(this.id,e)}setAmbientEffect(e){this.getSink().setAmbientEffect(this.id,e)}setAmbientEffectEnabled(e){this.getSink().setAmbientEffectEnabled(this.id,e)}setAmbientEffectBlur(e){this.getSink().setAmbientEffectBlur(this.id,e)}setAmbientEffectScale(e){this.getSink().setAmbientEffectScale(this.id,e)}isAmbientEffectEnabled(){return this.getSink().isAmbientEffectEnabled(this.id)}getAmbientEffectConfig(){return this.getSink().getAmbientEffectConfig(this.id)}getPostProcessConfig(){return this.getSink().getPostProcessConfig(this.id)}setScalingMode(e){this.getSink().setScalingMode(this.id,e)}getScalingMode(){return this.getSink().getScalingMode(this.id)}setCellSize(e,t){this.getSink().setCellSize(this.id,e,t)}getCellSize(){return this.getSink().getCellSize(this.id)}setGrid(e){this.getSink().setGrid(this.id,e)}setGridEnabled(e){this.getSink().setGridEnabled(this.id,e)}isGridEnabled(){return this.getSink().isGridEnabled(this.id)}getGridConfig(){return this.getSink().getGridConfig(this.id)}switchPalette(e){this.getSink().switchPalette(this.id,e)}getCurrentPaletteSlotId(){return this.getSink().getCurrentPaletteSlotId(this.id)}getRenderPasses(){return this.renderPasses}setRenderPasses(e){if(!e||e.length===0){this.renderPasses=void 0;return}if(e.length>4)throw new Error(`renderPasses supports up to 4 entries, got ${e.length}`);this.renderPasses=e.map(t=>this.normalizePass(t))}normalizePass(e){let t=Math.max(0,Math.min(255,e.zMin)),n=Math.max(0,Math.min(255,e.zMax));if(t>n){let i=t;t=n,n=i}return{id:e.id,zMin:t,zMax:n,enabled:e.enabled!==!1}}getDebugInfo(){return{id:this.id,origin:{x:this.origin.x,y:this.origin.y},size:{x:this.size.x,y:this.size.y},renderPasses:this.renderPasses}}};J(L1,"Display");var px=L1,_1=J(r=>r?2:1,"charCodeByteSize"),gx=6,mx=6,yx=6,vx=7,wx=5,Cx=3,bx=1,Sx=6,xx=4,Ix=5,kx=2,Ex=8,Mx=7,Ux=7,Ax=8,Tx=10,Rx=6,Px=3,Bx=9,zx=15,Ox=51,Dx=5,Fx=6,Lx=4,_x=3,$x=3,Nx=4,Vx=5,Hx=4,jx=2,Yx=5,Wx=5,zg=5,Og=5,Gx=3,Dg=8,Fg=6,Lg=3,_g=8,$g=3,Ng=4,$1=class{constructor(e=65536,t=!1){O(this,"charCodes"),O(this,"fgColors"),O(this,"bgColors"),O(this,"size"),O(this,"is16bit"),this.size=e,this.is16bit=t,this.charCodes=t?new Uint16Array(e):new Uint8Array(e),this.fgColors=new Uint8Array(e),this.bgColors=new Uint8Array(e),this.clear()}clear(){this.charCodes.fill(0),this.fgColors.fill(255),this.bgColors.fill(255)}clearWithColor(e,t,n){let i=this.is16bit?e:e&255;this.charCodes.fill(i),this.fgColors.fill(t),this.bgColors.fill(n)}set(e,t,n,i){this.charCodes[e]=this.is16bit?t:t&255,this.fgColors[e]=n,this.bgColors[e]=i}fillCharsUniform(e,t,n,i){let s=this.is16bit?t:t&255;for(let o=0;o<e.length;o++){let a=e[o];this.charCodes[a]=s,this.fgColors[a]=n,this.bgColors[a]=i}}get(e){return{charCode:this.charCodes[e],fgColorCode:this.fgColors[e],bgColorCode:this.bgColors[e]}}setCharOnly(e,t){this.charCodes[e]=this.is16bit?t:t&255}setColorsOnly(e,t,n){this.fgColors[e]=t,this.bgColors[e]=n}getCharCode(e){return this.charCodes[e]}getFgColorCode(e){return this.fgColors[e]}getBgColorCode(e){return this.bgColors[e]}getRawCharCodes(){return this.charCodes}getRawFgColors(){return this.fgColors}getRawBgColors(){return this.bgColors}getSize(){return this.size}is16BitMode(){return this.is16bit}};J($1,"CellBuffer");var th=$1,N1=class{constructor(e){O(this,"data"),O(this,"size"),this.size=e,this.data=new Uint16Array(e)}clear(){this.data.fill(0)}set(e,t){this.data[e]=t}get(e){return this.data[e]}getRawData(){return this.data}getSize(){return this.size}};J(N1,"CharCodeBuffer");var Vg=N1,Xx=(r=>(r[r.Rectangle=1]="Rectangle",r[r.Circle=2]="Circle",r[r.Line=3]="Line",r[r.Ellipse=4]="Ellipse",r[r.Triangle=5]="Triangle",r))(Xx||{}),V1=class{constructor(){O(this,"currentWidth",256),O(this,"currentHeight",256)}rasterizeOrders(e,t,n,i,s){this.currentWidth=n,this.currentHeight=i,this.clearBuffer(t);for(let o of e)this.rasterizeOrder(o,t,s)}clearBuffer(e){e.clear()}rasterizeOrder(e,t,n){switch(e.type){case 1:this.rasterizeChar(e,t);break;case 2:this.rasterizeText(e,t);break;case 23:this.rasterizeTextMultiline(e,t);break;case 3:this.rasterizeSubFrame(e,t);break;case 4:this.rasterizeSubFrameMultiColor(e,t);break;case 5:this.rasterizeFullFrame(e,t);break;case 6:this.rasterizeFullFrameMultiColor(e,t);break;case 7:this.rasterizeSprite(e,t,n);break;case 8:this.rasterizeSpriteMultiColor(e,t,n);break;case 9:this.rasterizeColorMap(e,t);break;case 10:this.rasterizeShape(e,t);break;case 11:this.rasterizeDotCloud(e,t);break;case 12:this.rasterizeDotCloudMultiColor(e,t);break;case 17:this.rasterizeBitmask(e,t);break;case 18:this.rasterizeBitmask4(e,t);break;case 24:this.rasterizeBitmask16(e,t);break;case 25:this.rasterizePolyline(e,t);break;case 13:this.rasterizeSpriteCloud(e,t,n);break;case 14:this.rasterizeSpriteCloudMultiColor(e,t,n);break;case 15:this.rasterizeSpriteCloudVaried(e,t,n);break;case 16:this.rasterizeSpriteCloudVariedMultiColor(e,t,n);break;case 19:this.rasterizeFill(e,t);break;case 20:this.rasterizeFillChar(e,t);break;case 21:this.rasterizeFillSprite(e,t,n);break;case 22:this.rasterizeFillSpriteMultiColor(e,t,n);break}}rasterizeChar(e,t){let{posX:n,posY:i,charCode:s,bgColorCode:o,fgColorCode:a}=e;if(!this.isInBounds(n,i))return;let l=i*this.currentWidth+n;t.set(l,s,a,o)}rasterizeText(e,t){let{posX:n,posY:i,text:s,bgColorCode:o,fgColorCode:a}=e;if(this.isInBounds(n,i))for(let l=0;l<s.length;l++){let u=n+l;if(u>=this.currentWidth)break;let c=i*this.currentWidth+u,d=s.charCodeAt(l);t.set(c,d,a,o)}}rasterizeTextMultiline(e,t){let{posX:n,posY:i,text:s,bgColorCode:o,fgColorCode:a}=e,l=s.split(`
|
|
41
|
+
`),u=i;for(let c of l){if(u>=this.currentHeight)break;if(u>=0&&this.isInBounds(n,u))for(let d=0;d<c.length;d++){let h=n+d;if(h>=this.currentWidth)break;let f=u*this.currentWidth+h,p=c.charCodeAt(d);t.set(f,p,a,o)}u++}}rasterizeSubFrame(e,t){let{posX:n,posY:i,sizeX:s,sizeY:o,frame:a,bgColorCode:l,fgColorCode:u}=e;for(let c=0;c<o;c++){let d=i+c;if(!(d<0||d>=this.currentHeight))for(let h=0;h<s;h++){let f=n+h;if(f<0||f>=this.currentWidth)continue;let p=c*s+h;if(p>=a.length)break;let m=d*this.currentWidth+f;t.set(m,a[p],u,l)}}}rasterizeSubFrameMultiColor(e,t){let{posX:n,posY:i,sizeX:s,sizeY:o,frame:a}=e;for(let l=0;l<o;l++){let u=i+l;if(!(u<0||u>=this.currentHeight))for(let c=0;c<s;c++){let d=n+c;if(d<0||d>=this.currentWidth)continue;let h=l*s+c;if(h>=a.length)break;let f=a[h],p=u*this.currentWidth+d;t.set(p,f.charCode,f.fgColorCode,f.bgColorCode)}}}rasterizeFullFrame(e,t){let{frame:n,bgColorCode:i,fgColorCode:s}=e,o=this.currentWidth*this.currentHeight;for(let a=0;a<o&&a<n.length;a++)t.set(a,n[a],s,i)}rasterizeFullFrameMultiColor(e,t){let{frame:n}=e,i=this.currentWidth*this.currentHeight;for(let s=0;s<i&&s<n.length;s++){let o=n[s];t.set(s,o.charCode,o.fgColorCode,o.bgColorCode)}}rasterizeColorMap(e,t){let{posX:n,posY:i,sizeX:s,sizeY:o,colorData:a}=e;for(let l=0;l<o;l++){let u=i+l;if(!(u<0||u>=this.currentHeight))for(let c=0;c<s;c++){let d=n+c;if(d<0||d>=this.currentWidth)continue;let h=l*s+c;if(h>=a.length)break;let f=u*this.currentWidth+d,p=a[h];t.setColorsOnly(f,p.fgColorCode,p.bgColorCode)}}}rasterizeShape(e,t){let{shapeType:n,shapeData:i}=e;switch(n){case 1:this.rasterizeRectangle(i,t);break;case 2:this.rasterizeCircle(i,t);break;case 3:this.rasterizeLine(i,t);break;case 4:this.rasterizeEllipse(i,t);break;case 5:this.rasterizeTriangle(i,t);break}}rasterizeRectangle(e,t){let{posX:n,posY:i,width:s,height:o,filled:a,charCode:l,bgColorCode:u,fgColorCode:c}=e;if(a)for(let d=0;d<o;d++){let h=i+d;if(!(h<0||h>=this.currentHeight))for(let f=0;f<s;f++){let p=n+f;if(p<0||p>=this.currentWidth)continue;let m=h*this.currentWidth+p;t.set(m,l,c,u)}}else{for(let d=0;d<s;d++)this.setCell(n+d,i,l,u,c,t),this.setCell(n+d,i+o-1,l,u,c,t);for(let d=0;d<o;d++)this.setCell(n,i+d,l,u,c,t),this.setCell(n+s-1,i+d,l,u,c,t)}}rasterizeCircle(e,t){let{centerX:n,centerY:i,radius:s,filled:o,charCode:a,bgColorCode:l,fgColorCode:u}=e;if(o)for(let c=-s;c<=s;c++){let d=i+c;if(!(d<0||d>=this.currentHeight))for(let h=-s;h<=s;h++){let f=n+h;if(!(f<0||f>=this.currentWidth)&&h*h+c*c<=s*s){let p=d*this.currentWidth+f;t.set(p,a,u,l)}}}else{let c=s,d=0,h=0;for(;c>=d;)this.setCell(n+c,i+d,a,l,u,t),this.setCell(n+d,i+c,a,l,u,t),this.setCell(n-d,i+c,a,l,u,t),this.setCell(n-c,i+d,a,l,u,t),this.setCell(n-c,i-d,a,l,u,t),this.setCell(n-d,i-c,a,l,u,t),this.setCell(n+d,i-c,a,l,u,t),this.setCell(n+c,i-d,a,l,u,t),h<=0&&(d+=1,h+=2*d+1),h>0&&(c-=1,h-=2*c+1)}}rasterizeLine(e,t){let{x1:n,y1:i,x2:s,y2:o,charCode:a,bgColorCode:l,fgColorCode:u}=e,c=Math.abs(s-n),d=Math.abs(o-i),h=n<s?1:-1,f=i<o?1:-1,p=c-d,m=n,S=i;for(;this.setCell(m,S,a,l,u,t),!(m===s&&S===o);){let w=2*p;w>-d&&(p-=d,m+=h),w<c&&(p+=c,S+=f)}}rasterizePolyline(e,t){let{charCode:n,fgColorCode:i,bgColorCode:s,points:o}=e;if(o.length<2){o.length===1&&this.setCell(o[0].x,o[0].y,n,s,i,t);return}for(let a=0;a<o.length-1;a++){let l=o[a],u=o[a+1];this.rasterizeLineSegment(l.x,l.y,u.x,u.y,n,s,i,t)}}rasterizeLineSegment(e,t,n,i,s,o,a,l){let u=Math.abs(n-e),c=Math.abs(i-t),d=e<n?1:-1,h=t<i?1:-1,f=u-c,p=e,m=t;for(;this.setCell(p,m,s,o,a,l),!(p===n&&m===i);){let S=2*f;S>-c&&(f-=c,p+=d),S<u&&(f+=u,m+=h)}}rasterizeEllipse(e,t){let{centerX:n,centerY:i,radiusX:s,radiusY:o,filled:a,charCode:l,bgColorCode:u,fgColorCode:c}=e;if(a)for(let d=-o;d<=o;d++){let h=i+d;if(!(h<0||h>=this.currentHeight))for(let f=-s;f<=s;f++){let p=n+f;if(!(p<0||p>=this.currentWidth)&&f*f/(s*s)+d*d/(o*o)<=1){let m=h*this.currentWidth+p;t.set(m,l,c,u)}}}else{let d=Math.max(s,o)*8;for(let h=0;h<d;h++){let f=2*Math.PI*h/d,p=Math.round(n+s*Math.cos(f)),m=Math.round(i+o*Math.sin(f));this.setCell(p,m,l,u,c,t)}}}rasterizeTriangle(e,t){let{x1:n,y1:i,x2:s,y2:o,x3:a,y3:l,filled:u,charCode:c,bgColorCode:d,fgColorCode:h}=e;if(u){let f=[{x:n,y:i},{x:s,y:o},{x:a,y:l}].sort((y,C)=>y.y-C.y),[p,m,S]=f,w=J((y,C,x)=>{let I=Math.round(Math.min(C,x)),E=Math.round(Math.max(C,x));for(let A=I;A<=E;A++)if(A>=0&&A<this.currentWidth&&y>=0&&y<this.currentHeight){let R=y*this.currentWidth+A;t.set(R,c,h,d)}},"drawLine"),g=J((y,C,x,I,E)=>I===C?x:x+(y-C)*(E-x)/(I-C),"interpolate");for(let y=p.y;y<=m.y;y++){let C=g(y,p.y,p.x,S.y,S.x),x=g(y,p.y,p.x,m.y,m.x);w(y,C,x)}for(let y=m.y+1;y<=S.y;y++){let C=g(y,p.y,p.x,S.y,S.x),x=g(y,m.y,m.x,S.y,S.x);w(y,C,x)}}else this.drawLineSegment(n,i,s,o,c,d,h,t),this.drawLineSegment(s,o,a,l,c,d,h,t),this.drawLineSegment(a,l,n,i,c,d,h,t)}drawLineSegment(e,t,n,i,s,o,a,l){let u=Math.abs(n-e),c=Math.abs(i-t),d=e<n?1:-1,h=t<i?1:-1,f=u-c,p=e,m=t;for(;this.setCell(p,m,s,o,a,l),!(p===n&&m===i);){let S=2*f;S>-c&&(f-=c,p+=d),S<u&&(f+=u,m+=h)}}rasterizeDotCloud(e,t){let{charCode:n,bgColorCode:i,fgColorCode:s,positions:o}=e,a=this.currentWidth;for(let l=0;l<o.length;l++){let u=o[l];if(u.posX<0||u.posX>=a||u.posY<0||u.posY>=this.currentHeight)continue;let c=u.posY*a+u.posX;t.set(c,n,s,i)}}rasterizeDotCloudMultiColor(e,t){let{dots:n}=e;for(let i of n)this.setCell(i.posX,i.posY,i.charCode,i.bgColorCode,i.fgColorCode,t)}rasterizeBitmask(e,t){let{posX:n,posY:i,sizeX:s,sizeY:o,charCode:a,bgColorCode:l,fgColorCode:u,override:c,mask:d}=e;for(let h=0;h<o;h++){let f=i+h;if(!(f<0||f>=this.currentHeight))for(let p=0;p<s;p++){let m=n+p;if(m<0||m>=this.currentWidth)continue;let S=h*s+p,w=Math.floor(S/8),g=S%8,y=(d[w]&1<<g)!==0,C=f*this.currentWidth+m;y?t.set(C,a,u,l):c&&t.set(C,255,255,255)}}}rasterizeBitmask4(e,t){let{posX:n,posY:i,sizeX:s,sizeY:o,override:a,variants:l,mask:u}=e;for(let c=0;c<o;c++){let d=i+c;if(!(d<0||d>=this.currentHeight))for(let h=0;h<s;h++){let f=n+h;if(f<0||f>=this.currentWidth)continue;let p=c*s+h,m=Math.floor(p/4),S=p%4*2,w=u[m]>>S&3,g=d*this.currentWidth+f;if(w>0){let y=l[w-1];t.set(g,y.charCode,y.fgColorCode,y.bgColorCode)}else a&&t.set(g,255,255,255)}}}rasterizeBitmask16(e,t){let{posX:n,posY:i,sizeX:s,sizeY:o,override:a,variants:l,mask:u}=e;for(let c=0;c<o;c++){let d=i+c;if(!(d<0||d>=this.currentHeight))for(let h=0;h<s;h++){let f=n+h;if(f<0||f>=this.currentWidth)continue;let p=c*s+h,m=Math.floor(p/2),S=p%2*4,w=u[m]>>S&15,g=d*this.currentWidth+f;if(w>0){let y=l[w-1];t.set(g,y.charCode,y.fgColorCode,y.bgColorCode)}else a&&t.set(g,255,255,255)}}}rasterizeFill(e,t){let{charCode:n,bgColorCode:i,fgColorCode:s}=e;t.clearWithColor(n,s,i)}rasterizeFillChar(e,t){let{patternWidth:n,patternHeight:i,pattern:s,bgColorCode:o,fgColorCode:a}=e;for(let l=0;l<this.currentHeight;l++)for(let u=0;u<this.currentWidth;u++){let c=u%n,d=l%i*n+c;if(d<s.length){let h=l*this.currentWidth+u;t.set(h,s[d],a,o)}}}rasterizeSprite(e,t,n){if(!n)return;let{posX:i,posY:s,spriteIndex:o,bgColorCode:a,fgColorCode:l}=e,u=n.getUnicolorSprite(o);if(!u)return;let c=u.data;for(let d=0;d<u.sizeY;d++)for(let h=0;h<u.sizeX;h++){let f=i+h,p=s+d;if(!this.isInBounds(f,p))continue;let m=d*u.sizeX+h,S=c.get(m);this.setCell(f,p,S,a,l,t)}}rasterizeSpriteMultiColor(e,t,n){if(!n)return;let{posX:i,posY:s,spriteIndex:o}=e,a=n.getMulticolorSprite(o);if(!a)return;let l=a.data;for(let u=0;u<a.sizeY;u++)for(let c=0;c<a.sizeX;c++){let d=i+c,h=s+u;if(!this.isInBounds(d,h))continue;let f=u*a.sizeX+c,p=l.getCharCode(f),m=l.getFgColorCode(f),S=l.getBgColorCode(f);this.setCell(d,h,p,S,m,t)}}rasterizeSpriteCloud(e,t,n){if(!n)return;let{spriteIndex:i,bgColorCode:s,fgColorCode:o,positions:a}=e,l=n.getUnicolorSprite(i);if(l){if(l.sizeX===1&&l.sizeY===1){let u=l.data.get(0),c=this.currentWidth;for(let d=0;d<a.length;d++){let h=a[d];if(h.posX<0||h.posX>=c||h.posY<0||h.posY>=this.currentHeight)continue;let f=h.posY*c+h.posX;t.set(f,u,o,s)}return}for(let u=0;u<a.length;u++){let c=l.data;for(let d=0;d<l.sizeY;d++)for(let h=0;h<l.sizeX;h++){let f=a[u].posX+h,p=a[u].posY+d;if(!this.isInBounds(f,p))continue;let m=d*l.sizeX+h,S=c.get(m);this.setCell(f,p,S,s,o,t)}}}}rasterizeSpriteCloudMultiColor(e,t,n){if(!n)return;let{spriteIndex:i,positions:s}=e,o=n.getMulticolorSprite(i);if(o)for(let a=0;a<s.length;a++){let l=o.data;for(let u=0;u<o.sizeY;u++)for(let c=0;c<o.sizeX;c++){let d=s[a].posX+c,h=s[a].posY+u;if(!this.isInBounds(d,h))continue;let f=u*o.sizeX+c,p=l.getCharCode(f),m=l.getFgColorCode(f),S=l.getBgColorCode(f);this.setCell(d,h,p,S,m,t)}}}rasterizeSpriteCloudVaried(e,t,n){if(!n)return;let{sprites:i}=e;for(let s=0;s<i.length;s++){let o=i[s],a=n.getUnicolorSprite(o.spriteIndex);if(!a)continue;let l=a.data;for(let u=0;u<a.sizeY;u++)for(let c=0;c<a.sizeX;c++){let d=o.posX+c,h=o.posY+u;if(!this.isInBounds(d,h))continue;let f=u*a.sizeX+c,p=l.get(f);this.setCell(d,h,p,o.bgColorCode,o.fgColorCode,t)}}}rasterizeSpriteCloudVariedMultiColor(e,t,n){if(!n)return;let{sprites:i}=e;for(let s=0;s<i.length;s++){let o=i[s],a=n.getMulticolorSprite(o.spriteIndex);if(!a)continue;let l=a.data;for(let u=0;u<a.sizeY;u++)for(let c=0;c<a.sizeX;c++){let d=o.posX+c,h=o.posY+u;if(!this.isInBounds(d,h))continue;let f=u*a.sizeX+c,p=l.getCharCode(f),m=l.getFgColorCode(f),S=l.getBgColorCode(f);this.setCell(d,h,p,S,m,t)}}}rasterizeFillSprite(e,t,n){if(!n)return;let{spriteIndex:i,bgColorCode:s,fgColorCode:o}=e,a=n.getUnicolorSprite(i);if(!a)return;let l=a.data;for(let u=0;u<this.currentHeight;u++)for(let c=0;c<this.currentWidth;c++){let d=c%a.sizeX,h=u%a.sizeY*a.sizeX+d,f=l.get(h),p=u*this.currentWidth+c;t.set(p,f,o,s)}}rasterizeFillSpriteMultiColor(e,t,n){if(!n)return;let{spriteIndex:i}=e,s=n.getMulticolorSprite(i);if(!s)return;let o=s.data;for(let a=0;a<this.currentHeight;a++)for(let l=0;l<this.currentWidth;l++){let u=l%s.sizeX,c=a%s.sizeY*s.sizeX+u,d=o.getCharCode(c),h=o.getFgColorCode(c),f=o.getBgColorCode(c),p=a*this.currentWidth+l;t.set(p,d,h,f)}}setCell(e,t,n,i,s,o){if(!this.isInBounds(e,t))return;let a=t*this.currentWidth+e;o.set(a,n,s,i)}isInBounds(e,t){return e>=0&&e<this.currentWidth&&t>=0&&t<this.currentHeight}};J(V1,"LayerRasterizer");var Kx=V1,Dc=255,rh=class Yo{constructor(e,t,n,i,s){if(O(this,"id",0),O(this,"name"),O(this,"isMacroLayer"),O(this,"origin"),O(this,"orders",[]),O(this,"zOrder",0),O(this,"data"),O(this,"width"),O(this,"height"),O(this,"mustBeReliable",!1),O(this,"spriteRegistry"),O(this,"mode","server"),O(this,"charCodeMode"),O(this,"previousOrigin"),O(this,"previousZOrder"),O(this,"enabled",!0),O(this,"useSetMode",!1),O(this,"needsCommit",!1),n<1||n>256||i<1||i>256)throw new Error(`Layer size must be 1-256, got ${n}×${i}`);let o={};typeof s=="boolean"?o={mustBeReliable:s}:s&&(o=s),this.origin=e,this.zOrder=t,this.name=o.name,this.width=n,this.height=i,this.mustBeReliable=o.mustBeReliable??!1,this.isMacroLayer=o.isMacroLayer??!1,this.charCodeMode=o.charCodeMode??"8bit";let a=this.charCodeMode==="16bit";this.data=new th(n*i,a),this.previousOrigin=new Yt(e.x,e.y),this.previousZOrder=t}getIsMacroLayer(){return this.isMacroLayer}getCharCodeMode(){return this.charCodeMode}setMode(e){this.mode=e}setSpriteRegistry(e){this.spriteRegistry=e}getOrders(){return this.orders}addOrders(e){this.orders.push(...e),this.useSetMode=!1,(this.mode==="client"||this.mode==="standalone")&&Yo.rasterizer.rasterizeOrders(this.orders,this.data,this.width,this.height,this.spriteRegistry)}addTemporaryOrders(e){(this.mode==="client"||this.mode==="standalone")&&Yo.rasterizer.rasterizeOrders(e,this.data,this.width,this.height,this.spriteRegistry)}setOrders(e){this.orders=e,this.useSetMode=!0,(this.mode==="client"||this.mode==="standalone")&&Yo.rasterizer.rasterizeOrders(e,this.data,this.width,this.height,this.spriteRegistry)}clearOrders(){this.orders=[],(this.mode==="client"||this.mode==="standalone")&&Yo.rasterizer.clearBuffer(this.data)}getOrigin(){return this.origin}setOrigin(e){this.origin=e}getZOrder(){return this.zOrder}setZOrder(e){this.zOrder=e}getId(){return this.id}getName(){return this.name}setName(e){let t=typeof e=="string"?e.trim():void 0;this.name=t&&t.length>0?t:void 0}getDebugInfo(){return{id:this.id,name:this.name,z:this.zOrder,mustBeReliable:this.mustBeReliable,charCodeMode:this.charCodeMode,width:this.width,height:this.height,origin:{x:this.origin.x,y:this.origin.y},enabled:this.enabled,useSetMode:this.useSetMode,needsCommit:this.needsCommit,ordersCount:this.orders.length}}setIdInternal(e){this.id=e}getData(){return this.data}getWidth(){return this.width}getHeight(){return this.height}getCellAt(e,t){return e<0||e>=this.width||t<0||t>=this.height?null:this.data.get(t*this.width+e)}setMustBeReliable(e){this.mustBeReliable=e}getMustBeReliable(){return this.mustBeReliable}setEnabled(e){this.enabled=e}isEnabled(){return this.enabled}hasOriginChanged(){return this.origin.x!==this.previousOrigin.x||this.origin.y!==this.previousOrigin.y}hasZOrderChanged(){return this.zOrder!==this.previousZOrder}calculateUpdateFlags(){if(!this.enabled)return 0;let e=1;return this.useSetMode&&(e|=2),this.hasOriginChanged()&&(e|=4),this.hasZOrderChanged()&&(e|=8),(this.orders.length>0||this.needsCommit&&this.useSetMode)&&(e|=4),e}resetChangeTracking(){this.previousOrigin.x=this.origin.x,this.previousOrigin.y=this.origin.y,this.previousZOrder=this.zOrder}commit(){this.orders.length>Dc&&(console.error(`[UTSP] ⚠️ CRITICAL: Layer ${this.id} has ${this.orders.length} orders, but max is ${Dc}!
|
|
42
42
|
This WILL cause packet corruption and decoding errors.
|
|
43
43
|
Solution: Split into multiple layers or reduce order count.
|
|
44
|
-
Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0,Oc)),this.needsCommit=!0}getOrdersBreakdown(){let e=new Map;for(let t of this.orders){let n=t.type??"unknown";e.set(n,(e.get(n)??0)+1)}return Array.from(e.entries()).map(([t,n])=>`0x${t.toString(16)}:${n}`).join(", ")}getNeedsCommit(){return this.needsCommit}resetCommit(){this.needsCommit=!1}};J(rh,"Layer"),D(rh,"rasterizer",new Kx);var Zx=rh;function Aa(r,e){r.setIdInternal(e)}J(Aa,"assignLayerId");var qx=(r=>(r[r.CreateInstance=1]="CreateInstance",r[r.UpdateInstance=2]="UpdateInstance",r[r.RemoveInstance=3]="RemoveInstance",r))(qx||{}),Qx=(r=>(r[r.Click=1]="Click",r[r.Change=2]="Change",r[r.Submit=3]="Submit",r[r.Select=4]="Select",r))(Qx||{});function Jx(r){return r>=1&&r<=3}J(Jx,"isValidMacroOrderType");function eI(r){return r>=1&&r<=4}J(eI,"isValidMacroEventType");function tI(r){switch(r){case 1:return"CreateInstance";case 2:return"UpdateInstance";case 3:return"RemoveInstance";default:return`Unknown(0x${r.toString(16)})`}}J(tI,"getMacroOrderTypeName");function rI(r){switch(r){case 1:return"Click";case 2:return"Change";case 3:return"Submit";case 4:return"Select";default:return`Unknown(0x${r.toString(16)})`}}J(rI,"getMacroEventTypeName");var H1=class{constructor(){D(this,"macros",new Map),D(this,"macroNameToId",new Map),D(this,"nextMacroId",0),D(this,"instances",new Map),D(this,"instanceNameToId",new Map),D(this,"nextInstanceId",0),D(this,"layerNameToId",new Map),D(this,"pendingOrders",[])}registerMacro(e){let t=e.id;if(this.macroNameToId.has(t)){let s=this.macroNameToId.get(t);return this.macros.set(s,{macroId:s,name:t,template:e}),s}let n=this.nextMacroId++;if(n>255)throw new Error("Maximum macro count (256) exceeded");let i={macroId:n,name:t,template:e};return this.macros.set(n,i),this.macroNameToId.set(t,n),n}getMacroByName(e){let t=this.macroNameToId.get(e);return t!==void 0?this.macros.get(t):void 0}getMacroById(e){return this.macros.get(e)}getMacroId(e){return this.macroNameToId.get(e)}toMacroLoad(e){let t=this.macros.get(e);if(t)return{loadType:7,macroId:t.macroId,template:t.template}}toAllMacroLoads(){let e=[];for(let t of this.macros.values())e.push({loadType:7,macroId:t.macroId,template:t.template});return e}setLayerMapping(e,t){this.layerNameToId.set(e,t)}createInstance(e){let t=this.macroNameToId.get(e.macro);if(t===void 0){console.warn(`MacroRegistry: Unknown macro "${e.macro}"`);return}let n=this.layerNameToId.get(e.layer);if(n===void 0){console.warn(`MacroRegistry: Unknown layer "${e.layer}"`);return}if(this.instanceNameToId.has(e.id))return console.warn(`MacroRegistry: Instance "${e.id}" already exists`),this.instanceNameToId.get(e.id);let i=this.nextInstanceId++;if(i>255)throw new Error("Maximum instance count (256) exceeded");let s={instanceId:i,name:e.id,macroId:t,layerId:n,x:e.x,y:e.y,tabIndex:e.tabIndex??0,params:e.params??{}};this.instances.set(i,s),this.instanceNameToId.set(e.id,i);let o={type:1,instanceId:i,macroId:t,layerId:n,x:e.x,y:e.y,tabIndex:e.tabIndex??0,params:e.params??{}};return this.pendingOrders.push(o),i}updateInstance(e,t){let n=this.instanceNameToId.get(e);if(n===void 0)return!1;let i=this.instances.get(n);if(!i)return!1;for(let o in t)i.params[o]=t[o];let s={type:2,instanceId:n,params:t};return this.pendingOrders.push(s),!0}removeInstance(e){let t=this.instanceNameToId.get(e);if(t===void 0)return!1;this.instances.delete(t),this.instanceNameToId.delete(e);let n={type:3,instanceId:t};return this.pendingOrders.push(n),!0}getInstanceByName(e){let t=this.instanceNameToId.get(e);return t!==void 0?this.instances.get(t):void 0}getInstanceById(e){return this.instances.get(e)}getInstanceName(e){var t;return(t=this.instances.get(e))==null?void 0:t.name}flushPendingOrders(){let e=this.pendingOrders;return this.pendingOrders=[],e}hasPendingOrders(){return this.pendingOrders.length>0}getAllInstances(){return Array.from(this.instances.values())}clearInstances(){this.instances.clear(),this.instanceNameToId.clear(),this.nextInstanceId=0,this.pendingOrders=[]}clear(){this.macros.clear(),this.macroNameToId.clear(),this.nextMacroId=0,this.clearInstances()}};J(H1,"MacroRegistry");var nI=H1;function Ti(r){return typeof r=="number"?r:r.charCodeAt(0)}J(Ti,"toCharCode");function su(r){return typeof r=="string"?r.charAt(0):String.fromCharCode(r)}J(su,"toCharString");var iI=(r=>(r[r.Char=1]="Char",r[r.Text=2]="Text",r[r.TextMultiline=23]="TextMultiline",r[r.SubFrame=3]="SubFrame",r[r.SubFrameMultiColor=4]="SubFrameMultiColor",r[r.FullFrame=5]="FullFrame",r[r.FullFrameMultiColor=6]="FullFrameMultiColor",r[r.Sprite=7]="Sprite",r[r.SpriteMultiColor=8]="SpriteMultiColor",r[r.ColorMap=9]="ColorMap",r[r.Shape=10]="Shape",r[r.DotCloud=11]="DotCloud",r[r.DotCloudMultiColor=12]="DotCloudMultiColor",r[r.SpriteCloud=13]="SpriteCloud",r[r.SpriteCloudMultiColor=14]="SpriteCloudMultiColor",r[r.SpriteCloudVaried=15]="SpriteCloudVaried",r[r.SpriteCloudVariedMultiColor=16]="SpriteCloudVariedMultiColor",r[r.Bitmask=17]="Bitmask",r[r.Bitmask4=18]="Bitmask4",r[r.Bitmask16=24]="Bitmask16",r[r.Polyline=25]="Polyline",r[r.Fill=19]="Fill",r[r.FillChar=20]="FillChar",r[r.FillSprite=21]="FillSprite",r[r.FillSpriteMultiColor=22]="FillSpriteMultiColor",r))(iI||{});function sI(r){return r>=1&&r<=2||r>=3&&r<=6||r>=7&&r<=8||r>=9&&r<=10||r>=11&&r<=18||r>=19&&r<=23||r===24||r===25}J(sI,"isValidOrderType");function oI(r){switch(r){case 1:return"Char";case 2:return"Text";case 3:return"SubFrame";case 4:return"SubFrameMultiColor";case 5:return"FullFrame";case 6:return"FullFrameMultiColor";case 7:return"Sprite";case 8:return"SpriteMultiColor";case 9:return"ColorMap";case 10:return"Shape";case 11:return"DotCloud";case 12:return"DotCloudMultiColor";case 13:return"SpriteCloud";case 14:return"SpriteCloudMultiColor";case 15:return"SpriteCloudVaried";case 16:return"SpriteCloudVariedMultiColor";case 17:return"Bitmask";case 18:return"Bitmask4";case 24:return"Bitmask16";case 25:return"Polyline";case 19:return"Fill";case 20:return"FillChar";case 21:return"FillSprite";case 22:return"FillSpriteMultiColor";default:return`Unknown(0x${r.toString(16)})`}}J(oI,"getOrderTypeName");var aI={single:{topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",horizontal:"─",vertical:"│"},double:{topLeft:"╔",topRight:"╗",bottomLeft:"╚",bottomRight:"╝",horizontal:"═",vertical:"║"},rounded:{topLeft:"╭",topRight:"╮",bottomLeft:"╰",bottomRight:"╯",horizontal:"─",vertical:"│"}},Hg={update(r,e,t,n){var l,u,c,d;let i,s;e.subtype==="button"&&e.button?(i=t.resolveValue(e.button.width,r.params),s=t.resolveValue(e.button.height??3,r.params)):(i=t.resolveValue(r.params.width??1,r.params),s=t.resolveValue(r.params.height??1,r.params));let o=r.isHovered;r.isHovered=j1(t.mouseX,t.mouseY,r.x,r.y,i,s);let a=r.isActive;r.isActive=r.isHovered&&t.mouseDown,a&&!r.isActive&&r.isHovered&&(n.push({instanceId:r.instanceId,event:"click"}),e.subtype==="button"&&((l=e.button)==null?void 0:l.soundRelease)!==void 0&&((u=t.playSound)==null||u.call(t,e.button.soundRelease))),e.subtype==="button"&&e.button&&(!o&&r.isHovered&&e.button.soundHover!==void 0&&((c=t.playSound)==null||c.call(t,e.button.soundHover)),!a&&r.isActive&&e.button.soundClick!==void 0&&((d=t.playSound)==null||d.call(t,e.button.soundClick)))},render(r,e,t){let n=kf(r),i=e.states[n]??e.states.normal,s={...r.params,...i},o=[];if(e.subtype==="button"&&e.button)Y1(r,e,s,o,t);else if(e.base)for(let a of e.base){let l=X1(a,r.x,r.y,s,t);l&&o.push(l)}return o}};function j1(r,e,t,n,i,s){return r>=t&&r<t+i&&e>=n&&e<n+s}J(j1,"isPointInRect");function kf(r){return r.isDisabled?"disabled":r.isActive?"active":r.isHovered?"hover":r.isFocused?"focused":"normal"}J(kf,"getUIState");function As(r){if(typeof r=="number")return Math.max(0,Math.min(255,Math.floor(r)));if(typeof r=="string"){let e=parseInt(r,10);if(!isNaN(e))return Math.max(0,Math.min(255,Math.floor(e)))}return 243}J(As,"toColorIndex");function Y1(r,e,t,n,i){let s=e.button,o=kf(r),a=e.states[o]??e.states.normal,l=i.resolveValue(s.width,t),u=i.resolveValue(s.height??3,t),c=i.resolveValue(s.label,t),d=s.border??"single",h=i.resolveValue(a.fg??15,t),f=i.resolveValue(a.bg??0,t),p=i.resolveValue(a.textFg??h,t),m=a.offsetY??0,S=r.x,w=r.y+m;d==="none"?W1(S,w,l,u,c,h,f,p,n):G1(S,w,l,u,c,h,f,p,d,n)}J(Y1,"renderButton");function W1(r,e,t,n,i,s,o,a,l){if(n===1)l.push({type:2,posX:r,posY:e,text:" ".repeat(t),fgColorCode:s,bgColorCode:o});else for(let d=0;d<n;d++)l.push({type:2,posX:r,posY:e+d,text:" ".repeat(t),fgColorCode:s,bgColorCode:o});let u=r+Math.floor((t-i.length)/2),c=e+Math.floor(n/2);l.push({type:2,posX:u,posY:c,text:i,fgColorCode:a,bgColorCode:o})}J(W1,"renderButtonNoBorder");function G1(r,e,t,n,i,s,o,a,l,u){let c=aI[l];u.push({type:2,posX:r,posY:e,text:c.topLeft+c.horizontal.repeat(t-2)+c.topRight,fgColorCode:s,bgColorCode:o});for(let m=1;m<n-1;m++)u.push({type:2,posX:r,posY:e+m,text:c.vertical+" ".repeat(t-2)+c.vertical,fgColorCode:s,bgColorCode:o});u.push({type:2,posX:r,posY:e+n-1,text:c.bottomLeft+c.horizontal.repeat(t-2)+c.bottomRight,fgColorCode:s,bgColorCode:o});let d=t-2,h=n-2,f=r+1+Math.floor((d-i.length)/2),p=e+1+Math.floor(h/2);u.push({type:2,posX:f,posY:p,text:i,fgColorCode:a,bgColorCode:o})}J(G1,"renderButtonWithBorder");function X1(r,e,t,n,i){if(r.fillRect){let[s,o,a,l,u,c,d]=r.fillRect;return{type:3,posX:e+i.resolveValue(s,n),posY:t+i.resolveValue(o,n),sizeX:i.resolveValue(a,n),sizeY:i.resolveValue(l,n),fgColorCode:As(i.resolveValue(c,n)),bgColorCode:As(i.resolveValue(d,n)),frame:Array(i.resolveValue(a,n)*i.resolveValue(l,n)).fill(Ti(u))}}if(r.text){let[s,o,a,l]=r.text;return{type:2,posX:e+i.resolveValue(s,n),posY:t+i.resolveValue(o,n),text:i.resolveValue(a,n),fgColorCode:As(i.resolveValue(l,n)),bgColorCode:255}}if(r.setCell){let[s,o,a,l,u]=r.setCell;return{type:1,posX:e+i.resolveValue(s,n),posY:t+i.resolveValue(o,n),charCode:Ti(i.resolveValue(a,n)),fgColorCode:As(i.resolveValue(l,n)),bgColorCode:As(i.resolveValue(u,n))}}return null}J(X1,"executeRenderCommand");function K1(r,e,t,n,i,s,o){return{type:"ui",instanceId:r,macroId:e,layerId:t,x:n,y:i,params:s,tabIndex:o,isHovered:!1,isFocused:!1,isActive:!1,isDisabled:!1}}J(K1,"createUIInstance");var Z1=class{update(e,t,n,i){let s=t.emitter,{resolveValue:o}=n;if(!e.emitDone){if(s.burst){let a=o(s.burst,e.params);for(let l=0;l<a&&!(s.limit&&e.particles.length>=s.limit);l++)e.particles.push(this.createParticle(e,t,n));s.once&&(e.emitDone=!0)}else if(s.rate){let a=o(s.rate,e.params);for(e.timeSinceEmit+=a;e.timeSinceEmit>=1&&!(s.limit&&e.particles.length>=s.limit);)e.particles.push(this.createParticle(e,t,n)),e.timeSinceEmit-=1}}for(let a=e.particles.length-1;a>=0;a--){let l=e.particles[a];l.x+=l.vx,l.y+=l.vy,l.lifetime-=1,l.lifetime<=0&&e.particles.splice(a,1)}}render(e,t,n){if(e.particles.length===0)return[];let{resolveValue:i}=n,s=t.emitter,o=s.viewport??s.zone,a=i(o.x,e.params),l=i(o.y,e.params),u=i(o.width,e.params),c=i(o.height,e.params),d=e.x+(typeof a=="number"?a:0),h=e.y+(typeof l=="number"?l:0),f=typeof u=="number"?u:0,p=typeof c=="number"?c:0;if(f<=0||p<=0)return[];let m=[];for(let S of e.particles){let w=Math.floor(S.x),g=Math.floor(S.y);if(w<d||w>=d+f||g<h||g>=h+p)continue;let y=S.fg;if(t.particle.fade&&S.maxLifetime>0){let C=S.lifetime/S.maxLifetime;y=this.fadeColorIndex(S.fg,C)}m.push({charCode:Ti(S.char),fgColorCode:y,bgColorCode:S.bg??255,posX:w,posY:g})}return[{type:12,dots:m}]}createParticle(e,t,n){let{resolveValue:i,resolveRandomValue:s}=n,o=t.emitter,a=t.particle,l=i(o.zone.x,e.params),u=i(o.zone.y,e.params),c=i(o.zone.width,e.params),d=i(o.zone.height,e.params),h=e.x+l+Math.random()*c,f=e.y+u+Math.random()*d,p=0,m=0;if("x"in a.velocity&&"y"in a.velocity)p=i(a.velocity.x,e.params),m=i(a.velocity.y,e.params);else if("angle"in a.velocity&&"speed"in a.velocity){let E=s(a.velocity.angle),A=s(a.velocity.speed,e.params),R=E*Math.PI/180;p=Math.cos(R)*A,m=Math.sin(R)*A}let S=s(a.lifetime),w=Array.isArray(a.char)?a.char[Math.floor(Math.random()*a.char.length)]:a.char,g=su(w),y=Array.isArray(a.fg)?a.fg[Math.floor(Math.random()*a.fg.length)]:a.fg,C=typeof y=="number"?y:parseInt(y,10)||243,x=a.bg?Array.isArray(a.bg)?a.bg[Math.floor(Math.random()*a.bg.length)]:a.bg:void 0,I=x!==void 0?typeof x=="number"?x:parseInt(x,10)||255:void 0;return{x:h,y:f,vx:p,vy:m,char:g,fg:C,bg:I,lifetime:S,maxLifetime:S}}fadeColorIndex(e,t){return t<.1?255:e}};J(Z1,"ParticleHandler");var lI=Z1,q1=class{update(e,t,n,i){e.elapsed+=1;let s=Math.min(1,e.elapsed/e.duration),o=t.transform.decay?1-s:1,a=t.transform.offset;a&&(e.currentOffsetX=this.resolveRandomOffset(a.x,e.params,n)*o,e.currentOffsetY=this.resolveRandomOffset(a.y,e.params,n)*o),e.elapsed>=e.duration&&(i.push({instanceId:e.instanceId,event:"complete"}),n.deleteInstance(e.instanceId))}render(e,t,n){return[]}getOffset(e){return{x:e.currentOffsetX,y:e.currentOffsetY}}resolveRandomOffset(e,t,n){if(typeof e=="number")return e;if(typeof e=="string")return n.resolveValue(e,t);if(typeof e=="object"&&"random"in e){let[i,s]=e.random,o=n.resolveValue(i,t),a=n.resolveValue(s,t);return o+Math.random()*(a-o)}return 0}};J(q1,"EffectHandler");var uI=q1,Q1=class{constructor(){D(this,"spriteRegistry",null)}setSpriteRegistry(e){this.spriteRegistry=e}update(e,t,n,i){var a;if(e.finished)return;if(e.delayRemaining>0){e.delayRemaining--;return}if(e.pauseRemaining>0){e.pauseRemaining--;return}let s=((a=t.cursor)==null?void 0:a.blinkRate)??15;e.blinkTimer++,e.blinkTimer>=s&&(e.blinkTimer=0,e.blinkState=!e.blinkState);let o=e.speed;if(e.direction==="reveal"){let l=Math.min(o,e.totalCells-e.revealedCount);if(t.pauseOn&&l>0){let u=e.cells[e.revealedCount];u&&t.pauseOn.chars.includes(u.char)&&(e.pauseRemaining=t.pauseOn.duration)}e.revealedCount+=l,e.revealedCount>=e.totalCells&&(e.finished=!0,i.push({instanceId:e.instanceId,event:"complete"}))}else{let l=Math.min(o,e.revealedCount);e.revealedCount-=l,e.revealedCount<=0&&(e.finished=!0,i.push({instanceId:e.instanceId,event:"complete"}))}}render(e,t,n){let i=[],s=e.cells.slice(0,e.revealedCount),o=new Map;for(let a of s)o.has(a.y)||o.set(a.y,[]),o.get(a.y).push(a);for(let[a,l]of o){l.sort((c,d)=>c.x-d.x);let u=0;for(;u<l.length;){let c=l[u],d=u+1;for(;d<l.length&&l[d].x===l[d-1].x+1&&l[d].fg===c.fg&&l[d].bg===c.bg;)d++;if(d-u===1)i.push({type:1,posX:e.x+c.x,posY:e.y+a,charCode:c.char.charCodeAt(0),fgColorCode:c.fg,bgColorCode:c.bg});else{let h="";for(let f=u;f<d;f++)h+=l[f].char;i.push({type:2,posX:e.x+c.x,posY:e.y+a,text:h,fgColorCode:c.fg,bgColorCode:c.bg})}u=d}}if(t.cursor&&!e.finished&&(!t.cursor.blink||e.blinkState)&&e.revealedCount<e.cells.length){let a=e.cells[e.revealedCount];if(a){let l=t.cursor.bg??a.bg;i.push({type:1,posX:e.x+a.x,posY:e.y+a.y,charCode:Ti(t.cursor.char),fgColorCode:t.cursor.fg??15,bgColorCode:l})}}return i}buildCells(e,t,n){let i=[],s=e.content;switch(s.type){case"text":{let o=n(s.text,t),a=n(s.fg??15,t),l=n(s.bg??0,t),u=o.split(`
|
|
45
|
-
`);for(let c=0;c<u.length;c++){let d=u[c];for(let h=0;h<d.length;h++)i.push({char:d[h],fg:a,bg:l,x:h,y:c,revealOrder:0})}break}case"sprite":{if(!this.spriteRegistry)break;let o=n(s.sprite,t);if(s.multicolor!==!1){let l=this.spriteRegistry.getMulticolorSprite(o);if(l){let{sizeX:u,sizeY:c,data:d}=l;for(let h=0;h<c;h++)for(let f=0;f<u;f++){let p=h*u+f,m=d.get(p);m.charCode!==0&&i.push({char:String.fromCharCode(m.charCode),fg:m.fgColorCode,bg:m.bgColorCode,x:f,y:h,revealOrder:0})}break}}let a=this.spriteRegistry.getUnicolorSprite(o);if(a){let{sizeX:l,sizeY:u,data:c}=a,d=n(s.fg??15,t),h=n(s.bg??0,t);for(let f=0;f<u;f++)for(let p=0;p<l;p++){let m=f*l+p,S=c.get(m);S!==0&&i.push({char:String.fromCharCode(S),fg:d,bg:h,x:p,y:f,revealOrder:0})}}break}case"cells":{for(let o of s.cells)i.push({char:su(o.char),fg:o.fg,bg:o.bg,x:o.x,y:o.y,revealOrder:0});break}case"fill":{let o=su(s.char),a=n(s.fg,t),l=n(s.bg,t),u=n(s.width,t),c=n(s.height,t);for(let d=0;d<c;d++)for(let h=0;h<u;h++)i.push({char:o,fg:a,bg:l,x:h,y:d,revealOrder:0});break}}return this.assignRevealOrder(i,e.pattern,e.direction),i}assignRevealOrder(e,t,n){if(e.length===0)return;let i=0,s=0;for(let l of e)l.x>i&&(i=l.x),l.y>s&&(s=l.y);let o=i+1,a=s+1;switch(t){case"typewriter":for(let l of e)l.revealOrder=l.y*o+l.x;break;case"typewriter-rev":for(let l of e)l.revealOrder=(a-1-l.y)*o+(o-1-l.x);break;case"ltr":for(let l of e)l.revealOrder=l.x*a+l.y;break;case"rtl":for(let l of e)l.revealOrder=(o-1-l.x)*a+l.y;break;case"ttb":for(let l of e)l.revealOrder=l.y;break;case"btt":for(let l of e)l.revealOrder=a-1-l.y;break;case"random":{let l=e.map((u,c)=>c);for(let u=l.length-1;u>0;u--){let c=Math.floor(Math.random()*(u+1));[l[u],l[c]]=[l[c],l[u]]}for(let u=0;u<e.length;u++)e[u].revealOrder=l[u];break}case"center-out":{let l=(o-1)/2,u=(a-1)/2;for(let c of e)c.revealOrder=Math.abs(c.x-l)+Math.abs(c.y-u);break}case"spiral":{let l=(o-1)/2,u=(a-1)/2,c=Math.max(l,u);for(let d of e){let h=Math.abs(d.x-l),f=Math.abs(d.y-u),p=Math.max(h,f);d.revealOrder=c-p+(d.y*o+d.x)*.001}break}}e.sort((l,u)=>l.revealOrder-u.revealOrder);for(let l=0;l<e.length;l++)e[l].revealOrder=l}};J(Q1,"RevealHandler");var cI=Q1,J1=class{update(e,t,n,i){let{resolveValue:s}=n,o=e.params;e.currentTick++;let a=o.point;if(a&&typeof a.x=="number"&&typeof a.y=="number"){e.points.push({x:a.x,y:a.y,addedAt:e.currentTick}),delete o.point;let u=s(t.maxPoints,o)??100;for(;e.points.length>u;)e.points.shift()}o.clear===!0&&(e.points=[],delete o.clear);let l=o.points;if(Array.isArray(l)){e.points=l.map(c=>({x:c.x,y:c.y,addedAt:e.currentTick})),delete o.points;let u=s(t.maxPoints,o)??100;for(;e.points.length>u;)e.points.shift()}}render(e,t,n){let{resolveValue:i}=n,s=e.params,o=e.points;if(o.length===0)return[];let a=i(t.char,s),l=i(t.fg,s)??15,u=i(t.bg,s)??255,c=t.closed??!1,d=t.fadeOut??!1,h=o.map(f=>({x:e.x+f.x,y:e.y+f.y}));return c&&h.length>=2&&h.push({...h[0]}),d&&o.length>=2?this.renderFadedLine(e,t,n,h,a,l,u):[{type:25,charCode:Ti(a),fgColorCode:l,bgColorCode:u,points:h.map(f=>({x:f.x&255,y:f.y&255}))}]}renderFadedLine(e,t,n,i,s,o,a){e.params;let l=t.fadeLength??i.length,u=[],c=i.length,d=Math.max(0,c-l);if(d>0){let f=i.slice(0,d+1);f.length>=2&&u.push({type:25,charCode:Ti(s),fgColorCode:o,bgColorCode:a,points:f.map(p=>({x:p.x&255,y:p.y&255}))})}let h=i.slice(d);if(h.length>=2){let f=Math.max(0,o-8);u.push({type:25,charCode:Ti(s),fgColorCode:f,bgColorCode:a,points:h.map(p=>({x:p.x&255,y:p.y&255}))})}return u}};J(J1,"LineHandler");var dI=J1;function Ki(...r){}J(Ki,"macroLog");var ev=class{constructor(){D(this,"templates",new Map),D(this,"instances",new Map),D(this,"spriteRegistry",null),D(this,"playSound",null),D(this,"focusedInstanceId",null),D(this,"focusableInstances",[]),D(this,"mouseX",0),D(this,"mouseY",0),D(this,"mouseDown",!1),D(this,"particleHandler",new lI),D(this,"effectHandler",new uI),D(this,"revealHandler",new cI),D(this,"lineHandler",new dI),D(this,"instancesToDelete",[])}setSpriteRegistry(e){this.spriteRegistry=e,this.revealHandler.setSpriteRegistry(e)}setAudioCallback(e){this.playSound=e}createContext(){return{mouseX:this.mouseX,mouseY:this.mouseY,mouseDown:this.mouseDown,playSound:this.playSound??void 0,getTemplate:e=>this.getTemplate(e),resolveValue:(e,t)=>this.resolveValue(e,t),resolveRandomValue:(e,t)=>this.resolveRandomValue(e,t),deleteInstance:e=>{this.instancesToDelete.push(e)}}}loadTemplate(e,t){Ki(`loadTemplate: macroId=${e}, type=${t.type}`),this.templates.set(e,{macroId:e,template:t})}getTemplate(e){var t;return(t=this.templates.get(e))==null?void 0:t.template}hasTemplate(e){return this.templates.has(e)}applyOrder(e){switch(Ki(`applyOrder: type=${e.type}, instanceId=${e.instanceId}`),e.type){case 1:this.createInstance(e);break;case 2:this.updateInstance(e);break;case 3:this.removeInstance(e);break}}createInstance(e){let t=this.getTemplate(e.macroId);if(!t){Ki(`createInstance: FAILED - template ${e.macroId} not found`);return}Ki(`createInstance: id=${e.instanceId}, macroId=${e.macroId}, type=${t.type}, pos=(${e.x}, ${e.y}), layer=${e.layerId}`);let n;switch(t.type){case"ui":n=K1(e.instanceId,e.macroId,e.layerId,e.x,e.y,e.params,e.tabIndex),e.tabIndex>0&&this.addToFocusableList(e.instanceId,e.tabIndex);break;case"particle":n={type:"particle",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,particles:[],timeSinceEmit:0,emitDone:!1};break;case"effect":{let i=t;n={type:"effect",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,elapsed:0,duration:this.resolveValue(i.transform.duration,e.params),currentOffsetX:0,currentOffsetY:0};break}case"reveal":{let i=t,s=this.revealHandler.buildCells(i,e.params,(l,u)=>this.resolveValue(l,u)),o=s.length,a=i.direction??"reveal";n={type:"reveal",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,cells:s,revealedCount:a==="hide"?o:0,totalCells:o,delayRemaining:i.delay??0,pauseRemaining:0,finished:!1,direction:a,speed:i.speed??1,blinkState:!0,blinkTimer:0};break}case"line":{let i=[],s=e.params.points;if(Array.isArray(s)){for(let a of s)i.push({x:a.x,y:a.y,addedAt:0});delete e.params.points}let o=e.params.point;o&&typeof o.x=="number"&&typeof o.y=="number"&&(i.push({x:o.x,y:o.y,addedAt:0}),delete e.params.point),n={type:"line",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,points:i,currentTick:0};break}default:return}n&&this.instances.set(e.instanceId,n)}updateInstance(e){let t=this.instances.get(e.instanceId);if(t)for(let n in e.params)t.params[n]=e.params[n]}removeInstance(e){let t=this.instances.get(e.instanceId);t&&(t.type==="ui"&&(this.removeFromFocusableList(e.instanceId),this.focusedInstanceId===e.instanceId&&(this.focusedInstanceId=null)),this.instances.delete(e.instanceId))}addToFocusableList(e,t){this.focusableInstances.push(e),this.focusableInstances.sort((n,i)=>{let s=this.instances.get(n),o=this.instances.get(i);return((s==null?void 0:s.tabIndex)??0)-((o==null?void 0:o.tabIndex)??0)})}removeFromFocusableList(e){let t=this.focusableInstances.indexOf(e);t!==-1&&this.focusableInstances.splice(t,1)}focusNext(){if(this.focusableInstances.length===0)return;let e=((this.focusedInstanceId!==null?this.focusableInstances.indexOf(this.focusedInstanceId):-1)+1)%this.focusableInstances.length;this.setFocus(this.focusableInstances[e])}focusPrevious(){if(this.focusableInstances.length===0)return;let e=((this.focusedInstanceId!==null?this.focusableInstances.indexOf(this.focusedInstanceId):0)-1+this.focusableInstances.length)%this.focusableInstances.length;this.setFocus(this.focusableInstances[e])}setFocus(e){if(this.focusedInstanceId!==null){let t=this.instances.get(this.focusedInstanceId);(t==null?void 0:t.type)==="ui"&&(t.isFocused=!1)}if(this.focusedInstanceId=e,e!==null){let t=this.instances.get(e);(t==null?void 0:t.type)==="ui"&&(t.isFocused=!0)}}updateMouse(e,t,n){this.mouseX=e,this.mouseY=t,this.mouseDown=n}estimateUISize(e,t){if(e.subtype==="button"&&e.button){let s=this.resolveValue(e.button.width,t??{}),o=this.resolveValue(e.button.height??3,t??{});return{width:s,height:o}}let n=1,i=1;if(e.base)for(let s of e.base)"w"in s&&typeof s.w=="number"&&(n=Math.max(n,s.w)),"h"in s&&typeof s.h=="number"&&(i=Math.max(i,s.h));return{width:n,height:i}}activateFocused(){if(this.focusedInstanceId===null)return;let e=this.instances.get(this.focusedInstanceId);(e==null?void 0:e.type)==="ui"&&(e.isActive=!0)}update(){let e=[];this.instances.size>0&&Ki(`update: instances=${this.instances.size}, templates=${this.templates.size}`);let t=this.createContext();this.instancesToDelete=[];for(let n of this.instances.values()){let i=this.getTemplate(n.macroId);if(i)switch(n.type){case"ui":Hg.update(n,i,t,e);break;case"particle":this.particleHandler.update(n,i,t,e);break;case"effect":this.effectHandler.update(n,i,t,e);break;case"reveal":this.revealHandler.update(n,i,t,e);break;case"line":this.lineHandler.update(n,i,t,e);break}}for(let n of this.instancesToDelete)this.instances.delete(n);return{events:e.map(n=>({instanceId:n.instanceId,event:n.event,data:n.data}))}}getOrdersByLayer(){let e=new Map;for(let t of this.instances.values()){let n=this.renderInstance(t);n.length!==0&&(e.has(t.layerId)||e.set(t.layerId,[]),e.get(t.layerId).push(...n))}if(e.size>0){let t=0;for(let n of e.values())t+=n.length;Ki(`getOrdersByLayer: ${e.size} layers, ${t} total orders`)}return e}renderInstance(e){let t=this.getTemplate(e.macroId);if(!t)return[];let n=this.createContext();switch(e.type){case"ui":return Hg.render(e,t,n);case"particle":return this.particleHandler.render(e,t,n);case"effect":return this.effectHandler.render(e,t,n);case"reveal":return this.revealHandler.render(e,t,n);case"line":return this.lineHandler.render(e,t,n);default:return[]}}resolveValue(e,t){if(typeof e=="string"&&e.startsWith("$")){let n=e.slice(1);return t[n]??e}return e}resolveRandomValue(e,t){if(typeof e=="string"){let n=this.resolveValue(e,t??{});return typeof n=="number"?n:0}if(Array.isArray(e)){let[n,i]=e;return n+Math.random()*(i-n)}return e}getEffectOffset(){let e=0,t=0;for(let n of this.instances.values())n.type==="effect"&&(e+=n.currentOffsetX,t+=n.currentOffsetY);return{x:e,y:t}}getAllInstances(){return Array.from(this.instances.values())}getInstanceCount(){return this.instances.size}clear(){this.templates.clear(),this.instances.clear(),this.focusedInstanceId=null,this.focusableInstances=[]}};J(ev,"MacroEngine");var hI=ev,tv=class{constructor(){D(this,"axes",new Map),D(this,"buttons",new Map),D(this,"touchZones",new Map),D(this,"axisNameToId",new Map),D(this,"buttonNameToId",new Map),D(this,"touchZoneNameToId",new Map),D(this,"version",1)}defineAxis(e,t,n=[],i=-1,s=1,o=0){if(e<0||e>255)throw new Error(`Axis bindingId must be between 0 and 255, got ${e}`);if(this.axes.has(e))throw new Error(`Axis bindingId ${e} is already defined`);if(this.axisNameToId.has(t)){let l=this.axisNameToId.get(t);throw new Error(`Axis name "${t}" is already defined with bindingId ${l}`)}let a={bindingId:e,name:t,min:i,max:s,defaultValue:o,sources:n};this.axes.set(e,a),this.axisNameToId.set(t,e),this.version++}defineButton(e,t,n=[],i=!1){if(e<0||e>255)throw new Error(`Button bindingId must be between 0 and 255, got ${e}`);if(this.buttons.has(e))throw new Error(`Button bindingId ${e} is already defined`);if(this.buttonNameToId.has(t)){let o=this.buttonNameToId.get(t);throw new Error(`Button name "${t}" is already defined with bindingId ${o}`)}let s={bindingId:e,name:t,defaultValue:i,sources:n};this.buttons.set(e,s),this.buttonNameToId.set(t,e),this.version++}defineTouchZone(e,t,n,i,s,o){if(e<0||e>31)throw new Error(`Touch zone zoneId must be between 0 and 31, got ${e}`);if(this.touchZones.has(e))throw new Error(`Touch zone zoneId ${e} is already defined`);if(this.touchZoneNameToId.has(t)){let l=this.touchZoneNameToId.get(t);throw new Error(`Touch zone name "${t}" is already defined with zoneId ${l}`)}if(s<=0||o<=0)throw new Error(`Touch zone dimensions must be positive, got ${s}x${o}`);let a={zoneId:e,name:t,x:n,y:i,width:s,height:o};this.touchZones.set(e,a),this.touchZoneNameToId.set(t,e),this.version++}evaluateAxis(e,t){let n=this.axes.get(e);if(!n)return 0;let i=0;for(let s of n.sources){let o=t.get(s.sourceId)??0,a=s.deadzone??0;Math.abs(o)<a?o=0:o=(o>0?1:-1)*((Math.abs(o)-a)/(1-a));let l=s.scale??1;o*=l;let u=s.sensitivity??1;o*=u,s.invert&&(o=-o),i+=o}return Math.max(n.min,Math.min(n.max,i))}evaluateButton(e,t){let n=this.buttons.get(e);if(!n)return!1;for(let i of n.sources)if(t.get(i.sourceId)??!1)return!0;return!1}toLoadPacket(){let e={type:"input-binding",version:this.version,axes:Array.from(this.axes.values()),buttons:Array.from(this.buttons.values()),touchZones:this.touchZones.size>0?Array.from(this.touchZones.values()):void 0};return JSON.stringify(e)}toLoadPacketObject(){return{type:"input-binding",version:this.version,axes:Array.from(this.axes.values()),buttons:Array.from(this.buttons.values()),touchZones:this.touchZones.size>0?Array.from(this.touchZones.values()):void 0}}getAxisBindingId(e){return this.axisNameToId.get(e)??null}getButtonBindingId(e){return this.buttonNameToId.get(e)??null}getAxisName(e){var t;return((t=this.axes.get(e))==null?void 0:t.name)??null}getButtonName(e){var t;return((t=this.buttons.get(e))==null?void 0:t.name)??null}getAxisBinding(e){return this.axes.get(e)??null}getButtonBinding(e){return this.buttons.get(e)??null}hasAxis(e){return this.axes.has(e)}hasButton(e){return this.buttons.has(e)}hasTouchZone(e){return this.touchZones.has(e)}getAxisCount(){return this.axes.size}getButtonCount(){return this.buttons.size}getTouchZoneCount(){return this.touchZones.size}getAllAxes(){return Array.from(this.axes.values())}getAllButtons(){return Array.from(this.buttons.values())}getAllTouchZones(){return Array.from(this.touchZones.values())}getTouchZone(e){return this.touchZones.get(e)??null}getTouchZoneId(e){return this.touchZoneNameToId.get(e)??null}getVersion(){return this.version}removeAxis(e){let t=this.axes.get(e);return t?(this.axes.delete(e),this.axisNameToId.delete(t.name),this.version++,!0):!1}removeButton(e){let t=this.buttons.get(e);return t?(this.buttons.delete(e),this.buttonNameToId.delete(t.name),this.version++,!0):!1}removeTouchZone(e){let t=this.touchZones.get(e);return t?(this.touchZones.delete(e),this.touchZoneNameToId.delete(t.name),this.version++,!0):!1}clearAxes(){this.axes.clear(),this.axisNameToId.clear(),this.version++}clearButtons(){this.buttons.clear(),this.buttonNameToId.clear(),this.version++}clearTouchZones(){this.touchZones.clear(),this.touchZoneNameToId.clear(),this.version++}clear(){this.axes.clear(),this.axisNameToId.clear(),this.buttons.clear(),this.buttonNameToId.clear(),this.touchZones.clear(),this.touchZoneNameToId.clear(),this.version=1}toString(){let e=`InputBindingRegistry (version ${this.version})
|
|
44
|
+
Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0,Dc)),this.needsCommit=!0}getOrdersBreakdown(){let e=new Map;for(let t of this.orders){let n=t.type??"unknown";e.set(n,(e.get(n)??0)+1)}return Array.from(e.entries()).map(([t,n])=>`0x${t.toString(16)}:${n}`).join(", ")}getNeedsCommit(){return this.needsCommit}resetCommit(){this.needsCommit=!1}};J(rh,"Layer"),O(rh,"rasterizer",new Kx);var Zx=rh;function Aa(r,e){r.setIdInternal(e)}J(Aa,"assignLayerId");var qx=(r=>(r[r.CreateInstance=1]="CreateInstance",r[r.UpdateInstance=2]="UpdateInstance",r[r.RemoveInstance=3]="RemoveInstance",r))(qx||{}),Qx=(r=>(r[r.Click=1]="Click",r[r.Change=2]="Change",r[r.Submit=3]="Submit",r[r.Select=4]="Select",r))(Qx||{});function Jx(r){return r>=1&&r<=3}J(Jx,"isValidMacroOrderType");function eI(r){return r>=1&&r<=4}J(eI,"isValidMacroEventType");function tI(r){switch(r){case 1:return"CreateInstance";case 2:return"UpdateInstance";case 3:return"RemoveInstance";default:return`Unknown(0x${r.toString(16)})`}}J(tI,"getMacroOrderTypeName");function rI(r){switch(r){case 1:return"Click";case 2:return"Change";case 3:return"Submit";case 4:return"Select";default:return`Unknown(0x${r.toString(16)})`}}J(rI,"getMacroEventTypeName");var H1=class{constructor(){O(this,"macros",new Map),O(this,"macroNameToId",new Map),O(this,"nextMacroId",0),O(this,"instances",new Map),O(this,"instanceNameToId",new Map),O(this,"nextInstanceId",0),O(this,"layerNameToId",new Map),O(this,"pendingOrders",[])}registerMacro(e){let t=e.id;if(this.macroNameToId.has(t)){let s=this.macroNameToId.get(t);return this.macros.set(s,{macroId:s,name:t,template:e}),s}let n=this.nextMacroId++;if(n>255)throw new Error("Maximum macro count (256) exceeded");let i={macroId:n,name:t,template:e};return this.macros.set(n,i),this.macroNameToId.set(t,n),n}getMacroByName(e){let t=this.macroNameToId.get(e);return t!==void 0?this.macros.get(t):void 0}getMacroById(e){return this.macros.get(e)}getMacroId(e){return this.macroNameToId.get(e)}toMacroLoad(e){let t=this.macros.get(e);if(t)return{loadType:7,macroId:t.macroId,template:t.template}}toAllMacroLoads(){let e=[];for(let t of this.macros.values())e.push({loadType:7,macroId:t.macroId,template:t.template});return e}setLayerMapping(e,t){this.layerNameToId.set(e,t)}createInstance(e){let t=this.macroNameToId.get(e.macro);if(t===void 0){console.warn(`MacroRegistry: Unknown macro "${e.macro}"`);return}let n=this.layerNameToId.get(e.layer);if(n===void 0){console.warn(`MacroRegistry: Unknown layer "${e.layer}"`);return}if(this.instanceNameToId.has(e.id))return console.warn(`MacroRegistry: Instance "${e.id}" already exists`),this.instanceNameToId.get(e.id);let i=this.nextInstanceId++;if(i>255)throw new Error("Maximum instance count (256) exceeded");let s={instanceId:i,name:e.id,macroId:t,layerId:n,x:e.x,y:e.y,tabIndex:e.tabIndex??0,params:e.params??{}};this.instances.set(i,s),this.instanceNameToId.set(e.id,i);let o={type:1,instanceId:i,macroId:t,layerId:n,x:e.x,y:e.y,tabIndex:e.tabIndex??0,params:e.params??{}};return this.pendingOrders.push(o),i}updateInstance(e,t){let n=this.instanceNameToId.get(e);if(n===void 0)return!1;let i=this.instances.get(n);if(!i)return!1;for(let o in t)i.params[o]=t[o];let s={type:2,instanceId:n,params:t};return this.pendingOrders.push(s),!0}removeInstance(e){let t=this.instanceNameToId.get(e);if(t===void 0)return!1;this.instances.delete(t),this.instanceNameToId.delete(e);let n={type:3,instanceId:t};return this.pendingOrders.push(n),!0}getInstanceByName(e){let t=this.instanceNameToId.get(e);return t!==void 0?this.instances.get(t):void 0}getInstanceById(e){return this.instances.get(e)}getInstanceName(e){var t;return(t=this.instances.get(e))==null?void 0:t.name}flushPendingOrders(){let e=this.pendingOrders;return this.pendingOrders=[],e}hasPendingOrders(){return this.pendingOrders.length>0}getAllInstances(){return Array.from(this.instances.values())}clearInstances(){this.instances.clear(),this.instanceNameToId.clear(),this.nextInstanceId=0,this.pendingOrders=[]}clear(){this.macros.clear(),this.macroNameToId.clear(),this.nextMacroId=0,this.clearInstances()}};J(H1,"MacroRegistry");var nI=H1;function Ti(r){return typeof r=="number"?r:r.charCodeAt(0)}J(Ti,"toCharCode");function su(r){return typeof r=="string"?r.charAt(0):String.fromCharCode(r)}J(su,"toCharString");var iI=(r=>(r[r.Char=1]="Char",r[r.Text=2]="Text",r[r.TextMultiline=23]="TextMultiline",r[r.SubFrame=3]="SubFrame",r[r.SubFrameMultiColor=4]="SubFrameMultiColor",r[r.FullFrame=5]="FullFrame",r[r.FullFrameMultiColor=6]="FullFrameMultiColor",r[r.Sprite=7]="Sprite",r[r.SpriteMultiColor=8]="SpriteMultiColor",r[r.ColorMap=9]="ColorMap",r[r.Shape=10]="Shape",r[r.DotCloud=11]="DotCloud",r[r.DotCloudMultiColor=12]="DotCloudMultiColor",r[r.SpriteCloud=13]="SpriteCloud",r[r.SpriteCloudMultiColor=14]="SpriteCloudMultiColor",r[r.SpriteCloudVaried=15]="SpriteCloudVaried",r[r.SpriteCloudVariedMultiColor=16]="SpriteCloudVariedMultiColor",r[r.Bitmask=17]="Bitmask",r[r.Bitmask4=18]="Bitmask4",r[r.Bitmask16=24]="Bitmask16",r[r.Polyline=25]="Polyline",r[r.Fill=19]="Fill",r[r.FillChar=20]="FillChar",r[r.FillSprite=21]="FillSprite",r[r.FillSpriteMultiColor=22]="FillSpriteMultiColor",r))(iI||{});function sI(r){return r>=1&&r<=2||r>=3&&r<=6||r>=7&&r<=8||r>=9&&r<=10||r>=11&&r<=18||r>=19&&r<=23||r===24||r===25}J(sI,"isValidOrderType");function oI(r){switch(r){case 1:return"Char";case 2:return"Text";case 3:return"SubFrame";case 4:return"SubFrameMultiColor";case 5:return"FullFrame";case 6:return"FullFrameMultiColor";case 7:return"Sprite";case 8:return"SpriteMultiColor";case 9:return"ColorMap";case 10:return"Shape";case 11:return"DotCloud";case 12:return"DotCloudMultiColor";case 13:return"SpriteCloud";case 14:return"SpriteCloudMultiColor";case 15:return"SpriteCloudVaried";case 16:return"SpriteCloudVariedMultiColor";case 17:return"Bitmask";case 18:return"Bitmask4";case 24:return"Bitmask16";case 25:return"Polyline";case 19:return"Fill";case 20:return"FillChar";case 21:return"FillSprite";case 22:return"FillSpriteMultiColor";default:return`Unknown(0x${r.toString(16)})`}}J(oI,"getOrderTypeName");var aI={single:{topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",horizontal:"─",vertical:"│"},double:{topLeft:"╔",topRight:"╗",bottomLeft:"╚",bottomRight:"╝",horizontal:"═",vertical:"║"},rounded:{topLeft:"╭",topRight:"╮",bottomLeft:"╰",bottomRight:"╯",horizontal:"─",vertical:"│"}},Hg={update(r,e,t,n){var l,u,c,d;let i,s;e.subtype==="button"&&e.button?(i=t.resolveValue(e.button.width,r.params),s=t.resolveValue(e.button.height??3,r.params)):(i=t.resolveValue(r.params.width??1,r.params),s=t.resolveValue(r.params.height??1,r.params));let o=r.isHovered;r.isHovered=j1(t.mouseX,t.mouseY,r.x,r.y,i,s);let a=r.isActive;r.isActive=r.isHovered&&t.mouseDown,a&&!r.isActive&&r.isHovered&&(n.push({instanceId:r.instanceId,event:"click"}),e.subtype==="button"&&((l=e.button)==null?void 0:l.soundRelease)!==void 0&&((u=t.playSound)==null||u.call(t,e.button.soundRelease))),e.subtype==="button"&&e.button&&(!o&&r.isHovered&&e.button.soundHover!==void 0&&((c=t.playSound)==null||c.call(t,e.button.soundHover)),!a&&r.isActive&&e.button.soundClick!==void 0&&((d=t.playSound)==null||d.call(t,e.button.soundClick)))},render(r,e,t){let n=kf(r),i=e.states[n]??e.states.normal,s={...r.params,...i},o=[];if(e.subtype==="button"&&e.button)Y1(r,e,s,o,t);else if(e.base)for(let a of e.base){let l=X1(a,r.x,r.y,s,t);l&&o.push(l)}return o}};function j1(r,e,t,n,i,s){return r>=t&&r<t+i&&e>=n&&e<n+s}J(j1,"isPointInRect");function kf(r){return r.isDisabled?"disabled":r.isActive?"active":r.isHovered?"hover":r.isFocused?"focused":"normal"}J(kf,"getUIState");function As(r){if(typeof r=="number")return Math.max(0,Math.min(255,Math.floor(r)));if(typeof r=="string"){let e=parseInt(r,10);if(!isNaN(e))return Math.max(0,Math.min(255,Math.floor(e)))}return 243}J(As,"toColorIndex");function Y1(r,e,t,n,i){let s=e.button,o=kf(r),a=e.states[o]??e.states.normal,l=i.resolveValue(s.width,t),u=i.resolveValue(s.height??3,t),c=i.resolveValue(s.label,t),d=s.border??"single",h=i.resolveValue(a.fg??15,t),f=i.resolveValue(a.bg??0,t),p=i.resolveValue(a.textFg??h,t),m=a.offsetY??0,S=r.x,w=r.y+m;d==="none"?W1(S,w,l,u,c,h,f,p,n):G1(S,w,l,u,c,h,f,p,d,n)}J(Y1,"renderButton");function W1(r,e,t,n,i,s,o,a,l){if(n===1)l.push({type:2,posX:r,posY:e,text:" ".repeat(t),fgColorCode:s,bgColorCode:o});else for(let d=0;d<n;d++)l.push({type:2,posX:r,posY:e+d,text:" ".repeat(t),fgColorCode:s,bgColorCode:o});let u=r+Math.floor((t-i.length)/2),c=e+Math.floor(n/2);l.push({type:2,posX:u,posY:c,text:i,fgColorCode:a,bgColorCode:o})}J(W1,"renderButtonNoBorder");function G1(r,e,t,n,i,s,o,a,l,u){let c=aI[l];u.push({type:2,posX:r,posY:e,text:c.topLeft+c.horizontal.repeat(t-2)+c.topRight,fgColorCode:s,bgColorCode:o});for(let m=1;m<n-1;m++)u.push({type:2,posX:r,posY:e+m,text:c.vertical+" ".repeat(t-2)+c.vertical,fgColorCode:s,bgColorCode:o});u.push({type:2,posX:r,posY:e+n-1,text:c.bottomLeft+c.horizontal.repeat(t-2)+c.bottomRight,fgColorCode:s,bgColorCode:o});let d=t-2,h=n-2,f=r+1+Math.floor((d-i.length)/2),p=e+1+Math.floor(h/2);u.push({type:2,posX:f,posY:p,text:i,fgColorCode:a,bgColorCode:o})}J(G1,"renderButtonWithBorder");function X1(r,e,t,n,i){if(r.fillRect){let[s,o,a,l,u,c,d]=r.fillRect;return{type:3,posX:e+i.resolveValue(s,n),posY:t+i.resolveValue(o,n),sizeX:i.resolveValue(a,n),sizeY:i.resolveValue(l,n),fgColorCode:As(i.resolveValue(c,n)),bgColorCode:As(i.resolveValue(d,n)),frame:Array(i.resolveValue(a,n)*i.resolveValue(l,n)).fill(Ti(u))}}if(r.text){let[s,o,a,l]=r.text;return{type:2,posX:e+i.resolveValue(s,n),posY:t+i.resolveValue(o,n),text:i.resolveValue(a,n),fgColorCode:As(i.resolveValue(l,n)),bgColorCode:255}}if(r.setCell){let[s,o,a,l,u]=r.setCell;return{type:1,posX:e+i.resolveValue(s,n),posY:t+i.resolveValue(o,n),charCode:Ti(i.resolveValue(a,n)),fgColorCode:As(i.resolveValue(l,n)),bgColorCode:As(i.resolveValue(u,n))}}return null}J(X1,"executeRenderCommand");function K1(r,e,t,n,i,s,o){return{type:"ui",instanceId:r,macroId:e,layerId:t,x:n,y:i,params:s,tabIndex:o,isHovered:!1,isFocused:!1,isActive:!1,isDisabled:!1}}J(K1,"createUIInstance");var Z1=class{update(e,t,n,i){let s=t.emitter,{resolveValue:o}=n;if(!e.emitDone){if(s.burst){let a=o(s.burst,e.params);for(let l=0;l<a&&!(s.limit&&e.particles.length>=s.limit);l++)e.particles.push(this.createParticle(e,t,n));s.once&&(e.emitDone=!0)}else if(s.rate){let a=o(s.rate,e.params);for(e.timeSinceEmit+=a;e.timeSinceEmit>=1&&!(s.limit&&e.particles.length>=s.limit);)e.particles.push(this.createParticle(e,t,n)),e.timeSinceEmit-=1}}for(let a=e.particles.length-1;a>=0;a--){let l=e.particles[a];l.x+=l.vx,l.y+=l.vy,l.lifetime-=1,l.lifetime<=0&&e.particles.splice(a,1)}}render(e,t,n){if(e.particles.length===0)return[];let{resolveValue:i}=n,s=t.emitter,o=s.viewport??s.zone,a=i(o.x,e.params),l=i(o.y,e.params),u=i(o.width,e.params),c=i(o.height,e.params),d=e.x+(typeof a=="number"?a:0),h=e.y+(typeof l=="number"?l:0),f=typeof u=="number"?u:0,p=typeof c=="number"?c:0;if(f<=0||p<=0)return[];let m=[];for(let S of e.particles){let w=Math.floor(S.x),g=Math.floor(S.y);if(w<d||w>=d+f||g<h||g>=h+p)continue;let y=S.fg;if(t.particle.fade&&S.maxLifetime>0){let C=S.lifetime/S.maxLifetime;y=this.fadeColorIndex(S.fg,C)}m.push({charCode:Ti(S.char),fgColorCode:y,bgColorCode:S.bg??255,posX:w,posY:g})}return[{type:12,dots:m}]}createParticle(e,t,n){let{resolveValue:i,resolveRandomValue:s}=n,o=t.emitter,a=t.particle,l=i(o.zone.x,e.params),u=i(o.zone.y,e.params),c=i(o.zone.width,e.params),d=i(o.zone.height,e.params),h=e.x+l+Math.random()*c,f=e.y+u+Math.random()*d,p=0,m=0;if("x"in a.velocity&&"y"in a.velocity)p=i(a.velocity.x,e.params),m=i(a.velocity.y,e.params);else if("angle"in a.velocity&&"speed"in a.velocity){let E=s(a.velocity.angle),A=s(a.velocity.speed,e.params),R=E*Math.PI/180;p=Math.cos(R)*A,m=Math.sin(R)*A}let S=s(a.lifetime),w=Array.isArray(a.char)?a.char[Math.floor(Math.random()*a.char.length)]:a.char,g=su(w),y=Array.isArray(a.fg)?a.fg[Math.floor(Math.random()*a.fg.length)]:a.fg,C=typeof y=="number"?y:parseInt(y,10)||243,x=a.bg?Array.isArray(a.bg)?a.bg[Math.floor(Math.random()*a.bg.length)]:a.bg:void 0,I=x!==void 0?typeof x=="number"?x:parseInt(x,10)||255:void 0;return{x:h,y:f,vx:p,vy:m,char:g,fg:C,bg:I,lifetime:S,maxLifetime:S}}fadeColorIndex(e,t){return t<.1?255:e}};J(Z1,"ParticleHandler");var lI=Z1,q1=class{update(e,t,n,i){e.elapsed+=1;let s=Math.min(1,e.elapsed/e.duration),o=t.transform.decay?1-s:1,a=t.transform.offset;a&&(e.currentOffsetX=this.resolveRandomOffset(a.x,e.params,n)*o,e.currentOffsetY=this.resolveRandomOffset(a.y,e.params,n)*o),e.elapsed>=e.duration&&(i.push({instanceId:e.instanceId,event:"complete"}),n.deleteInstance(e.instanceId))}render(e,t,n){return[]}getOffset(e){return{x:e.currentOffsetX,y:e.currentOffsetY}}resolveRandomOffset(e,t,n){if(typeof e=="number")return e;if(typeof e=="string")return n.resolveValue(e,t);if(typeof e=="object"&&"random"in e){let[i,s]=e.random,o=n.resolveValue(i,t),a=n.resolveValue(s,t);return o+Math.random()*(a-o)}return 0}};J(q1,"EffectHandler");var uI=q1,Q1=class{constructor(){O(this,"spriteRegistry",null)}setSpriteRegistry(e){this.spriteRegistry=e}update(e,t,n,i){var a;if(e.finished)return;if(e.delayRemaining>0){e.delayRemaining--;return}if(e.pauseRemaining>0){e.pauseRemaining--;return}let s=((a=t.cursor)==null?void 0:a.blinkRate)??15;e.blinkTimer++,e.blinkTimer>=s&&(e.blinkTimer=0,e.blinkState=!e.blinkState);let o=e.speed;if(e.direction==="reveal"){let l=Math.min(o,e.totalCells-e.revealedCount);if(t.pauseOn&&l>0){let u=e.cells[e.revealedCount];u&&t.pauseOn.chars.includes(u.char)&&(e.pauseRemaining=t.pauseOn.duration)}e.revealedCount+=l,e.revealedCount>=e.totalCells&&(e.finished=!0,i.push({instanceId:e.instanceId,event:"complete"}))}else{let l=Math.min(o,e.revealedCount);e.revealedCount-=l,e.revealedCount<=0&&(e.finished=!0,i.push({instanceId:e.instanceId,event:"complete"}))}}render(e,t,n){let i=[],s=e.cells.slice(0,e.revealedCount),o=new Map;for(let a of s)o.has(a.y)||o.set(a.y,[]),o.get(a.y).push(a);for(let[a,l]of o){l.sort((c,d)=>c.x-d.x);let u=0;for(;u<l.length;){let c=l[u],d=u+1;for(;d<l.length&&l[d].x===l[d-1].x+1&&l[d].fg===c.fg&&l[d].bg===c.bg;)d++;if(d-u===1)i.push({type:1,posX:e.x+c.x,posY:e.y+a,charCode:c.char.charCodeAt(0),fgColorCode:c.fg,bgColorCode:c.bg});else{let h="";for(let f=u;f<d;f++)h+=l[f].char;i.push({type:2,posX:e.x+c.x,posY:e.y+a,text:h,fgColorCode:c.fg,bgColorCode:c.bg})}u=d}}if(t.cursor&&!e.finished&&(!t.cursor.blink||e.blinkState)&&e.revealedCount<e.cells.length){let a=e.cells[e.revealedCount];if(a){let l=t.cursor.bg??a.bg;i.push({type:1,posX:e.x+a.x,posY:e.y+a.y,charCode:Ti(t.cursor.char),fgColorCode:t.cursor.fg??15,bgColorCode:l})}}return i}buildCells(e,t,n){let i=[],s=e.content;switch(s.type){case"text":{let o=n(s.text,t),a=n(s.fg??15,t),l=n(s.bg??0,t),u=o.split(`
|
|
45
|
+
`);for(let c=0;c<u.length;c++){let d=u[c];for(let h=0;h<d.length;h++)i.push({char:d[h],fg:a,bg:l,x:h,y:c,revealOrder:0})}break}case"sprite":{if(!this.spriteRegistry)break;let o=n(s.sprite,t);if(s.multicolor!==!1){let l=this.spriteRegistry.getMulticolorSprite(o);if(l){let{sizeX:u,sizeY:c,data:d}=l;for(let h=0;h<c;h++)for(let f=0;f<u;f++){let p=h*u+f,m=d.get(p);m.charCode!==0&&i.push({char:String.fromCharCode(m.charCode),fg:m.fgColorCode,bg:m.bgColorCode,x:f,y:h,revealOrder:0})}break}}let a=this.spriteRegistry.getUnicolorSprite(o);if(a){let{sizeX:l,sizeY:u,data:c}=a,d=n(s.fg??15,t),h=n(s.bg??0,t);for(let f=0;f<u;f++)for(let p=0;p<l;p++){let m=f*l+p,S=c.get(m);S!==0&&i.push({char:String.fromCharCode(S),fg:d,bg:h,x:p,y:f,revealOrder:0})}}break}case"cells":{for(let o of s.cells)i.push({char:su(o.char),fg:o.fg,bg:o.bg,x:o.x,y:o.y,revealOrder:0});break}case"fill":{let o=su(s.char),a=n(s.fg,t),l=n(s.bg,t),u=n(s.width,t),c=n(s.height,t);for(let d=0;d<c;d++)for(let h=0;h<u;h++)i.push({char:o,fg:a,bg:l,x:h,y:d,revealOrder:0});break}}return this.assignRevealOrder(i,e.pattern,e.direction),i}assignRevealOrder(e,t,n){if(e.length===0)return;let i=0,s=0;for(let l of e)l.x>i&&(i=l.x),l.y>s&&(s=l.y);let o=i+1,a=s+1;switch(t){case"typewriter":for(let l of e)l.revealOrder=l.y*o+l.x;break;case"typewriter-rev":for(let l of e)l.revealOrder=(a-1-l.y)*o+(o-1-l.x);break;case"ltr":for(let l of e)l.revealOrder=l.x*a+l.y;break;case"rtl":for(let l of e)l.revealOrder=(o-1-l.x)*a+l.y;break;case"ttb":for(let l of e)l.revealOrder=l.y;break;case"btt":for(let l of e)l.revealOrder=a-1-l.y;break;case"random":{let l=e.map((u,c)=>c);for(let u=l.length-1;u>0;u--){let c=Math.floor(Math.random()*(u+1));[l[u],l[c]]=[l[c],l[u]]}for(let u=0;u<e.length;u++)e[u].revealOrder=l[u];break}case"center-out":{let l=(o-1)/2,u=(a-1)/2;for(let c of e)c.revealOrder=Math.abs(c.x-l)+Math.abs(c.y-u);break}case"spiral":{let l=(o-1)/2,u=(a-1)/2,c=Math.max(l,u);for(let d of e){let h=Math.abs(d.x-l),f=Math.abs(d.y-u),p=Math.max(h,f);d.revealOrder=c-p+(d.y*o+d.x)*.001}break}}e.sort((l,u)=>l.revealOrder-u.revealOrder);for(let l=0;l<e.length;l++)e[l].revealOrder=l}};J(Q1,"RevealHandler");var cI=Q1,J1=class{update(e,t,n,i){let{resolveValue:s}=n,o=e.params;e.currentTick++;let a=o.point;if(a&&typeof a.x=="number"&&typeof a.y=="number"){e.points.push({x:a.x,y:a.y,addedAt:e.currentTick}),delete o.point;let u=s(t.maxPoints,o)??100;for(;e.points.length>u;)e.points.shift()}o.clear===!0&&(e.points=[],delete o.clear);let l=o.points;if(Array.isArray(l)){e.points=l.map(c=>({x:c.x,y:c.y,addedAt:e.currentTick})),delete o.points;let u=s(t.maxPoints,o)??100;for(;e.points.length>u;)e.points.shift()}}render(e,t,n){let{resolveValue:i}=n,s=e.params,o=e.points;if(o.length===0)return[];let a=i(t.char,s),l=i(t.fg,s)??15,u=i(t.bg,s)??255,c=t.closed??!1,d=t.fadeOut??!1,h=o.map(f=>({x:e.x+f.x,y:e.y+f.y}));return c&&h.length>=2&&h.push({...h[0]}),d&&o.length>=2?this.renderFadedLine(e,t,n,h,a,l,u):[{type:25,charCode:Ti(a),fgColorCode:l,bgColorCode:u,points:h.map(f=>({x:f.x&255,y:f.y&255}))}]}renderFadedLine(e,t,n,i,s,o,a){e.params;let l=t.fadeLength??i.length,u=[],c=i.length,d=Math.max(0,c-l);if(d>0){let f=i.slice(0,d+1);f.length>=2&&u.push({type:25,charCode:Ti(s),fgColorCode:o,bgColorCode:a,points:f.map(p=>({x:p.x&255,y:p.y&255}))})}let h=i.slice(d);if(h.length>=2){let f=Math.max(0,o-8);u.push({type:25,charCode:Ti(s),fgColorCode:f,bgColorCode:a,points:h.map(p=>({x:p.x&255,y:p.y&255}))})}return u}};J(J1,"LineHandler");var dI=J1;function Ki(...r){}J(Ki,"macroLog");var ev=class{constructor(){O(this,"templates",new Map),O(this,"instances",new Map),O(this,"spriteRegistry",null),O(this,"playSound",null),O(this,"focusedInstanceId",null),O(this,"focusableInstances",[]),O(this,"mouseX",0),O(this,"mouseY",0),O(this,"mouseDown",!1),O(this,"particleHandler",new lI),O(this,"effectHandler",new uI),O(this,"revealHandler",new cI),O(this,"lineHandler",new dI),O(this,"instancesToDelete",[])}setSpriteRegistry(e){this.spriteRegistry=e,this.revealHandler.setSpriteRegistry(e)}setAudioCallback(e){this.playSound=e}createContext(){return{mouseX:this.mouseX,mouseY:this.mouseY,mouseDown:this.mouseDown,playSound:this.playSound??void 0,getTemplate:e=>this.getTemplate(e),resolveValue:(e,t)=>this.resolveValue(e,t),resolveRandomValue:(e,t)=>this.resolveRandomValue(e,t),deleteInstance:e=>{this.instancesToDelete.push(e)}}}loadTemplate(e,t){Ki(`loadTemplate: macroId=${e}, type=${t.type}`),this.templates.set(e,{macroId:e,template:t})}getTemplate(e){var t;return(t=this.templates.get(e))==null?void 0:t.template}hasTemplate(e){return this.templates.has(e)}applyOrder(e){switch(Ki(`applyOrder: type=${e.type}, instanceId=${e.instanceId}`),e.type){case 1:this.createInstance(e);break;case 2:this.updateInstance(e);break;case 3:this.removeInstance(e);break}}createInstance(e){let t=this.getTemplate(e.macroId);if(!t){Ki(`createInstance: FAILED - template ${e.macroId} not found`);return}Ki(`createInstance: id=${e.instanceId}, macroId=${e.macroId}, type=${t.type}, pos=(${e.x}, ${e.y}), layer=${e.layerId}`);let n;switch(t.type){case"ui":n=K1(e.instanceId,e.macroId,e.layerId,e.x,e.y,e.params,e.tabIndex),e.tabIndex>0&&this.addToFocusableList(e.instanceId,e.tabIndex);break;case"particle":n={type:"particle",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,particles:[],timeSinceEmit:0,emitDone:!1};break;case"effect":{let i=t;n={type:"effect",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,elapsed:0,duration:this.resolveValue(i.transform.duration,e.params),currentOffsetX:0,currentOffsetY:0};break}case"reveal":{let i=t,s=this.revealHandler.buildCells(i,e.params,(l,u)=>this.resolveValue(l,u)),o=s.length,a=i.direction??"reveal";n={type:"reveal",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,cells:s,revealedCount:a==="hide"?o:0,totalCells:o,delayRemaining:i.delay??0,pauseRemaining:0,finished:!1,direction:a,speed:i.speed??1,blinkState:!0,blinkTimer:0};break}case"line":{let i=[],s=e.params.points;if(Array.isArray(s)){for(let a of s)i.push({x:a.x,y:a.y,addedAt:0});delete e.params.points}let o=e.params.point;o&&typeof o.x=="number"&&typeof o.y=="number"&&(i.push({x:o.x,y:o.y,addedAt:0}),delete e.params.point),n={type:"line",instanceId:e.instanceId,macroId:e.macroId,layerId:e.layerId,x:e.x,y:e.y,params:e.params,points:i,currentTick:0};break}default:return}n&&this.instances.set(e.instanceId,n)}updateInstance(e){let t=this.instances.get(e.instanceId);if(t)for(let n in e.params)t.params[n]=e.params[n]}removeInstance(e){let t=this.instances.get(e.instanceId);t&&(t.type==="ui"&&(this.removeFromFocusableList(e.instanceId),this.focusedInstanceId===e.instanceId&&(this.focusedInstanceId=null)),this.instances.delete(e.instanceId))}addToFocusableList(e,t){this.focusableInstances.push(e),this.focusableInstances.sort((n,i)=>{let s=this.instances.get(n),o=this.instances.get(i);return((s==null?void 0:s.tabIndex)??0)-((o==null?void 0:o.tabIndex)??0)})}removeFromFocusableList(e){let t=this.focusableInstances.indexOf(e);t!==-1&&this.focusableInstances.splice(t,1)}focusNext(){if(this.focusableInstances.length===0)return;let e=((this.focusedInstanceId!==null?this.focusableInstances.indexOf(this.focusedInstanceId):-1)+1)%this.focusableInstances.length;this.setFocus(this.focusableInstances[e])}focusPrevious(){if(this.focusableInstances.length===0)return;let e=((this.focusedInstanceId!==null?this.focusableInstances.indexOf(this.focusedInstanceId):0)-1+this.focusableInstances.length)%this.focusableInstances.length;this.setFocus(this.focusableInstances[e])}setFocus(e){if(this.focusedInstanceId!==null){let t=this.instances.get(this.focusedInstanceId);(t==null?void 0:t.type)==="ui"&&(t.isFocused=!1)}if(this.focusedInstanceId=e,e!==null){let t=this.instances.get(e);(t==null?void 0:t.type)==="ui"&&(t.isFocused=!0)}}updateMouse(e,t,n){this.mouseX=e,this.mouseY=t,this.mouseDown=n}estimateUISize(e,t){if(e.subtype==="button"&&e.button){let s=this.resolveValue(e.button.width,t??{}),o=this.resolveValue(e.button.height??3,t??{});return{width:s,height:o}}let n=1,i=1;if(e.base)for(let s of e.base)"w"in s&&typeof s.w=="number"&&(n=Math.max(n,s.w)),"h"in s&&typeof s.h=="number"&&(i=Math.max(i,s.h));return{width:n,height:i}}activateFocused(){if(this.focusedInstanceId===null)return;let e=this.instances.get(this.focusedInstanceId);(e==null?void 0:e.type)==="ui"&&(e.isActive=!0)}update(){let e=[];this.instances.size>0&&Ki(`update: instances=${this.instances.size}, templates=${this.templates.size}`);let t=this.createContext();this.instancesToDelete=[];for(let n of this.instances.values()){let i=this.getTemplate(n.macroId);if(i)switch(n.type){case"ui":Hg.update(n,i,t,e);break;case"particle":this.particleHandler.update(n,i,t,e);break;case"effect":this.effectHandler.update(n,i,t,e);break;case"reveal":this.revealHandler.update(n,i,t,e);break;case"line":this.lineHandler.update(n,i,t,e);break}}for(let n of this.instancesToDelete)this.instances.delete(n);return{events:e.map(n=>({instanceId:n.instanceId,event:n.event,data:n.data}))}}getOrdersByLayer(){let e=new Map;for(let t of this.instances.values()){let n=this.renderInstance(t);n.length!==0&&(e.has(t.layerId)||e.set(t.layerId,[]),e.get(t.layerId).push(...n))}if(e.size>0){let t=0;for(let n of e.values())t+=n.length;Ki(`getOrdersByLayer: ${e.size} layers, ${t} total orders`)}return e}renderInstance(e){let t=this.getTemplate(e.macroId);if(!t)return[];let n=this.createContext();switch(e.type){case"ui":return Hg.render(e,t,n);case"particle":return this.particleHandler.render(e,t,n);case"effect":return this.effectHandler.render(e,t,n);case"reveal":return this.revealHandler.render(e,t,n);case"line":return this.lineHandler.render(e,t,n);default:return[]}}resolveValue(e,t){if(typeof e=="string"&&e.startsWith("$")){let n=e.slice(1);return t[n]??e}return e}resolveRandomValue(e,t){if(typeof e=="string"){let n=this.resolveValue(e,t??{});return typeof n=="number"?n:0}if(Array.isArray(e)){let[n,i]=e;return n+Math.random()*(i-n)}return e}getEffectOffset(){let e=0,t=0;for(let n of this.instances.values())n.type==="effect"&&(e+=n.currentOffsetX,t+=n.currentOffsetY);return{x:e,y:t}}getAllInstances(){return Array.from(this.instances.values())}getInstanceCount(){return this.instances.size}clear(){this.templates.clear(),this.instances.clear(),this.focusedInstanceId=null,this.focusableInstances=[]}};J(ev,"MacroEngine");var hI=ev,tv=class{constructor(){O(this,"axes",new Map),O(this,"buttons",new Map),O(this,"touchZones",new Map),O(this,"axisNameToId",new Map),O(this,"buttonNameToId",new Map),O(this,"touchZoneNameToId",new Map),O(this,"version",1)}defineAxis(e,t,n=[],i=-1,s=1,o=0){if(e<0||e>255)throw new Error(`Axis bindingId must be between 0 and 255, got ${e}`);if(this.axes.has(e))throw new Error(`Axis bindingId ${e} is already defined`);if(this.axisNameToId.has(t)){let l=this.axisNameToId.get(t);throw new Error(`Axis name "${t}" is already defined with bindingId ${l}`)}let a={bindingId:e,name:t,min:i,max:s,defaultValue:o,sources:n};this.axes.set(e,a),this.axisNameToId.set(t,e),this.version++}defineButton(e,t,n=[],i=!1){if(e<0||e>255)throw new Error(`Button bindingId must be between 0 and 255, got ${e}`);if(this.buttons.has(e))throw new Error(`Button bindingId ${e} is already defined`);if(this.buttonNameToId.has(t)){let o=this.buttonNameToId.get(t);throw new Error(`Button name "${t}" is already defined with bindingId ${o}`)}let s={bindingId:e,name:t,defaultValue:i,sources:n};this.buttons.set(e,s),this.buttonNameToId.set(t,e),this.version++}defineTouchZone(e,t,n,i,s,o){if(e<0||e>31)throw new Error(`Touch zone zoneId must be between 0 and 31, got ${e}`);if(this.touchZones.has(e))throw new Error(`Touch zone zoneId ${e} is already defined`);if(this.touchZoneNameToId.has(t)){let l=this.touchZoneNameToId.get(t);throw new Error(`Touch zone name "${t}" is already defined with zoneId ${l}`)}if(s<=0||o<=0)throw new Error(`Touch zone dimensions must be positive, got ${s}x${o}`);let a={zoneId:e,name:t,x:n,y:i,width:s,height:o};this.touchZones.set(e,a),this.touchZoneNameToId.set(t,e),this.version++}evaluateAxis(e,t){let n=this.axes.get(e);if(!n)return 0;let i=0;for(let s of n.sources){let o=t.get(s.sourceId)??0,a=s.deadzone??0;Math.abs(o)<a?o=0:o=(o>0?1:-1)*((Math.abs(o)-a)/(1-a));let l=s.scale??1;o*=l;let u=s.sensitivity??1;o*=u,s.invert&&(o=-o),i+=o}return Math.max(n.min,Math.min(n.max,i))}evaluateButton(e,t){let n=this.buttons.get(e);if(!n)return!1;for(let i of n.sources)if(t.get(i.sourceId)??!1)return!0;return!1}toLoadPacket(){let e={type:"input-binding",version:this.version,axes:Array.from(this.axes.values()),buttons:Array.from(this.buttons.values()),touchZones:this.touchZones.size>0?Array.from(this.touchZones.values()):void 0};return JSON.stringify(e)}toLoadPacketObject(){return{type:"input-binding",version:this.version,axes:Array.from(this.axes.values()),buttons:Array.from(this.buttons.values()),touchZones:this.touchZones.size>0?Array.from(this.touchZones.values()):void 0}}getAxisBindingId(e){return this.axisNameToId.get(e)??null}getButtonBindingId(e){return this.buttonNameToId.get(e)??null}getAxisName(e){var t;return((t=this.axes.get(e))==null?void 0:t.name)??null}getButtonName(e){var t;return((t=this.buttons.get(e))==null?void 0:t.name)??null}getAxisBinding(e){return this.axes.get(e)??null}getButtonBinding(e){return this.buttons.get(e)??null}hasAxis(e){return this.axes.has(e)}hasButton(e){return this.buttons.has(e)}hasTouchZone(e){return this.touchZones.has(e)}getAxisCount(){return this.axes.size}getButtonCount(){return this.buttons.size}getTouchZoneCount(){return this.touchZones.size}getAllAxes(){return Array.from(this.axes.values())}getAllButtons(){return Array.from(this.buttons.values())}getAllTouchZones(){return Array.from(this.touchZones.values())}getTouchZone(e){return this.touchZones.get(e)??null}getTouchZoneId(e){return this.touchZoneNameToId.get(e)??null}getVersion(){return this.version}removeAxis(e){let t=this.axes.get(e);return t?(this.axes.delete(e),this.axisNameToId.delete(t.name),this.version++,!0):!1}removeButton(e){let t=this.buttons.get(e);return t?(this.buttons.delete(e),this.buttonNameToId.delete(t.name),this.version++,!0):!1}removeTouchZone(e){let t=this.touchZones.get(e);return t?(this.touchZones.delete(e),this.touchZoneNameToId.delete(t.name),this.version++,!0):!1}clearAxes(){this.axes.clear(),this.axisNameToId.clear(),this.version++}clearButtons(){this.buttons.clear(),this.buttonNameToId.clear(),this.version++}clearTouchZones(){this.touchZones.clear(),this.touchZoneNameToId.clear(),this.version++}clear(){this.axes.clear(),this.axisNameToId.clear(),this.buttons.clear(),this.buttonNameToId.clear(),this.touchZones.clear(),this.touchZoneNameToId.clear(),this.version=1}toString(){let e=`InputBindingRegistry (version ${this.version})
|
|
46
46
|
`;return e+=`Axes (${this.axes.size}):
|
|
47
47
|
`,this.axes.forEach(t=>{e+=` [${t.bindingId}] ${t.name}: `,e+=`${t.min} to ${t.max} (default: ${t.defaultValue})
|
|
48
48
|
`}),e+=`Buttons (${this.buttons.size}):
|
|
49
49
|
`,this.buttons.forEach(t=>{e+=` [${t.bindingId}] ${t.name}: `,e+=`(default: ${t.defaultValue})
|
|
50
50
|
`}),e+=`Touch Zones (${this.touchZones.size}):
|
|
51
51
|
`,this.touchZones.forEach(t=>{e+=` [${t.zoneId}] ${t.name}: `,e+=`(${t.x}, ${t.y}) ${t.width}x${t.height}
|
|
52
|
-
`}),e}};J(tv,"InputBindingRegistry");var fI=tv;function rv(r=0n){return{tick:r,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[],isTabHidden:!1}}J(rv,"createEmptyCompressedInputPacket");function nv(r){let e=Math.max(-1,Math.min(1,r));return Math.round(e*127)}J(nv,"encodeAxisToInt8");function iv(r){return r/127}J(iv,"decodeInt8ToAxis");function Tu(r){return r===0?0:Math.ceil(r/8)}J(Tu,"getButtonByteCount");function sv(r,e){let t=r,n=Tu(e);return 8+t+n+4}J(sv,"getCompressedPacketSize");var ov=class{decode(e,t=0){let n=e.readUInt8(t);switch(n){case 1:return this.decodeClick(e,t);case 2:return this.decodeChange(e,t);case 3:return this.decodeSubmit(e,t);case 4:return this.decodeSelect(e,t);default:throw new Error(`Unknown macro event type: 0x${n.toString(16)}`)}}decodeAll(e,t,n){let i=[],s=0;for(let o=0;o<n;o++){let{event:a,bytesRead:l}=this.decode(e,t+s);i.push(a),s+=l}return{events:i,bytesRead:s}}decodeClick(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1);return{event:{type:n,instanceId:i},bytesRead:2}}decodeChange(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1),s=e.readUInt8(t+2),o,a;return s===1?(o=e.readUInt8(t+3)===1,a=4):(o=e.readFloatBE(t+3),a=7),{event:{type:n,instanceId:i,value:o},bytesRead:a}}decodeSubmit(e,t){let n=t,i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+o);t+=o;let l=new TextDecoder().decode(a);return{event:{type:i,instanceId:s,text:l},bytesRead:t-n}}decodeSelect(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1),s=e.readUInt16BE(t+2);return{event:{type:n,instanceId:i,index:s},bytesRead:4}}};J(ov,"MacroEventDecoder");var pI=ov,av=class Zi{constructor(e){D(this,"data"),D(this,"view"),this.data=new Uint8Array(e),this.view=new DataView(this.data.buffer)}static from(e){let t=new Zi(0);return t.data=e,t.view=new DataView(e.buffer,e.byteOffset,e.byteLength),t}static allocUnsafe(e){return new Zi(e)}get length(){return this.data.length}toUint8Array(){return this.data}readUInt8(e){return this.view.getUint8(e)}readInt8(e){return this.view.getInt8(e)}readUInt16BE(e){return this.view.getUint16(e,!1)}readInt16BE(e){return this.view.getInt16(e,!1)}readUInt16LE(e){return this.view.getUint16(e,!0)}readInt16LE(e){return this.view.getInt16(e,!0)}readUInt32BE(e){return this.view.getUint32(e,!1)}readInt32BE(e){return this.view.getInt32(e,!1)}readUInt32LE(e){return this.view.getUint32(e,!0)}readInt32LE(e){return this.view.getInt32(e,!0)}readBigUInt64BE(e){return this.view.getBigUint64(e,!1)}readBigInt64BE(e){return this.view.getBigInt64(e,!1)}readBigUInt64LE(e){return this.view.getBigUint64(e,!0)}readBigInt64LE(e){return this.view.getBigInt64(e,!0)}writeUInt8(e,t){this.view.setUint8(t,e)}writeInt8(e,t){this.view.setInt8(t,e)}writeUInt16BE(e,t){this.view.setUint16(t,e,!1)}writeInt16BE(e,t){this.view.setInt16(t,e,!1)}writeUInt16LE(e,t){this.view.setUint16(t,e,!0)}writeInt16LE(e,t){this.view.setInt16(t,e,!0)}writeUInt32BE(e,t){this.view.setUint32(t,e,!1)}writeInt32BE(e,t){this.view.setInt32(t,e,!1)}writeUInt32LE(e,t){this.view.setUint32(t,e,!0)}writeInt32LE(e,t){this.view.setInt32(t,e,!0)}writeBigUInt64BE(e,t){this.view.setBigUint64(t,e,!1)}writeBigInt64BE(e,t){this.view.setBigInt64(t,e,!1)}writeBigUInt64LE(e,t){this.view.setBigUint64(t,e,!0)}writeBigInt64LE(e,t){this.view.setBigInt64(t,e,!0)}readFloatBE(e){return this.view.getFloat32(e,!1)}readFloatLE(e){return this.view.getFloat32(e,!0)}writeFloatBE(e,t){this.view.setFloat32(t,e,!1)}writeFloatLE(e,t){this.view.setFloat32(t,e,!0)}copy(e,t=0,n=0,i=this.length){let s=this.data.subarray(n,i);return e.data.set(s,t),s.length}slice(e,t){let n=this.data.slice(e,t);return Zi.from(n)}subarray(e,t){let n=this.data.subarray(e,t);return Zi.from(n)}toBuffer(){return typeof Buffer<"u"&&Buffer.from?Buffer.from(this.data):this.data}static fromNodeBuffer(e){return e instanceof Uint8Array?Zi.from(e):Zi.from(new Uint8Array(e))}};J(av,"BufferCompat");var ie=av,gI=new TextDecoder,mI=new pI;function lv(r,e){let t=e.getAllAxes().length,n=e.getAllButtons().length,i=Tu(n),s=8+t+i+4;if(r.length<s)throw new Error(`Invalid compressed input packet: expected at least ${s} bytes (${t} axes + ${n} buttons), got ${r.length}`);let o=new DataView(r.buffer,r.byteOffset,r.byteLength),a=0,l=rv();l.tick=o.getBigUint64(a,!0),a+=8;for(let c=0;c<t;c++){let d=r[a],h=d>127?d-256:d,f=iv(h);l.axes.set(c,f),a+=1}for(let c=0;c<i;c++){let d=r[a];for(let h=0;h<8;h++){let f=c*8+h;if(f<n){let p=(d&1<<h)!==0;l.buttons.set(f,p)}}a+=1}l.displayId=r[a],a+=1,l.mouseX=r[a],a+=1,l.mouseY=r[a],a+=1;let u=r[a];if(l.mouseOverDisplay=(u&1)!==0,l.isTabHidden=(u&2)!==0,a+=1,a<r.length){let c=r[a];a+=1,l.textInputs=[];for(let d=0;d<c&&a<r.length;d++){let h=r[a];if(a+=1,a+h<=r.length){let f=r.slice(a,a+h),p=gI.decode(f);l.textInputs.push(p),a+=h}}}if(a<r.length){let c=r[a];a+=1;let d=[],h=ie.from(r);for(let f=0;f<c&&a<r.length;f++){let p=mI.decode(h,a);d.push(p.event),a+=p.bytesRead}l.macroEvents=d}if(a<r.length){let c=r[a];a+=1;for(let d=0;d<c&&a+5<=r.length;d++){let h=r[a];a+=1;let f=o.getUint16(a,!1);a+=2;let p=o.getUint16(a,!1);a+=2,l.displayViewports.push({displayId:h,pixelWidth:f,pixelHeight:p})}}if(a<r.length){let c=Math.min(r[a],10);a+=1;for(let d=0;d<c&&a+4<=r.length;d++){let h=r[a]&15;a+=1;let f=r[a];a+=1;let p=r[a];a+=1;let m=(r[a]&1)!==0;a+=1,l.touchPositions.push({id:h,x:f,y:p,over:m})}}return l}J(lv,"decodeCompressedInput");var uv=class{constructor(e,t){D(this,"enabled",!1),D(this,"currentStats",null),D(this,"_userId"),D(this,"_userName"),this._userId=e,this._userName=t}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get userId(){var e;return((e=this.currentStats)==null?void 0:e.userId)??this._userId}get userName(){var e;return((e=this.currentStats)==null?void 0:e.userName)??this._userName}get tick(){var e;return((e=this.currentStats)==null?void 0:e.tick)??0}get timestamp(){var e;return((e=this.currentStats)==null?void 0:e.timestamp)??0}get displayCount(){var e;return((e=this.currentStats)==null?void 0:e.displayCount)??0}get totalDisplayArea(){var e;return((e=this.currentStats)==null?void 0:e.totalDisplayArea)??0}get totalLayers(){var e;return((e=this.currentStats)==null?void 0:e.totalLayers)??0}get visibleLayers(){var e;return((e=this.currentStats)==null?void 0:e.visibleLayers)??0}get staticLayers(){var e;return((e=this.currentStats)==null?void 0:e.staticLayers)??0}get dynamicLayers(){var e;return((e=this.currentStats)==null?void 0:e.dynamicLayers)??0}get totalOrders(){var e;return((e=this.currentStats)==null?void 0:e.totalOrders)??0}get ordersByLayer(){var e;return((e=this.currentStats)==null?void 0:e.ordersByLayer)??new Map}get staticPacketSize(){var e;return((e=this.currentStats)==null?void 0:e.staticPacketSize)??0}get dynamicPacketSize(){var e;return((e=this.currentStats)==null?void 0:e.dynamicPacketSize)??0}get totalPacketSize(){var e;return((e=this.currentStats)==null?void 0:e.totalPacketSize)??0}get compressedPacketSize(){return Math.round(this.totalPacketSize*.25)}get hasInput(){var e;return((e=this.currentStats)==null?void 0:e.hasInput)??!1}get axisCount(){var e;return((e=this.currentStats)==null?void 0:e.axisCount)??0}get buttonCount(){var e;return((e=this.currentStats)==null?void 0:e.buttonCount)??0}startTick(e){this.enabled&&(this.currentStats={userId:this._userId,userName:this._userName,tick:e,timestamp:Date.now(),displayCount:0,totalDisplayArea:0,totalLayers:0,visibleLayers:0,staticLayers:0,dynamicLayers:0,totalOrders:0,ordersByLayer:new Map,staticPacketSize:0,dynamicPacketSize:0,totalPacketSize:0,hasInput:!1,axisCount:0,buttonCount:0})}recordDisplays(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCount=e,this.currentStats.totalDisplayArea=t)}recordLayers(e,t,n,i){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t,this.currentStats.staticLayers=n,this.currentStats.dynamicLayers=i)}recordLayerOrders(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalOrders+=t,this.currentStats.ordersByLayer.set(e,t))}recordPacketSizes(e,t){!this.enabled||!this.currentStats||(this.currentStats.staticPacketSize=e,this.currentStats.dynamicPacketSize=t,this.currentStats.totalPacketSize=e+t)}recordInput(e,t,n){!this.enabled||!this.currentStats||(this.currentStats.hasInput=e,this.currentStats.axisCount=t,this.currentStats.buttonCount=n)}endTick(){}reset(){this.currentStats=null}};J(uv,"UserStats");var yI=uv,cv=class{constructor(e,t,n){this.id=e,this.name=t,D(this,"displays",[]),D(this,"layers",[]),D(this,"spriteRegistry"),D(this,"mode"),D(this,"axes",new Map),D(this,"buttons",new Map),D(this,"textInputs",[]),D(this,"mouseX",0),D(this,"mouseY",0),D(this,"mouseOver",!1),D(this,"mouseDisplayId",0),D(this,"isTabHidden",!1),D(this,"touchPositions",new Map),D(this,"activeTouchId",null),D(this,"inputBindings",new fI),D(this,"stats"),D(this,"soundCommands",[]),D(this,"nextSoundInstanceId",1),D(this,"audioConfigCommands",[]),D(this,"lastListenerX",-1),D(this,"lastListenerY",-1),D(this,"pendingSendSounds",!1),D(this,"audioProcessor"),D(this,"loadedSounds",new Map),D(this,"soundLoadErrors",new Map),D(this,"playingSounds",new Map),D(this,"mobileVibrationCommands",[]),D(this,"mobileVibrationProcessor"),D(this,"gamepadVibrationCommands",[]),D(this,"gamepadVibrationProcessor"),D(this,"macroRegistry",new nI),D(this,"macroEngine",new hI),D(this,"macroEventHandlers",new Map),D(this,"postProcessCommands",[]),D(this,"currentPostProcessConfig",null),D(this,"bridgeMessages",[]),D(this,"totalBytesSent",0),D(this,"totalBytesReceived",0),D(this,"bytesSentPerTick",[]),D(this,"bytesReceivedPerTick",[]),D(this,"bytesTickIndex",0),D(this,"bytesTickRate",20),D(this,"currentTickBytesSent",0),D(this,"currentTickBytesReceived",0),D(this,"lastInputTick",-1n),D(this,"availableViewports",new Map),D(this,"displayCommandSink",{setPostProcess:(i,s)=>this.setPostProcess(i,s),setScanlinesEnabled:(i,s)=>this.setScanlinesEnabled(i,s),setScanlinesOpacity:(i,s)=>this.setScanlinesOpacity(i,s),setScanlinesPattern:(i,s)=>this.setScanlinesPattern(i,s),setAmbientEffect:(i,s)=>this.setAmbientEffect(i,s),setAmbientEffectEnabled:(i,s)=>this.setAmbientEffectEnabled(i,s),setAmbientEffectBlur:(i,s)=>this.setAmbientEffectBlur(i,s),setAmbientEffectScale:(i,s)=>this.setAmbientEffectScale(i,s),isAmbientEffectEnabled:()=>this.isAmbientEffectEnabled(),getAmbientEffectConfig:()=>this.getAmbientEffectConfig(),getPostProcessConfig:()=>this.getPostProcessConfig(),setScalingMode:(i,s)=>this.setScalingMode(i,s),getScalingMode:i=>this.getScalingMode(i),setCellSize:(i,s,o)=>this.setCellSize(i,s,o),getCellSize:i=>this.getCellSize(i),setGrid:(i,s)=>this.setGrid(i,s),setGridEnabled:(i,s)=>this.setGridEnabled(i,s),isGridEnabled:i=>this.isGridEnabled(i),getGridConfig:i=>this.getGridConfig(i),switchPalette:(i,s)=>this.switchPalette(i,s),getCurrentPaletteSlotId:i=>this.getCurrentPaletteSlotId(i)}),D(this,"data"),D(this,"currentScalingModes",new Map),D(this,"currentCellSizes",new Map),D(this,"currentGridConfigs",new Map),D(this,"currentPaletteSlotIds",new Map),this.mode=n,this.stats=new yI(e,t),this.data={}}setSpriteRegistry(e){this.spriteRegistry=e;for(let t of this.layers)t.setSpriteRegistry(e);this.macroEngine.setSpriteRegistry(e)}getDisplays(){return this.displays}addDisplay(e){e.setCommandSink(this.displayCommandSink),this.displays.push(e)}removeDisplay(e){let t=this.displays.indexOf(e);return t!==-1?(this.displays.splice(t,1),!0):!1}clearDisplays(){this.displays=[]}setDisplayViewport(e,t,n){this.availableViewports.set(e,{pixelWidth:t,pixelHeight:n})}getDisplayViewport(e){return this.availableViewports.get(e)??null}getAllDisplayViewports(){return this.availableViewports}calculateMaxCells(e,t,n){let i=this.availableViewports.get(e);return i?{cols:Math.floor(i.pixelWidth/t),rows:Math.floor(i.pixelHeight/n)}:null}getLayers(){return this.layers}getLayerById(e){return this.layers.find(t=>t.getId()===e)}addLayer(e,t){e.setMode(this.mode);let n=this.layers.length+1;Aa(e,n),this.layers.push(e),this.spriteRegistry&&e.setSpriteRegistry(this.spriteRegistry),t&&this.macroRegistry.setLayerMapping(t,e.getId())}removeLayer(e){let t=this.layers.indexOf(e);return t!==-1?(this.layers.splice(t,1),!0):!1}clearLayers(){this.layers=[]}setMousePosition(e,t,n=!0){this.mouseX=Math.max(0,Math.min(255,e)),this.mouseY=Math.max(0,Math.min(255,t)),this.mouseOver=n}setTouchPosition(e,t,n,i=!0,s=0){if(e<0||e>9){console.warn(`Invalid touchId ${e}, must be 0-9`);return}i?(this.touchPositions.set(e,{x:Math.max(0,Math.min(255,t)),y:Math.max(0,Math.min(255,n)),over:!0,displayId:s}),this.activeTouchId=e):(this.touchPositions.delete(e),this.activeTouchId===e&&(this.activeTouchId=null))}setAxis(e,t){let n=Math.max(-1,Math.min(1,t));this.axes.set(e,n)}getAxis(e){return this.axes.get(e)??0}setButton(e,t){this.buttons.set(e,t)}getButton(e){return this.buttons.get(e)??!1}getButtonJustPressed(e){let t=`${e}_justPressed`;return this.buttons.get(t)??!1}getButtonJustReleased(e){let t=`${e}_justReleased`;return this.buttons.get(t)??!1}setTextInputs(e){this.textInputs=e}getTextInputs(){return this.textInputs}clearTextInputs(){this.textInputs=[]}getAxisNames(){return Array.from(this.axes.keys())}getButtonNames(){return Array.from(this.buttons.keys())}clearAxes(){this.axes.clear()}clearButtons(){this.buttons.clear()}getMouseDisplayInfo(){if(!this.mouseOver||this.displays.length===0)return null;let e=this.displays[0],t=0,n=this.mouseX,i=this.mouseY,s=e.getOrigin(),o=s.x+n,a=s.y+i;return{displayId:t,localX:n,localY:i,worldX:o,worldY:a}}getTouchDisplayInfo(e=0){if(e<0||e>9)return console.warn(`Invalid touchId ${e}, must be 0-9`),null;let t=this.touchPositions.get(e);if(!t||!t.over||this.displays.length===0)return null;let n=this.displays[0],i=t.displayId,s=t.x,o=t.y,a=n.getOrigin(),l=a.x+s,u=a.y+o;return{displayId:i,localX:s,localY:o,worldX:l,worldY:u}}getIsMouseOnADisplay(){return this.mouseOver}getMouseDisplayHover(){let e=this.getMouseDisplayInfo();return e?e.displayId:null}findLayerById(e){return this.layers.find(t=>t.getId()===e)??null}applyUpdate(e){if(this.updateDisplaysFromPacket(e.displays),this.updateLayersFromPacket(e.layers),e.macroOrders&&e.macroOrders.length>0)for(let t of e.macroOrders)this.macroEngine.applyOrder(t)}updateDisplaysFromPacket(e){for(let t of e){let n=this.displays[t.id];if(!n){for(n=new px(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=n}n.setCommandSink(this.displayCommandSink),n.setOrigin(new Yt(t.originX,t.originY)),n.setSize(new Yt(t.sizeX,t.sizeY)),n.setRenderPasses(t.renderPasses)}}updateLayersFromPacket(e){for(let t of e){let n=this.findLayerById(t.id);n||(n=new Zx(new Yt(t.originX,t.originY),t.zIndex,t.width,t.height,{mustBeReliable:!1,isMacroLayer:t.isMacroLayer,charCodeMode:t.is16bit?"16bit":"8bit"}),Aa(n,t.id),n.setMode(this.mode),this.spriteRegistry&&n.setSpriteRegistry(this.spriteRegistry),this.addLayer(n)),t.updateFlags&1&&n.setOrigin(new Yt(t.originX,t.originY)),t.updateFlags&2&&n.setZOrder(t.zIndex),t.updateFlags&4&&n.setOrders(t.orders)}}defineAxisBinding(e,t,n=[],i=-1,s=1,o=0){this.inputBindings.defineAxis(e,t,n,i,s,o)}defineButtonBinding(e,t,n=[],i=!1){this.inputBindings.defineButton(e,t,n,i)}defineAxisBindings(e){e.forEach(({bindingId:t,name:n,sources:i,min:s,max:o,defaultValue:a})=>{this.defineAxisBinding(t,n,i??[],s,o,a)})}defineButtonBindings(e){e.forEach(({bindingId:t,name:n,sources:i,defaultValue:s})=>{this.defineButtonBinding(t,n,i??[],s)})}getInputBindingsLoadPacket(){return this.inputBindings.toLoadPacket()}applyInputBindingsLoadPacket(e){try{let t=JSON.parse(e);if(t.type!=="input-binding")throw new Error(`Invalid packet type: ${t.type}`);this.inputBindings.clear();for(let n of t.axes)this.defineAxisBinding(n.bindingId,n.name,n.sources||[],n.min,n.max,n.defaultValue);for(let n of t.buttons)this.defineButtonBinding(n.bindingId,n.name,n.sources||[],n.defaultValue)}catch(t){throw console.error("[User] Failed to apply input bindings:",t),t}}getInputBindingRegistry(){return this.inputBindings}getStats(){return this.stats}getTotalBytesSent(){return this.totalBytesSent}getTotalBytesReceived(){return this.totalBytesReceived}recordBytesSent(e){this.totalBytesSent+=e,this.currentTickBytesSent+=e}recordBytesReceived(e){this.totalBytesReceived+=e,this.currentTickBytesReceived+=e}resetByteCounters(){this.totalBytesSent=0,this.totalBytesReceived=0}setBytesTickRate(e){e<=0||(this.bytesTickRate=e,this.bytesSentPerTick=new Array(e).fill(0),this.bytesReceivedPerTick=new Array(e).fill(0),this.bytesTickIndex=0)}endTickBytes(){this.bytesSentPerTick.length!==this.bytesTickRate&&(this.bytesSentPerTick=new Array(this.bytesTickRate).fill(0),this.bytesReceivedPerTick=new Array(this.bytesTickRate).fill(0)),this.bytesSentPerTick[this.bytesTickIndex]=this.currentTickBytesSent,this.bytesReceivedPerTick[this.bytesTickIndex]=this.currentTickBytesReceived,this.bytesTickIndex=(this.bytesTickIndex+1)%this.bytesTickRate,this.currentTickBytesSent=0,this.currentTickBytesReceived=0}getBytesSentPerSecond(){return this.bytesSentPerTick.reduce((e,t)=>e+t,0)}getBytesReceivedPerSecond(){return this.bytesReceivedPerTick.reduce((e,t)=>e+t,0)}getAxisBindingId(e){return this.inputBindings.getAxisBindingId(e)}getButtonBindingId(e){return this.inputBindings.getButtonBindingId(e)}decodeAndApplyCompressedInput(e){let t=lv(e,this.inputBindings);this.lastInputTick=t.tick;let n=this.inputBindings.getAllAxes(),i=this.inputBindings.getAllButtons(),s=n.sort((a,l)=>a.bindingId-l.bindingId),o=i.sort((a,l)=>a.bindingId-l.bindingId);for(let[a,l]of t.axes)if(a<s.length){let u=s[a];this.setAxis(u.name,l)}for(let[a,l]of t.buttons)if(a<o.length){let u=o[a],c=this.getButton(u.name);this.setButton(u.name,l);let d=l&&!c,h=!l&&c;this.setButton(`${u.name}_justPressed`,d),this.setButton(`${u.name}_justReleased`,h)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId,this.isTabHidden=t.isTabHidden;for(let a of t.touchPositions)this.setTouchPosition(a.id,a.x,a.y,a.over);for(let a of t.displayViewports)this.setDisplayViewport(a.displayId,a.pixelWidth,a.pixelHeight)}playSound(e,t){let n=this.nextSoundInstanceId++,i={sound:e,instanceId:n,volume:t==null?void 0:t.volume,pitch:t==null?void 0:t.pitch,loop:t==null?void 0:t.loop,fadeIn:t==null?void 0:t.fadeIn,x:t==null?void 0:t.x,y:t==null?void 0:t.y,lowpass:t==null?void 0:t.lowpass,highpass:t==null?void 0:t.highpass,reverb:t==null?void 0:t.reverb};return this.soundCommands.push(i),n}stopSound(e){let t={sound:e};this.soundCommands.push(t)}fadeOutSound(e,t){let n={fadeOut:!0,sound:e,duration:t};this.soundCommands.push(n)}fadeOutAllSounds(e){let t={fadeOut:!0,sound:"all",duration:e};this.soundCommands.push(t)}stopAllSounds(){let e={sound:"all"};this.soundCommands.push(e)}pauseSound(e){let t={pause:!0,sound:e};this.soundCommands.push(t)}pauseAllSounds(){let e={pause:!0,sound:"all"};this.soundCommands.push(e)}resumeSound(e){let t={resume:!0,sound:e};this.soundCommands.push(t)}resumeAllSounds(){let e={resume:!0,sound:"all"};this.soundCommands.push(e)}setSoundEffects(e,t){let n={setEffects:!0,instanceId:e,lowpass:t.lowpass,highpass:t.highpass,reverb:t.reverb};this.soundCommands.push(n)}setListenerPosition(e,t){e===this.lastListenerX&&t===this.lastListenerY||(this.lastListenerX=e,this.lastListenerY=t,this.audioConfigCommands.push({type:"set-listener-position",x:e,y:t}))}configureSpatialAudio(e){this.audioConfigCommands.push({type:"configure-spatial",...e})}flushAudioConfigCommands(){let e=this.audioConfigCommands;return this.audioConfigCommands=[],e}hasAudioConfigCommands(){return this.audioConfigCommands.length>0}flushSoundCommands(){let e=this.soundCommands;return this.soundCommands=[],e}hasSoundCommands(){return this.soundCommands.length>0}sendSounds(){this.pendingSendSounds=!0}needsSendSounds(){return this.pendingSendSounds}clearSendSounds(){this.pendingSendSounds=!1}setAudioProcessor(e){this.audioProcessor=e,this.macroEngine.setAudioCallback(t=>{e.play(t)})}getAudioProcessor(){return this.audioProcessor}applyAudioCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e){if("setEffects"in t&&t.setEffects===!0){let n=t;this.audioProcessor.setEffects(n.instanceId,n.lowpass,n.highpass,n.reverb);continue}if("fadeOut"in t&&t.fadeOut===!0){let n=t;this.audioProcessor.fadeOut(n.sound,n.duration);continue}if("pause"in t&&t.pause===!0){let n=t;this.audioProcessor.pause(n.sound);continue}if("resume"in t&&t.resume===!0){let n=t;this.audioProcessor.resume(n.sound);continue}if("instanceId"in t||"volume"in t||"pitch"in t||"loop"in t||"fadeIn"in t||"x"in t||"y"in t||"lowpass"in t||"highpass"in t||"reverb"in t){let n=t,i=n.x!==void 0&&n.y!==void 0?{x:n.x,y:n.y}:void 0;this.audioProcessor.play(n.sound,{volume:n.volume,pitch:n.pitch,loop:n.loop,fadeIn:n.fadeIn,position:i,instanceId:n.instanceId,lowpass:n.lowpass,highpass:n.highpass,reverb:n.reverb})}else{let n=t;n.sound==="all"?this.audioProcessor.stopAll():this.audioProcessor.stop(n.sound)}}}applyAudioConfigCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e)t.type==="set-listener-position"?this.audioProcessor.setListenerPosition(t.x,t.y):t.type==="configure-spatial"&&this.audioProcessor.configureSpatial({maxDistance:t.maxDistance,referenceDistance:t.referenceDistance,rolloffFactor:t.rolloffFactor,panSpread:t.panSpread})}vibrate(e){let t={pattern:e};this.mobileVibrationCommands.push(t)}cancelVibration(){let e={cancel:!0};this.mobileVibrationCommands.push(e)}vibrateTap(){this.vibrate(10)}vibrateMediumTap(){this.vibrate(25)}vibrateHeavyTap(){this.vibrate(50)}vibrateSuccess(){this.vibrate([30,50,30])}vibrateError(){this.vibrate([50,30,50,30,50])}vibrateWarning(){this.vibrate([100])}vibrateSelection(){this.vibrate(5)}vibrateImpact(e="medium"){let t={light:15,medium:30,heavy:50};this.vibrate(t[e])}vibrateNotification(){this.vibrate([100,100,100,100,100])}vibrateGamepad(e,t){let n={gamepadIndex:e,options:t};this.gamepadVibrationCommands.push(n)}stopGamepadVibration(e="all"){let t={gamepadIndex:e,cancel:!0};this.gamepadVibrationCommands.push(t)}gamepadTap(e=0){this.vibrateGamepad(e,{duration:50,strongMagnitude:.3,weakMagnitude:.5})}gamepadImpact(e=0){this.vibrateGamepad(e,{duration:100,strongMagnitude:.7,weakMagnitude:.3})}gamepadHeavy(e=0){this.vibrateGamepad(e,{duration:200,strongMagnitude:1,weakMagnitude:.2})}gamepadExplosion(e=0){this.vibrateGamepad(e,{duration:400,strongMagnitude:1,weakMagnitude:.8})}gamepadSuccess(e=0){this.vibrateGamepad(e,{duration:150,strongMagnitude:.4,weakMagnitude:.6})}gamepadError(e=0){this.vibrateGamepad(e,{duration:300,strongMagnitude:.8,weakMagnitude:.4})}hasGamepadVibrationCommands(){return this.gamepadVibrationCommands.length>0}flushGamepadVibrationCommands(){let e=this.gamepadVibrationCommands;return this.gamepadVibrationCommands=[],e}setGamepadVibrationProcessor(e){this.gamepadVibrationProcessor=e}applyGamepadVibrationCommands(e){if(this.gamepadVibrationProcessor&&this.mode!=="server"){for(let t of e)if("cancel"in t&&t.cancel===!0)t.gamepadIndex==="all"?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(t.gamepadIndex);else if("options"in t){let n=t;if(n.gamepadIndex==="all")for(let i=0;i<4;i++)this.gamepadVibrationProcessor.vibrate(i,n.options);else this.gamepadVibrationProcessor.vibrate(n.gamepadIndex,n.options)}}}hasMobileVibrationCommands(){return this.mobileVibrationCommands.length>0}flushMobileVibrationCommands(){let e=this.mobileVibrationCommands;return this.mobileVibrationCommands=[],e}setMobileVibrationProcessor(e){this.mobileVibrationProcessor=e}getMobileVibrationProcessor(){return this.mobileVibrationProcessor}applyMobileVibrationCommands(e){if(this.mobileVibrationProcessor&&this.mode!=="server")for(let t of e)"cancel"in t&&t.cancel===!0?this.mobileVibrationProcessor.cancel():"pattern"in t&&this.mobileVibrationProcessor.vibrate(t.pattern)}applyVibrationOrders(e){if(this.mode==="server")return;let{VibrationOrderType:t}=(A1(),ul(U1)),{MobileVibrateFlags:n,GamepadVibrateFlags:i}=(R1(),ul(T1));for(let s of e)switch(s.type){case t.MobileVibrate:{if(!this.mobileVibrationProcessor)break;let o=s,a=o.pattern;o.flags&n.HasIntensity&&o.intensity!==void 0&&(a=a.map(l=>Math.round(l*o.intensity))),this.mobileVibrationProcessor.vibrate(a);break}case t.MobileCancel:{if(!this.mobileVibrationProcessor)break;this.mobileVibrationProcessor.cancel();break}case t.GamepadVibrate:{if(!this.gamepadVibrationProcessor)break;let o=s,a={duration:o.duration,strongMagnitude:o.strongMagnitude/255,weakMagnitude:o.weakMagnitude/255,startDelay:o.startDelay};if(o.flags&i.AllGamepads)for(let l=0;l<4;l++)this.gamepadVibrationProcessor.vibrate(l,a);else this.gamepadVibrationProcessor.vibrate(o.gamepadIndex,a);break}case t.GamepadCancel:{if(!this.gamepadVibrationProcessor)break;let o=s;o.flags&i.AllGamepads?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(o.gamepadIndex);break}}}applyAudioOrders(e){if(!this.audioProcessor||this.mode==="server")return;let{AudioOrderType:t,AudioTargetType:n}=(D1(),ul(P1)),{PlaySoundFlags:i}=(F1(),ul(O1));for(let s of e)switch(s.type){case t.PlaySound:case t.PlayGlobalSound:{let o=s,a=o.volume!==void 0?o.volume/255:void 0,l=o.pitch!==void 0?.25*Math.pow(2,o.pitch/64):void 0,u=o.fadeIn!==void 0?o.fadeIn/10:void 0,c=(o.flags&i.Loop)!==0,d=o.posX!==void 0&&o.posY!==void 0?{x:o.posX,y:o.posY}:void 0;this.audioProcessor.play(o.soundId,{volume:a,pitch:l,loop:c,fadeIn:u,position:d,instanceId:o.instanceId,lowpass:o.lowpass,highpass:o.highpass,reverb:o.reverb});break}case t.StopSound:{let o=s;o.targetType===n.All?this.audioProcessor.stopAll():o.targetType===n.InstanceId?this.audioProcessor.stop(o.target):this.audioProcessor.stop(o.target);break}case t.FadeOutSound:{let o=s,a=o.duration/10;o.targetType===n.All?this.audioProcessor.fadeOut("all",a):this.audioProcessor.fadeOut(o.target,a);break}case t.PauseSound:{let o=s;o.targetType===n.All?this.audioProcessor.pause("all"):this.audioProcessor.pause(o.target);break}case t.ResumeSound:{let o=s;o.targetType===n.All?this.audioProcessor.resume("all"):this.audioProcessor.resume(o.target);break}case t.SetListenerPosition:{let o=s;this.audioProcessor.setListenerPosition(o.x,o.y);break}case t.ConfigureSpatial:{let o=s;this.audioProcessor.configureSpatial({maxDistance:o.maxDistance*100,referenceDistance:o.referenceDistance*100,rolloffFactor:o.rolloffFactor/100,panSpread:o.panSpread/255});break}case t.SetSoundEffects:{let o=s;this.audioProcessor.setEffects(o.instanceId,o.lowpass,o.highpass,o.reverb);break}}}handleAudioAck(e){switch(e.type){case"sound-loaded":this.loadedSounds.set(e.soundId,{name:e.name,loadedAt:Date.now()}),this.soundLoadErrors.delete(e.soundId);break;case"sound-error":this.soundLoadErrors.set(e.soundId,{name:e.name,error:e.error,at:Date.now()});break;case"playback-started":this.playingSounds.set(e.instanceId,{soundId:e.soundId,startedAt:Date.now()});break;case"playback-ended":this.playingSounds.delete(e.instanceId);break;case"playback-error":e.instanceId!==void 0&&this.playingSounds.delete(e.instanceId);break}}isSoundLoaded(e){return this.loadedSounds.has(e)}getSoundLoadError(e){var t;return(t=this.soundLoadErrors.get(e))==null?void 0:t.error}getLoadedSounds(){return this.loadedSounds}getSoundLoadErrors(){return this.soundLoadErrors}isSoundPlaying(e){return this.playingSounds.has(e)}getPlayingSounds(){return this.playingSounds}getPlayingSoundCount(){return this.playingSounds.size}getAudioLoadingState(e){let t=this.loadedSounds.size,n=this.soundLoadErrors.size,i=e>0&&t>=e,s=Array.from(this.soundLoadErrors.values()).map(o=>o.name);return{loadedCount:t,totalExpected:e,errorCount:n,isComplete:i,errors:s}}loadMacro(e,t){let n={...t,id:e},i=this.macroRegistry.registerMacro(n);return this.mode==="client"&&this.macroEngine.loadTemplate(i,n),i}createInstance(e){return this.updateLayerMappings(),this.macroRegistry.createInstance(e)}updateInstance(e,t){return this.macroRegistry.updateInstance(e,t)}removeInstance(e){return this.macroEventHandlers.delete(e),this.macroRegistry.removeInstance(e)}onMacroEvent(e,t,n){this.macroEventHandlers.has(e)||this.macroEventHandlers.set(e,new Map),this.macroEventHandlers.get(e).set(t,n)}offMacroEvent(e,t){var n;t?(n=this.macroEventHandlers.get(e))==null||n.delete(t):this.macroEventHandlers.delete(e)}handleMacroEvent(e){let t=this.macroRegistry.getInstanceName(e.instanceId);if(!t){console.warn(`MacroEvent: Unknown instance ID ${e.instanceId}`);return}let n=this.macroEventHandlers.get(t);if(!n)return;let i,s;switch(e.type){case 1:i="click",s=void 0;break;case 2:i="change",s=e.value;break;case 3:i="submit",s=e.text;break;case 4:i="select",s=e.index;break;default:return}let o=n.get(i);o&&o(s)}flushMacroOrders(){return this.macroRegistry.flushPendingOrders()}hasPendingMacroOrders(){return this.macroRegistry.hasPendingOrders()}applyMacroOrders(e){for(let t of e)this.macroEngine.applyOrder(t)}getMacroRegistry(){return this.macroRegistry}getMacroLoads(){return this.macroRegistry.toAllMacroLoads()}updateLayerMappings(){for(let e of this.layers){let t=e.getName();t&&this.macroRegistry.setLayerMapping(t,e.getId())}}registerLayerName(e,t){this.macroRegistry.setLayerMapping(e,t.getId())}loadMacroTemplate(e,t){this.macroEngine.loadTemplate(e,t)}updateMacros(){return this.macroEngine.update()}processMacroEvents(e){for(let t of e.events){let n=this.macroRegistry.getInstanceName(t.instanceId);if(!n)continue;let i=this.macroEventHandlers.get(n);if(!i)continue;let s=i.get(t.event);s&&s(t.data)}}updateMacroMouse(e,t,n){let i=this.displays.find(s=>s.getId()===this.mouseDisplayId);if(!i&&this.displays.length>0&&(i=this.displays[0]),i){let s=i.getOrigin(),o=e+s.x,a=t+s.y;this.macroEngine.updateMouse(o,a,n)}else this.macroEngine.updateMouse(e,t,n)}getMacroRenderOrders(){let e=this.macroEngine.getOrdersByLayer(),t=this.displays[0];if(!t)return e;let n=t.getOrigin();if(n.x===0&&n.y===0)return e;let i=new Map;for(let[s,o]of e){let a=o.map(l=>{let u={...l};return"posX"in u&&typeof u.posX=="number"&&(u.posX=u.posX-n.x),"posY"in u&&typeof u.posY=="number"&&(u.posY=u.posY-n.y),u});i.set(s,a)}return i}getMacroEffectOffset(){return this.macroEngine.getEffectOffset()}getMacroEngine(){return this.macroEngine}macroFocusNext(){this.macroEngine.focusNext()}macroFocusPrevious(){this.macroEngine.focusPrevious()}macroActivateFocused(){this.macroEngine.activateFocused()}setPostProcess(e,t){let n=JSON.stringify(t),i=JSON.stringify(this.currentPostProcessConfig);n!==i&&(this.currentPostProcessConfig=t,this.postProcessCommands.push({type:"set-config",displayId:e,config:t??void 0}))}setScanlinesEnabled(e,t){var n;if(t){let i=(n=this.currentPostProcessConfig)==null?void 0:n.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:(i==null?void 0:i.opacity)??Ge.scanlines.opacity,pattern:(i==null?void 0:i.pattern)??Ge.scanlines.pattern,color:(i==null?void 0:i.color)??Ge.scanlines.color}})}else this.setPostProcess(e,{scanlines:{enabled:!1}})}setScanlinesOpacity(e,t){var s;let n=Math.max(0,Math.min(1,t)),i=(s=this.currentPostProcessConfig)==null?void 0:s.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:n,pattern:(i==null?void 0:i.pattern)??"horizontal",color:(i==null?void 0:i.color)??{r:0,g:0,b:0}}})}setScanlinesPattern(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.scanlines;this.setPostProcess(e,{scanlines:{enabled:(n==null?void 0:n.enabled)??!0,opacity:(n==null?void 0:n.opacity)??Ge.scanlines.opacity,pattern:t,color:(n==null?void 0:n.color)??{r:0,g:0,b:0}}})}setAmbientEffect(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.ambientEffect;typeof t=="boolean"?this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:t,blur:(n==null?void 0:n.blur)??Ge.ambientEffect.blur,scale:(n==null?void 0:n.scale)??Ge.ambientEffect.scale}}):this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:t.blur??(n==null?void 0:n.blur)??Ge.ambientEffect.blur,scale:t.scale??(n==null?void 0:n.scale)??Ge.ambientEffect.scale}})}setAmbientEffectEnabled(e,t){this.setAmbientEffect(e,t)}setAmbientEffectBlur(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:(n==null?void 0:n.enabled)??!0,blur:Math.max(0,t),scale:(n==null?void 0:n.scale)??Ge.ambientEffect.scale}})}setAmbientEffectScale(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:(n==null?void 0:n.enabled)??!0,blur:(n==null?void 0:n.blur)??Ge.ambientEffect.blur,scale:Math.max(1,t)}})}isAmbientEffectEnabled(){var e,t;return((t=(e=this.currentPostProcessConfig)==null?void 0:e.ambientEffect)==null?void 0:t.enabled)??!1}getAmbientEffectConfig(){var t;let e=(t=this.currentPostProcessConfig)==null?void 0:t.ambientEffect;return e?{enabled:e.enabled,blur:e.blur??Ge.ambientEffect.blur,scale:e.scale??Ge.ambientEffect.scale}:null}getPostProcessConfig(){return this.currentPostProcessConfig}hasPostProcessCommands(){return this.postProcessCommands.length>0}flushPostProcessCommands(){let e=this.postProcessCommands;return this.postProcessCommands=[],e}setScalingMode(e,t){this.currentScalingModes.get(e)!==t&&(this.currentScalingModes.set(e,t),this.postProcessCommands.push({type:"set-scaling-mode",displayId:e,scalingMode:t}))}getScalingMode(e){return this.currentScalingModes.get(e)??null}setCellSize(e,t,n){let i=Math.max(1,Math.min(255,Math.round(t))),s=Math.max(1,Math.min(255,Math.round(n))),o=this.currentCellSizes.get(e);o&&o.width===i&&o.height===s||(this.currentCellSizes.set(e,{width:i,height:s}),this.postProcessCommands.push({type:"set-cell-size",displayId:e,cellWidth:i,cellHeight:s}))}getCellSize(e){let t=this.currentCellSizes.get(e);return{cellWidth:(t==null?void 0:t.width)??8,cellHeight:(t==null?void 0:t.height)??8}}setGrid(e,t){let n;typeof t=="boolean"?n={enabled:t,color:js.color,lineWidth:js.lineWidth}:n={enabled:t.enabled,color:t.color??js.color,lineWidth:t.lineWidth??js.lineWidth},this.currentGridConfigs.set(e,n),this.postProcessCommands.push({type:"set-grid",displayId:e,gridConfig:n})}setGridEnabled(e,t){this.setGrid(e,t)}isGridEnabled(e){var t;return((t=this.currentGridConfigs.get(e))==null?void 0:t.enabled)??!1}getGridConfig(e){return this.currentGridConfigs.get(e)??null}switchPalette(e,t){if(t<0||t>255)throw new Error(`Palette slot ID must be between 0 and 255, got ${t}`);this.currentPaletteSlotIds.get(e)!==t&&(this.currentPaletteSlotIds.set(e,t),this.postProcessCommands.push({type:"switch-palette",displayId:e,paletteSlotId:t}))}getCurrentPaletteSlotId(e){return this.currentPaletteSlotIds.get(e)??null}sendBridge(e,t){this.bridgeMessages.push({channel:e,data:t})}getBridgeMessages(){let e=this.bridgeMessages;return this.bridgeMessages=[],e}hasBridgeMessages(){return this.bridgeMessages.length>0}getDebugInfo(){let e=Array.from(this.availableViewports.entries()).map(([t,n])=>({displayId:t,pixelWidth:n.pixelWidth,pixelHeight:n.pixelHeight}));return{id:this.id,name:this.name,bytesSentTotal:this.totalBytesSent,bytesSentTick:this.currentTickBytesSent,availableViewports:e,layers:this.layers.map(t=>t.getDebugInfo()),displays:this.displays.map(t=>t.getDebugInfo())}}};J(cv,"User");var vI=cv,dv=class{constructor(){D(this,"charCodeSize",_1)}encode(e,t=!1){switch(e.type){case 1:return this.encodeCharOrder(e,t);case 2:return this.encodeTextOrder(e);case 23:return this.encodeTextMultilineOrder(e);case 3:return this.encodeSubFrameOrder(e,t);case 4:return this.encodeSubFrameMultiColorOrder(e,t);case 5:return this.encodeFullFrameOrder(e,t);case 6:return this.encodeFullFrameMultiColorOrder(e,t);case 7:return this.encodeSpriteOrder(e);case 8:return this.encodeSpriteMultiColorOrder(e);case 9:return this.encodeColorMapOrder(e);case 10:return this.encodeShapeOrder(e,t);case 11:return this.encodeDotCloudOrder(e,t);case 12:return this.encodeDotCloudMultiColorOrder(e,t);case 17:return this.encodeBitmaskOrder(e,t);case 18:return this.encodeBitmask4Order(e,t);case 24:return this.encodeBitmask16Order(e,t);case 25:return this.encodePolylineOrder(e,t);case 13:return this.encodeSpriteCloudOrder(e);case 14:return this.encodeSpriteCloudMultiColorOrder(e);case 15:return this.encodeSpriteCloudVariedOrder(e);case 16:return this.encodeSpriteCloudVariedMultiColorOrder(e);case 19:return this.encodeFillOrder(e,t);case 20:return this.encodeFillCharOrder(e,t);case 21:return this.encodeFillSpriteOrder(e);case 22:return this.encodeFillSpriteMultiColorOrder(e);default:throw new Error(`Unknown order type: ${e.type}`)}}writeCharCode(e,t,n,i){return i?(e.writeUInt16LE(t,n),n+2):(e.writeUInt8(t,n),n+1)}encodeCharOrder(e,t){let n=ie.allocUnsafe(gx+(t?1:0)),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),i=this.writeCharCode(n,e.charCode,i,t),n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeTextOrder(e){let t=new TextEncoder().encode(e.text),n=ie.allocUnsafe(mx+t.length),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),n.writeUInt8(t.length,i++);for(let s=0;s<t.length;s++)n.writeUInt8(t[s],i++);return n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeTextMultilineOrder(e){let t=new TextEncoder().encode(e.text),n=ie.allocUnsafe(yx+t.length),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),n.writeUInt8(t.length,i++);for(let s=0;s<t.length;s++)n.writeUInt8(t[s],i++);return n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeSubFrameOrder(e,t){let n=e.sizeX*e.sizeY,i=this.charCodeSize(t),s=ie.allocUnsafe(vx+n*i),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.posX,o++),s.writeUInt8(e.posY,o++),s.writeUInt8(e.sizeX-1,o++),s.writeUInt8(e.sizeY-1,o++),s.writeUInt8(e.bgColorCode,o++),s.writeUInt8(e.fgColorCode,o++);for(let a of e.frame)o=this.writeCharCode(s,a,o,t);return s.toUint8Array()}encodeSubFrameMultiColorOrder(e,t){let n=e.sizeX*e.sizeY,i=this.charCodeSize(t),s=ie.allocUnsafe(wx+n*(i+2)),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.posX,o++),s.writeUInt8(e.posY,o++),s.writeUInt8(e.sizeX-1,o++),s.writeUInt8(e.sizeY-1,o++);for(let a of e.frame)o=this.writeCharCode(s,a.charCode,o,t),s.writeUInt8(a.bgColorCode,o++),s.writeUInt8(a.fgColorCode,o++);return s.toUint8Array()}encodeFullFrameOrder(e,t){let n=e.frame.length,i=this.charCodeSize(t),s=ie.allocUnsafe(Cx+n*i),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.bgColorCode,o++),s.writeUInt8(e.fgColorCode,o++);for(let a of e.frame)o=this.writeCharCode(s,a,o,t);return s.toUint8Array()}encodeFullFrameMultiColorOrder(e,t){let n=e.frame.length,i=this.charCodeSize(t),s=ie.allocUnsafe(bx+n*(i+2)),o=0;s.writeUInt8(e.type,o++);for(let a of e.frame)o=this.writeCharCode(s,a.charCode,o,t),s.writeUInt8(a.bgColorCode,o++),s.writeUInt8(a.fgColorCode,o++);return s.toUint8Array()}encodeSpriteOrder(e){let t=ie.allocUnsafe(Sx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.posX,n++),t.writeUInt8(e.posY,n++),t.writeUInt8(e.spriteIndex,n++),t.writeUInt8(e.bgColorCode,n++),t.writeUInt8(e.fgColorCode,n++),t.toUint8Array()}encodeSpriteMultiColorOrder(e){let t=ie.allocUnsafe(xx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.posX,n++),t.writeUInt8(e.posY,n++),t.writeUInt8(e.spriteIndex,n++),t.toUint8Array()}encodeColorMapOrder(e){let t=e.sizeX*e.sizeY,n=ie.allocUnsafe(Ix+t*2),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),n.writeUInt8(e.sizeX-1,i++),n.writeUInt8(e.sizeY-1,i++);for(let s of e.colorData)n.writeUInt8(s.bgColorCode,i++),n.writeUInt8(s.fgColorCode,i++);return n.toUint8Array()}encodeShapeOrder(e,t){let n=this.encodeShapeData(e.shapeType,e.shapeData,t),i=ie.allocUnsafe(kx+n.length),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.shapeType,s++);for(let o=0;o<n.length;o++)i.writeUInt8(n[o],s++);return i.toUint8Array()}encodeShapeData(e,t,n){switch(this.charCodeSize(n),e){case 1:{let i=ie.allocUnsafe(Ex+(n?1:0)),s=0;return i.writeUInt8(t.posX,s++),i.writeUInt8(t.posY,s++),i.writeUInt8(t.width-1,s++),i.writeUInt8(t.height-1,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 2:{let i=ie.allocUnsafe(Mx+(n?1:0)),s=0;return i.writeUInt8(t.centerX,s++),i.writeUInt8(t.centerY,s++),i.writeUInt8(t.radius-1,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 3:{let i=ie.allocUnsafe(Ux+(n?1:0)),s=0;return i.writeUInt8(t.x1,s++),i.writeUInt8(t.y1,s++),i.writeUInt8(t.x2,s++),i.writeUInt8(t.y2,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 4:{let i=ie.allocUnsafe(Ax+(n?1:0)),s=0;return i.writeUInt8(t.centerX,s++),i.writeUInt8(t.centerY,s++),i.writeUInt8(t.radiusX-1,s++),i.writeUInt8(t.radiusY-1,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 5:{let i=ie.allocUnsafe(Tx+(n?1:0)),s=0;return i.writeUInt8(t.x1,s++),i.writeUInt8(t.y1,s++),i.writeUInt8(t.x2,s++),i.writeUInt8(t.y2,s++),i.writeUInt8(t.x3,s++),i.writeUInt8(t.y3,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}default:throw new Error(`Unknown shape type: ${e}`)}}encodeDotCloudOrder(e,t){let n=e.positions.length;this.charCodeSize(t);let i=ie.allocUnsafe(Rx+(t?1:0)+n*2),s=0;i.writeUInt8(e.type,s++),s=this.writeCharCode(i,e.charCode,s,t),i.writeUInt8(e.bgColorCode,s++),i.writeUInt8(e.fgColorCode,s++),i.writeUInt16BE(n,s),s+=2;for(let o of e.positions)i.writeUInt8(o.posX,s++),i.writeUInt8(o.posY,s++);return i.toUint8Array()}encodeDotCloudMultiColorOrder(e,t){let n=e.dots.length,i=this.charCodeSize(t),s=ie.allocUnsafe(Px+n*(i+4)),o=0;s.writeUInt8(e.type,o++),s.writeUInt16BE(n,o),o+=2;for(let a of e.dots)o=this.writeCharCode(s,a.charCode,o,t),s.writeUInt8(a.bgColorCode,o++),s.writeUInt8(a.fgColorCode,o++),s.writeUInt8(a.posX,o++),s.writeUInt8(a.posY,o++);return s.toUint8Array()}encodeBitmaskOrder(e,t){let n=e.mask.length,i=ie.allocUnsafe(Bx+(t?1:0)+n),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.posX,s++),i.writeUInt8(e.posY,s++),i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),s=this.writeCharCode(i,e.charCode,s,t),i.writeUInt8(e.bgColorCode,s++),i.writeUInt8(e.fgColorCode,s++),i.writeUInt8(e.override?1:0,s++);for(let o=0;o<n;o++)i.writeUInt8(e.mask[o],s++);return i.toUint8Array()}encodeBitmask4Order(e,t){let n=e.mask.length;this.charCodeSize(t);let i=ie.allocUnsafe(zx+3*(t?1:0)+n),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.posX,s++),i.writeUInt8(e.posY,s++),i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),i.writeUInt8(e.override?1:0,s++);for(let o of e.variants)s=this.writeCharCode(i,o.charCode,s,t),i.writeUInt8(o.bgColorCode,s++),i.writeUInt8(o.fgColorCode,s++);for(let o=0;o<n;o++)i.writeUInt8(e.mask[o],s++);return i.toUint8Array()}encodeBitmask16Order(e,t){let n=e.mask.length;this.charCodeSize(t);let i=ie.allocUnsafe(Dx+15*(t?1:0)+n),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.posX,s++),i.writeUInt8(e.posY,s++),i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),i.writeUInt8(e.override?1:0,s++);for(let o of e.variants)s=this.writeCharCode(i,o.charCode,s,t),i.writeUInt8(o.bgColorCode,s++),i.writeUInt8(o.fgColorCode,s++);for(let o=0;o<n;o++)i.writeUInt8(e.mask[o],s++);return i.toUint8Array()}encodePolylineOrder(e,t){let n=e.points.length,i=ie.allocUnsafe(Ox+(t?1:0)+n*2),s=0;i.writeUInt8(e.type,s++),s=this.writeCharCode(i,e.charCode,s,t),i.writeUInt8(e.fgColorCode,s++),i.writeUInt8(e.bgColorCode,s++),i.writeUInt8(n,s++);for(let o of e.points)i.writeUInt8(o.x,s++),i.writeUInt8(o.y,s++);return i.toUint8Array()}encodeSpriteCloudOrder(e){let t=e.positions.length,n=ie.allocUnsafe(Fx+t*2),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.spriteIndex,i++),n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.positions)n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeSpriteCloudMultiColorOrder(e){let t=e.positions.length,n=ie.allocUnsafe(Lx+t*2),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.spriteIndex,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.positions)n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeSpriteCloudVariedOrder(e){let t=e.sprites.length,n=ie.allocUnsafe(_x+t*5),i=0;n.writeUInt8(e.type,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.sprites)n.writeUInt8(s.spriteIndex,i++),n.writeUInt8(s.bgColorCode,i++),n.writeUInt8(s.fgColorCode,i++),n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeSpriteCloudVariedMultiColorOrder(e){let t=e.sprites.length,n=ie.allocUnsafe($x+t*3),i=0;n.writeUInt8(e.type,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.sprites)n.writeUInt8(s.spriteIndex,i++),n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeFillOrder(e,t){let n=ie.allocUnsafe(Nx+(t?1:0)),i=0;return n.writeUInt8(e.type,i++),i=this.writeCharCode(n,e.charCode,i,t),n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeFillCharOrder(e,t){let n=e.patternWidth*e.patternHeight,i=this.charCodeSize(t),s=ie.allocUnsafe(Vx+n*i),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.patternWidth-1,o++),s.writeUInt8(e.patternHeight-1,o++),s.writeUInt8(e.bgColorCode,o++),s.writeUInt8(e.fgColorCode,o++);for(let a of e.pattern)o=this.writeCharCode(s,a,o,t);return s.toUint8Array()}encodeFillSpriteOrder(e){let t=ie.allocUnsafe(Hx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.spriteIndex,n++),t.writeUInt8(e.bgColorCode,n++),t.writeUInt8(e.fgColorCode,n++),t.toUint8Array()}encodeFillSpriteMultiColorOrder(e){let t=ie.allocUnsafe(jx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.spriteIndex,n++),t.toUint8Array()}};J(dv,"OrderEncoder");var wI=dv,jg=255,Yg=32,Wg=64,hv=class{constructor(){D(this,"orderEncoder"),this.orderEncoder=new wI}encode(e){let t=e.is16bit;if(e.orders.length>jg)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${jg}. This would cause packet corruption! Split into multiple layers.`);let n=e.orders.map(c=>this.orderEncoder.encode(c,t)),i=13,s=n.reduce((c,d)=>c+d.length,0),o=i+s,a=ie.allocUnsafe(o),l=0;a.writeUInt16BE(e.id,l),l+=2;let u=e.updateFlags;e.isMacroLayer?u|=Yg:u&=~Yg,t?u|=Wg:u&=~Wg,a.writeUInt8(u,l++),a.writeUInt8(e.zIndex,l++),a.writeUInt16BE(e.originX,l),l+=2,a.writeUInt16BE(e.originY,l),l+=2,a.writeUInt16BE(e.width,l),l+=2,a.writeUInt16BE(e.height,l),l+=2,a.writeUInt8(e.orders.length,l++);for(let c of n)ie.from(c).copy(a,l),l+=c.length;return a.toUint8Array()}calculateSize(e){let t=e.is16bit;return 13+e.orders.reduce((n,i)=>n+this.orderEncoder.encode(i,t).length,0)}};J(hv,"LayerEncoder");var CI=hv,fv=class{encode(e){switch(e.type){case 1:return this.encodePlaySoundOrder(e);case 2:return this.encodePlayGlobalSoundOrder(e);case 3:return this.encodeStopSoundOrder(e);case 4:return this.encodeFadeOutSoundOrder(e);case 5:return this.encodePauseSoundOrder(e);case 6:return this.encodeResumeSoundOrder(e);case 7:return this.encodeSetListenerPositionOrder(e);case 8:return this.encodeConfigureSpatialOrder(e);case 9:return this.encodeSetSoundEffectsOrder(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculatePlaySoundSize(e);case 2:return this.calculatePlayGlobalSoundSize(e);case 3:case 5:case 6:return this.calculateTargetOrderSize(e);case 4:return this.calculateFadeOutSize(e);case 7:return zg;case 8:return Dg;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.soundId,i++),n.writeUInt16BE(e.instanceId,i),i+=2,n.writeUInt8(e.flags,i++),e.flags&2&&n.writeUInt8(e.volume??255,i++),e.flags&4&&n.writeUInt8(e.pitch??128,i++),e.flags&8&&n.writeUInt8(e.fadeIn??0,i++),e.flags&16&&(n.writeUInt16BE(e.posX??0,i),i+=2,n.writeUInt16BE(e.posY??0,i),i+=2),e.flags&32&&n.writeUInt8(e.lowpass??0,i++),e.flags&64&&n.writeUInt8(e.highpass??0,i++),e.flags&128&&n.writeUInt8(e.reverb??0,i++),n.toUint8Array()}encodePlayGlobalSoundOrder(e){let t=this.calculatePlayGlobalSoundSize(e),n=ie.allocUnsafe(t),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.soundId,i++),n.writeUInt16BE(e.instanceId,i),i+=2;let s=e.flags&-17;return n.writeUInt8(s,i++),s&2&&n.writeUInt8(e.volume??255,i++),s&4&&n.writeUInt8(e.pitch??128,i++),s&8&&n.writeUInt8(e.fadeIn??0,i++),s&32&&n.writeUInt8(e.lowpass??0,i++),s&64&&n.writeUInt8(e.highpass??0,i++),s&128&&n.writeUInt8(e.reverb??0,i++),n.toUint8Array()}calculatePlaySoundSize(e){let t=Yx;return e.flags&2&&(t+=1),e.flags&4&&(t+=1),e.flags&8&&(t+=1),e.flags&16&&(t+=4),e.flags&32&&(t+=1),e.flags&64&&(t+=1),e.flags&128&&(t+=1),t}calculatePlayGlobalSoundSize(e){let t=Wx,n=e.flags&-17;return n&2&&(t+=1),n&4&&(t+=1),n&8&&(t+=1),n&32&&(t+=1),n&64&&(t+=1),n&128&&(t+=1),t}encodeStopSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodePauseSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeResumeSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeFadeOutSoundOrder(e){let t=this.calculateFadeOutSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.targetType,i++),n.writeUInt8(e.duration,i++),e.targetType===0?n.writeUInt16BE(e.target??0,i):e.targetType===1&&n.writeUInt8(e.target??0,i),n.toUint8Array()}encodeTargetOrder(e,t,n){let i=2;t===0?i+=2:t===1&&(i+=1);let s=ie.allocUnsafe(i),o=0;return s.writeUInt8(e,o++),s.writeUInt8(t,o++),t===0?s.writeUInt16BE(n??0,o):t===1&&s.writeUInt8(n??0,o),s.toUint8Array()}calculateTargetOrderSize(e){let t=2;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}calculateFadeOutSize(e){let t=3;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}encodeSetListenerPositionOrder(e){let t=ie.allocUnsafe(zg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt16BE(e.x,n),n+=2,t.writeUInt16BE(e.y,n),t.toUint8Array()}encodeConfigureSpatialOrder(e){let t=ie.allocUnsafe(Dg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.maxDistance,n++),t.writeUInt8(e.referenceDistance,n++),t.writeUInt8(e.rolloffFactor,n++),t.writeUInt8(e.panSpread,n++),t.toUint8Array()}encodeSetSoundEffectsOrder(e){let t=this.calculateSetSoundEffectsSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt16BE(e.instanceId,i),i+=2,n.writeUInt8(e.flags,i++),e.flags&1&&n.writeUInt8(e.lowpass??0,i++),e.flags&2&&n.writeUInt8(e.highpass??0,i++),e.flags&4&&n.writeUInt8(e.reverb??0,i++),n.toUint8Array()}calculateSetSoundEffectsSize(e){let t=4;return e.flags&1&&(t+=1),e.flags&2&&(t+=1),e.flags&4&&(t+=1),t}};J(fv,"AudioOrderEncoder");var bI=fv,pv=class{encode(e){switch(e.type){case 1:return this.encodeMobileVibrateOrder(e);case 2:return this.encodeMobileCancelOrder(e);case 16:return this.encodeGamepadVibrateOrder(e);case 17:return this.encodeGamepadCancelOrder(e);default:throw new Error(`Unknown vibration order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateMobileVibrateSize(e);case 2:return 1;case 16:return this.calculateGamepadVibrateSize(e);case 17:return 3;default:throw new Error(`Unknown vibration order type: ${e.type}`)}}calculateMobileVibrateSize(e){let t=3+e.pattern.length*2;return e.intensity!==void 0&&(t+=1),t}encodeMobileVibrateOrder(e){let t=this.calculateMobileVibrateSize(e),n=ie.allocUnsafe(t),i=0,s=0;e.intensity!==void 0&&(s|=1),n.writeUInt8(e.type,i++),n.writeUInt8(s,i++),n.writeUInt8(e.pattern.length,i++);for(let o of e.pattern){let a=Math.min(65535,Math.max(0,Math.round(o)));n.writeUInt16BE(a,i),i+=2}if(e.intensity!==void 0){let o=Math.round(Math.min(1,Math.max(0,e.intensity))*255);n.writeUInt8(o,i++)}return n.toUint8Array()}encodeMobileCancelOrder(e){let t=ie.allocUnsafe(1);return t.writeUInt8(2,0),t.toUint8Array()}calculateGamepadVibrateSize(e){let t=7;return e.startDelay!==void 0&&e.startDelay>0&&(t+=2),t}encodeGamepadVibrateOrder(e){let t=this.calculateGamepadVibrateSize(e),n=ie.allocUnsafe(t),i=0,s=0;e.startDelay!==void 0&&e.startDelay>0&&(s|=1),e.gamepadIndex===255&&(s|=2),n.writeUInt8(e.type,i++),n.writeUInt8(s,i++),n.writeUInt8(e.gamepadIndex,i++);let o=Math.min(65535,Math.max(0,Math.round(e.duration)));if(n.writeUInt16BE(o,i),i+=2,n.writeUInt8(e.strongMagnitude,i++),n.writeUInt8(e.weakMagnitude,i++),e.startDelay!==void 0&&e.startDelay>0){let a=Math.min(65535,Math.max(0,Math.round(e.startDelay)));n.writeUInt16BE(a,i),i+=2}return n.toUint8Array()}encodeGamepadCancelOrder(e){let t=ie.allocUnsafe(3),n=0,i=0;return e.gamepadIndex===255&&(i|=2),t.writeUInt8(e.type,n++),t.writeUInt8(i,n++),t.writeUInt8(e.gamepadIndex,n++),t.toUint8Array()}};J(pv,"VibrationOrderEncoder");var SI=pv,gv=class{encode(e){switch(e.type){case 1:return this.encodeCreateInstance(e);case 2:return this.encodeUpdateInstance(e);case 3:return this.encodeRemoveInstance(e);default:throw new Error(`Unknown macro order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateCreateInstanceSize(e);case 2:return this.calculateUpdateInstanceSize(e);case 3:return 2;default:throw new Error(`Unknown macro order type: ${e.type}`)}}encodeCreateInstance(e){let t=JSON.stringify(e.params),n=new TextEncoder().encode(t);if(n.length>65535)throw new Error(`Params JSON too large: ${n.length} bytes (max 65535)`);let i=11+n.length,s=ie.allocUnsafe(i),o=0;return s.writeUInt8(e.type,o++),s.writeUInt8(e.instanceId,o++),s.writeUInt8(e.macroId,o++),s.writeUInt8(e.layerId,o++),s.writeInt16BE(e.x,o),o+=2,s.writeInt16BE(e.y,o),o+=2,s.writeUInt8(e.tabIndex,o++),s.writeUInt16BE(n.length,o),o+=2,s.toUint8Array().set(n,o),s.toUint8Array()}calculateCreateInstanceSize(e){let t=JSON.stringify(e.params);return 11+new TextEncoder().encode(t).length}encodeUpdateInstance(e){let t=JSON.stringify(e.params),n=new TextEncoder().encode(t);if(n.length>65535)throw new Error(`Params JSON too large: ${n.length} bytes (max 65535)`);let i=4+n.length,s=ie.allocUnsafe(i),o=0;return s.writeUInt8(e.type,o++),s.writeUInt8(e.instanceId,o++),s.writeUInt16BE(n.length,o),o+=2,s.toUint8Array().set(n,o),s.toUint8Array()}calculateUpdateInstanceSize(e){let t=JSON.stringify(e.params);return 4+new TextEncoder().encode(t).length}encodeRemoveInstance(e){let t=ie.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};J(gv,"MacroOrderEncoder");var xI=gv,Xr=(r=>(r[r.SetConfig=1]="SetConfig",r[r.SetScanlines=2]="SetScanlines",r[r.SetAmbientEffect=3]="SetAmbientEffect",r[r.SetScalingMode=4]="SetScalingMode",r[r.SetGrid=5]="SetGrid",r[r.SwitchPalette=6]="SwitchPalette",r[r.SetCellSize=7]="SetCellSize",r))(Xr||{}),mv=class{encode(e){switch(e.type){case 1:return this.encodeSetConfigOrder(e);case 2:return this.encodeSetScanlinesOrder(e);case 3:return this.encodeSetAmbientEffectOrder(e);case 4:return this.encodeSetScalingModeOrder(e);case 5:return this.encodeSetGridOrder(e);case 6:return this.encodeSwitchPaletteOrder(e);case 7:return this.encodeSetCellSizeOrder(e);default:throw new Error(`Unknown post-process order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateSetConfigSize(e);case 2:return Og;case 3:return Fg;case 4:return Lg;case 5:return _g;case 6:return $g;case 7:return Ng;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.displayId,i++),n.writeUInt8(e.flags,i++),e.flags&1&&e.scanlines&&(n.writeUInt8(e.scanlines.enabled?1:0,i++),n.writeUInt8(Math.round(e.scanlines.opacity*255),i++),n.writeUInt8(e.scanlines.pattern,i++),n.writeUInt8(e.scanlines.colorR,i++),n.writeUInt8(e.scanlines.colorG,i++),n.writeUInt8(e.scanlines.colorB,i++)),e.flags&2&&e.ambientEffect&&(n.writeUInt8(e.ambientEffect.enabled?1:0,i++),n.writeUInt8(Math.min(255,Math.round(e.ambientEffect.blur)),i++),n.writeUInt8(Math.min(255,Math.max(100,Math.round(e.ambientEffect.scale*100))),i++),n.writeUInt8(Math.round(e.ambientEffect.opacity*255),i++)),n.toUint8Array()}calculateSetConfigSize(e){let t=Gx;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=ie.allocUnsafe(Og),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.enabled?1:0,n++),t.writeUInt8(Math.round(e.opacity*255),n++),t.writeUInt8(e.pattern,n++),t.writeUInt8(e.colorR,n++),t.writeUInt8(e.colorG,n++),t.writeUInt8(e.colorB,n++),t.toUint8Array()}encodeSetAmbientEffectOrder(e){let t=ie.allocUnsafe(Fg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.enabled?1:0,n++),t.writeUInt8(Math.min(255,Math.round(e.blur)),n++),t.writeUInt8(Math.min(255,Math.max(100,Math.round(e.scale*100))),n++),t.writeUInt8(Math.round(e.opacity*255),n++),t.toUint8Array()}encodeSetScalingModeOrder(e){let t=ie.allocUnsafe(Lg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.mode,n++),t.toUint8Array()}encodeSetGridOrder(e){let t=ie.allocUnsafe(_g),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.enabled?1:0,n++),t.writeUInt8(e.colorR,n++),t.writeUInt8(e.colorG,n++),t.writeUInt8(e.colorB,n++),t.writeUInt8(e.colorA,n++),t.writeUInt8(Math.min(10,Math.max(1,e.lineWidth)),n++),t.toUint8Array()}encodeSwitchPaletteOrder(e){let t=ie.allocUnsafe($g),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.slotId,n++),t.toUint8Array()}encodeSetCellSizeOrder(e){let t=ie.allocUnsafe(Ng),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.cellWidth,n++),t.writeUInt8(e.cellHeight,n++),t.toUint8Array()}};J(mv,"PostProcessOrderEncoder");var II=mv,Gg=4,Fc=4,Xg=8,yv=class{encode(e){var o;let t=((o=e.renderPasses)==null?void 0:o.length)??0;if(t>Fc)throw new Error(`renderPasses supports up to ${Fc} entries, got ${t}`);let n=Xg+t*Gg,i=ie.allocUnsafe(n),s=0;if(i.writeUInt8(e.id,s++),i.writeUInt16BE(e.originX,s),s+=2,i.writeUInt16BE(e.originY,s),s+=2,i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),i.writeUInt8(t,s++),t>0&&e.renderPasses)for(let a of e.renderPasses){let l=Math.max(0,Math.min(255,a.id)),u=Math.max(0,Math.min(255,a.zMin)),c=Math.max(0,Math.min(255,a.zMax)),d=a.enabled===!1?0:1;i.writeUInt8(l,s++),i.writeUInt8(u,s++),i.writeUInt8(c,s++),i.writeUInt8(d,s++)}return i.toUint8Array()}calculateSize(e){var n;let t=Math.min(((n=e.renderPasses)==null?void 0:n.length)??0,Fc);return Xg+t*Gg}};J(yv,"DisplayEncoder");var kI=yv,vv=class{constructor(){D(this,"layerEncoder"),D(this,"audioOrderEncoder"),D(this,"vibrationOrderEncoder"),D(this,"macroOrderEncoder"),D(this,"postProcessOrderEncoder"),D(this,"displayEncoder"),this.layerEncoder=new CI,this.audioOrderEncoder=new bI,this.vibrationOrderEncoder=new SI,this.macroOrderEncoder=new xI,this.postProcessOrderEncoder=new II,this.displayEncoder=new kI}encode(e){let t=e.layers.map(z=>this.layerEncoder.encode(z)),n=e.audioOrders||[],i=n.map(z=>this.audioOrderEncoder.encode(z)),s=e.vibrationOrders||[],o=s.map(z=>this.vibrationOrderEncoder.encode(z)),a=e.macroOrders||[],l=a.map(z=>this.macroOrderEncoder.encode(z)),u=e.postProcessOrders||[],c=u.map(z=>this.postProcessOrderEncoder.encode(z)),d=9,h=e.displays.reduce((z,P)=>z+this.displayEncoder.calculateSize(P),0),f=2,p=t.reduce((z,P)=>z+P.length,0),m=1,S=i.reduce((z,P)=>z+P.length,0),w=1,g=o.reduce((z,P)=>z+P.length,0),y=1,C=l.reduce((z,P)=>z+P.length,0),x=1,I=c.reduce((z,P)=>z+P.length,0),E=d+h+f+p+m+S+w+g+y+C+x+I,A=ie.allocUnsafe(E),R=0,F=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);A.writeBigUInt64BE(F,R),R+=8,A.writeUInt8(e.displays.length,R),R+=1;for(let z of e.displays){let P=this.displayEncoder.encode(z);ie.from(P).copy(A,R),R+=P.length}A.writeUInt16BE(e.layers.length,R),R+=2;for(let z of t)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(n.length,R),R+=1;for(let z of i)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(s.length,R),R+=1;for(let z of o)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(a.length,R),R+=1;for(let z of l)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(u.length,R),R+=1;for(let z of c)ie.from(z).copy(A,R),R+=z.length;return A.toUint8Array()}calculateSize(e){let t=e.displays.reduce((f,p)=>f+this.displayEncoder.calculateSize(p),0),n=2,i=e.layers.reduce((f,p)=>f+this.layerEncoder.calculateSize(p),0),s=1,o=(e.audioOrders||[]).reduce((f,p)=>f+this.audioOrderEncoder.calculateSize(p),0),a=1,l=(e.vibrationOrders||[]).reduce((f,p)=>f+this.vibrationOrderEncoder.calculateSize(p),0),u=1,c=(e.macroOrders||[]).reduce((f,p)=>f+this.macroOrderEncoder.calculateSize(p),0),d=1,h=(e.postProcessOrders||[]).reduce((f,p)=>f+this.postProcessOrderEncoder.calculateSize(p),0);return 9+t+n+i+s+o+a+l+u+c+d+h}static createEmptyPacket(e){return{tick:typeof e=="bigint"?Number(e):e,displayCount:0,displays:[],layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]}}encodeEmpty(e){let t=ie.allocUnsafe(15),n=typeof e=="bigint"?e:BigInt(e);return t.writeBigUInt64BE(n,0),t.writeUInt8(0,8),t.writeUInt16BE(0,9),t.writeUInt8(0,11),t.writeUInt8(0,12),t.writeUInt8(0,13),t.writeUInt8(0,14),t.toUint8Array()}};J(vv,"UpdatePacketEncoder");var EI=vv,MI=(r=>(r[r.ColorPalette=1]="ColorPalette",r[r.Sprite=2]="Sprite",r[r.MulticolorSprite=3]="MulticolorSprite",r[r.Sound=5]="Sound",r[r.Macro=7]="Macro",r[r.ImageFont=8]="ImageFont",r[r.ImageFontBlock=9]="ImageFontBlock",r))(MI||{}),wv=class{encode(e){let t=JSON.stringify(e.template),n=new TextEncoder().encode(t);if(n.length>65535)throw new Error(`Macro template JSON too large: ${n.length} bytes (max 65535)`);let i=4+n.length,s=ie.allocUnsafe(i),o=0;return s.writeUInt8(7,o++),s.writeUInt8(e.macroId,o++),s.writeUInt16BE(n.length,o),o+=2,s.toUint8Array().set(n,o),s.toUint8Array()}calculateSize(e){let t=JSON.stringify(e.template);return 4+new TextEncoder().encode(t).length}};J(wv,"MacroLoadEncoder");var UI=wv,Cv=class{encode(e){switch(e.loadType){case 1:return this.encodeColorPalette(e);case 2:return this.encodeSprite(e);case 3:return this.encodeMulticolorSprite(e);case 5:return this.encodeSound(e);case 8:return this.encodeImageFont(e);case 9:return this.encodeImageFontBlock(e);default:throw new Error(`Unknown load type: ${e.loadType}`)}}encodeColorPalette(e){let t=e.colors.length;if(t>255)throw new Error(`Palette size ${t} exceeds maximum of 255`);let n=e.slotId!==void 0,i=n?4:3,s=ie.allocUnsafe(i+t*6),o=0;s.writeUInt8(1,o++),s.writeUInt8(n?255:0,o++),n&&s.writeUInt8(e.slotId,o++),s.writeUInt8(t,o++);for(let a of e.colors)s.writeUInt8(a.colorId,o++),s.writeUInt8(a.r,o++),s.writeUInt8(a.g,o++),s.writeUInt8(a.b,o++),s.writeUInt8(a.a??255,o++),s.writeUInt8(a.e??0,o++);return s.toUint8Array()}encodeSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let n=2;for(let o of e.sprites)n+=3,n+=o.data.length;let i=ie.allocUnsafe(n),s=0;i.writeUInt8(2,s++),i.writeUInt8(t,s++);for(let o of e.sprites){if(o.data.length!==o.sizeX*o.sizeY)throw new Error(`Sprite ${o.spriteId}: data length ${o.data.length} does not match size ${o.sizeX}x${o.sizeY}`);i.writeUInt8(o.spriteId,s++),i.writeUInt8(o.sizeX,s++),i.writeUInt8(o.sizeY,s++);for(let a of o.data)i.writeUInt8(a,s++)}return i.toUint8Array()}encodeMulticolorSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let n=2;for(let o of e.sprites)n+=3,n+=o.data.length*3;let i=ie.allocUnsafe(n),s=0;i.writeUInt8(3,s++),i.writeUInt8(t,s++);for(let o of e.sprites){if(o.data.length!==o.sizeX*o.sizeY)throw new Error(`Sprite ${o.spriteId}: data length ${o.data.length} does not match size ${o.sizeX}x${o.sizeY}`);i.writeUInt8(o.spriteId,s++),i.writeUInt8(o.sizeX,s++),i.writeUInt8(o.sizeY,s++);for(let a of o.data)i.writeUInt8(a.charCode,s++),i.writeUInt8(a.fgColorId,s++),i.writeUInt8(a.bgColorId,s++)}return i.toUint8Array()}encodeSound(e){let t=e.sounds.length;if(t>255)throw new Error(`Sound count ${t} exceeds maximum of 255`);let n=2;for(let o of e.sounds){if(o.midiData.length>65535)throw new Error(`Sound ${o.soundId}: MIDI data size ${o.midiData.length} exceeds maximum of 65535 bytes`);n+=3,n+=o.midiData.length}let i=ie.allocUnsafe(n),s=0;i.writeUInt8(5,s++),i.writeUInt8(t,s++);for(let o of e.sounds){i.writeUInt8(o.soundId,s++),i.writeUInt16BE(o.midiData.length,s),s+=2;for(let a=0;a<o.midiData.length;a++)i.writeUInt8(o.midiData[a],s++)}return i.toUint8Array()}encodeImageFont(e){if(![1,4,16].includes(e.atlasBlocks))throw new Error(`Invalid atlasBlocks value: ${e.atlasBlocks}. Must be 1, 4, or 16.`);let t=ie.allocUnsafe(6),n=0;return t.writeUInt8(8,n++),t.writeUInt8(e.glyphWidth,n++),t.writeUInt8(e.glyphHeight,n++),t.writeUInt8(e.cellWidth,n++),t.writeUInt8(e.cellHeight,n++),t.writeUInt8(e.atlasBlocks,n++),t.toUint8Array()}encodeImageFontBlock(e){let t=6+e.imageData.length,n=ie.allocUnsafe(t),i=0;n.writeUInt8(9,i++),n.writeUInt8(e.blockIndex,i++),n.writeUInt32LE(e.imageData.length,i),i+=4;for(let s=0;s<e.imageData.length;s++)n.writeUInt8(e.imageData[s],i++);return n.toUint8Array()}};J(Cv,"LoadEncoder");var Lc=Cv,bv=class{decode(e,t=0){let n=t,i=e.readUInt8(t++);if(i!==7)throw new Error(`Expected LoadType.Macro (0x07), got 0x${i.toString(16)}`);let s=e.readUInt8(t++),o=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+o);t+=o;let l=new TextDecoder().decode(a),u=JSON.parse(l);return{load:{loadType:7,macroId:s,template:u},bytesRead:t-n}}};J(bv,"MacroLoadDecoder");var AI=bv,Sv=class{decode(e,t=0){let n=ie.from(e);if(t>=n.length)throw new Error("Buffer too short to decode load type");let i=n.readUInt8(t);switch(i){case 1:return this.decodeColorPalette(n,t);case 2:return this.decodeSprite(n,t);case 3:return this.decodeMulticolorSprite(n,t);case 5:return this.decodeSound(n,t);case 7:return this.decodeMacro(n,t);case 8:return this.decodeImageFont(n,t);case 9:return this.decodeImageFontBlock(n,t);default:throw new Error(`Unknown load type: 0x${i.toString(16)}`)}}decodeColorPalette(e,t){let n=t;this.checkSize(e,t,3,"ColorPalette header"),e.readUInt8(t++);let i=e.readUInt8(t++)===255,s;i&&(this.checkSize(e,t,1,"ColorPalette slotId"),s=e.readUInt8(t++));let o=e.readUInt8(t++);this.checkSize(e,t,o*6,`ColorPalette ${o} colors`);let a=[];for(let l=0;l<o;l++)a.push({colorId:e.readUInt8(t++),r:e.readUInt8(t++),g:e.readUInt8(t++),b:e.readUInt8(t++),a:e.readUInt8(t++),e:e.readUInt8(t++)});return{load:{loadType:1,...s!==void 0&&{slotId:s},colors:a},bytesRead:t-n}}decodeSprite(e,t){let n=t;this.checkSize(e,t,2,"Sprite header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=[];for(let o=0;o<i;o++){this.checkSize(e,t,3,`Sprite ${o} header`);let a=e.readUInt8(t++),l=e.readUInt8(t++),u=e.readUInt8(t++),c=l*u;this.checkSize(e,t,c,`Sprite ${o} data`);let d=[];for(let h=0;h<c;h++)d.push(e.readUInt8(t++));s.push({spriteId:a,sizeX:l,sizeY:u,data:d})}return{load:{loadType:2,sprites:s},bytesRead:t-n}}decodeMulticolorSprite(e,t){let n=t;this.checkSize(e,t,2,"MulticolorSprite header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=[];for(let o=0;o<i;o++){this.checkSize(e,t,3,`MulticolorSprite ${o} header`);let a=e.readUInt8(t++),l=e.readUInt8(t++),u=e.readUInt8(t++),c=l*u;this.checkSize(e,t,c*3,`MulticolorSprite ${o} data`);let d=[];for(let h=0;h<c;h++)d.push({charCode:e.readUInt8(t++),fgColorId:e.readUInt8(t++),bgColorId:e.readUInt8(t++)});s.push({spriteId:a,sizeX:l,sizeY:u,data:d})}return{load:{loadType:3,sprites:s},bytesRead:t-n}}decodeSound(e,t){let n=t;this.checkSize(e,t,2,"Sound header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=[];for(let o=0;o<i;o++){this.checkSize(e,t,3,`Sound ${o} header`);let a=e.readUInt8(t++),l=e.readUInt16BE(t);t+=2,this.checkSize(e,t,l,`Sound ${o} MIDI data`);let u=new Uint8Array(l);for(let c=0;c<l;c++)u[c]=e.readUInt8(t++);s.push({soundId:a,midiData:u})}return{load:{loadType:5,sounds:s},bytesRead:t-n}}checkSize(e,t,n,i){if(t+n>e.length)throw new Error(`Buffer too short for ${i}: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes remaining`)}decodeMacro(e,t){return new AI().decode(e,t)}decodeImageFont(e,t){let n=t;this.checkSize(e,t,6,"ImageFont header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt8(t++),a=e.readUInt8(t++),l=e.readUInt8(t++);if(![1,4,16].includes(l))throw new Error(`Invalid atlasBlocks value: ${l}. Must be 1, 4, or 16.`);return{load:{loadType:8,glyphWidth:i,glyphHeight:s,cellWidth:o,cellHeight:a,atlasBlocks:l},bytesRead:t-n}}decodeImageFontBlock(e,t){let n=t;this.checkSize(e,t,2,"ImageFontBlock header"),e.readUInt8(t++);let i=e.readUInt8(t++);this.checkSize(e,t,4,"ImageFontBlock data size");let s=e.readUInt32LE(t);t+=4,this.checkSize(e,t,s,"ImageFontBlock data");let o=new Uint8Array(s);for(let a=0;a<s;a++)o[a]=e.readUInt8(t++);return{load:{loadType:9,blockIndex:i,imageData:o},bytesRead:t-n}}};J(Sv,"LoadDecoder");var TI=Sv,RI=4,Kg=4,Zg=8,xv=class{decode(e,t=0){this.checkSize(e,t,Zg);let n=t,i=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let o=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++)+1,l=e.readUInt8(n++)+1,u=e.readUInt8(n++);if(u>Kg)throw new Error(`Invalid renderPass count: ${u} (max ${Kg})`);let c=u*RI;this.checkSize(e,n,c);let d=[];for(let h=0;h<u;h++){let f=e.readUInt8(n++),p=e.readUInt8(n++),m=e.readUInt8(n++),S=e.readUInt8(n++);d.push({id:f,zMin:p,zMax:m,enabled:(S&1)!==0})}return{display:{id:i,originX:s,originY:o,sizeX:a,sizeY:l,renderPasses:d.length>0?d:void 0},bytesRead:Zg+c}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for display: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(xv,"DisplayDecoder");var PI=xv,Iv=class{constructor(){D(this,"charCodeSize",_1)}decode(e,t=0,n=!1){if(t>=e.length)throw new Error("Buffer too short to decode order type");let i=e.readUInt8(t);switch(i){case 1:return this.decodeCharOrder(e,t,n);case 2:return this.decodeTextOrder(e,t);case 23:return this.decodeTextMultilineOrder(e,t);case 3:return this.decodeSubFrameOrder(e,t,n);case 4:return this.decodeSubFrameMultiColorOrder(e,t,n);case 5:return this.decodeFullFrameOrder(e,t,n);case 6:return this.decodeFullFrameMultiColorOrder(e,t,n);case 7:return this.decodeSpriteOrder(e,t);case 8:return this.decodeSpriteMultiColorOrder(e,t);case 9:return this.decodeColorMapOrder(e,t);case 10:return this.decodeShapeOrder(e,t,n);case 11:return this.decodeDotCloudOrder(e,t,n);case 12:return this.decodeDotCloudMultiColorOrder(e,t,n);case 17:return this.decodeBitmaskOrder(e,t,n);case 18:return this.decodeBitmask4Order(e,t,n);case 24:return this.decodeBitmask16Order(e,t,n);case 25:return this.decodePolylineOrder(e,t,n);case 13:return this.decodeSpriteCloudOrder(e,t);case 14:return this.decodeSpriteCloudMultiColorOrder(e,t);case 15:return this.decodeSpriteCloudVariedOrder(e,t);case 16:return this.decodeSpriteCloudVariedMultiColorOrder(e,t);case 19:return this.decodeFillOrder(e,t,n);case 20:return this.decodeFillCharOrder(e,t,n);case 21:return this.decodeFillSpriteOrder(e,t);case 22:return this.decodeFillSpriteMultiColorOrder(e,t);default:throw new Error(`Unknown order type: 0x${i.toString(16)}`)}}readCharCode(e,t,n){return n?[e.readUInt16LE(t),t+2]:[e.readUInt8(t),t+1]}decodeCharOrder(e,t,n){let i=5+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),[l,u]=this.readCharCode(e,s,n);s=u;let c=e.readUInt8(s++),d=e.readUInt8(s++);return{order:{type:1,posX:o,posY:a,charCode:l,bgColorCode:c,fgColorCode:d},bytesRead:i}}decodeTextOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n+3);this.checkSize(e,t,5+i);let s=e.subarray(n+4,n+4+i),o=new TextDecoder().decode(s.toUint8Array());return{order:{type:2,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),text:o,bgColorCode:e.readUInt8(n+4+i),fgColorCode:e.readUInt8(n+5+i)},bytesRead:6+i}}decodeTextMultilineOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n+3);this.checkSize(e,t,5+i);let s=e.subarray(n+4,n+4+i),o=new TextDecoder().decode(s.toUint8Array());return{order:{type:23,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),text:o,bgColorCode:e.readUInt8(n+4+i),fgColorCode:e.readUInt8(n+5+i)},bytesRead:6+i}}decodeSubFrameOrder(e,t,n){this.checkSize(e,t,7);let i=t,s=this.charCodeSize(n),o=e.readUInt8(i+3)+1,a=e.readUInt8(i+4)+1,l=o*a;this.checkSize(e,t,7+l*s);let u=[],c=i+7;for(let d=0;d<l;d++){let[h,f]=this.readCharCode(e,c,n);u.push(h),c=f}return{order:{type:3,posX:e.readUInt8(i+1),posY:e.readUInt8(i+2),sizeX:o,sizeY:a,bgColorCode:e.readUInt8(i+5),fgColorCode:e.readUInt8(i+6),frame:u},bytesRead:7+l*s}}decodeSubFrameMultiColorOrder(e,t,n){this.checkSize(e,t,5);let i=t,s=this.charCodeSize(n),o=e.readUInt8(i+3)+1,a=e.readUInt8(i+4)+1,l=o*a,u=s+2;this.checkSize(e,t,5+l*u);let c=[],d=i+5;for(let h=0;h<l;h++){let[f,p]=this.readCharCode(e,d,n);d=p,c.push({charCode:f,bgColorCode:e.readUInt8(d++),fgColorCode:e.readUInt8(d++)})}return{order:{type:4,posX:e.readUInt8(i+1),posY:e.readUInt8(i+2),sizeX:o,sizeY:a,frame:c},bytesRead:5+l*u}}decodeFullFrameOrder(e,t,n,i){this.checkSize(e,t,3);let s=t,o=this.charCodeSize(n),a=i||Math.floor((e.length-t-3)/o);this.checkSize(e,t,3+a*o);let l=[],u=s+3;for(let c=0;c<a;c++){let[d,h]=this.readCharCode(e,u,n);l.push(d),u=h}return{order:{type:5,bgColorCode:e.readUInt8(s+1),fgColorCode:e.readUInt8(s+2),frame:l},bytesRead:3+a*o}}decodeFullFrameMultiColorOrder(e,t,n,i){this.checkSize(e,t,1);let s=t,o=this.charCodeSize(n)+2,a=i||Math.floor((e.length-t-1)/o);this.checkSize(e,t,1+a*o);let l=[],u=s+1;for(let c=0;c<a;c++){let[d,h]=this.readCharCode(e,u,n);u=h,l.push({charCode:d,bgColorCode:e.readUInt8(u++),fgColorCode:e.readUInt8(u++)})}return{order:{type:6,frame:l},bytesRead:1+a*o}}decodeSpriteOrder(e,t){this.checkSize(e,t,6);let n=t;return{order:{type:7,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),spriteIndex:e.readUInt8(n+3),bgColorCode:e.readUInt8(n+4),fgColorCode:e.readUInt8(n+5)},bytesRead:6}}decodeSpriteMultiColorOrder(e,t){this.checkSize(e,t,4);let n=t;return{order:{type:8,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),spriteIndex:e.readUInt8(n+3)},bytesRead:4}}decodeColorMapOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n+3)+1,s=e.readUInt8(n+4)+1,o=i*s;this.checkSize(e,t,5+o*2);let a=[];for(let l=0;l<o;l++){let u=n+5+l*2;a.push({bgColorCode:e.readUInt8(u),fgColorCode:e.readUInt8(u+1)})}return{order:{type:9,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:s,colorData:a},bytesRead:5+o*2}}decodeShapeOrder(e,t,n){this.checkSize(e,t,2);let i=t,s=e.readUInt8(i+1),{shapeData:o,bytesRead:a}=this.decodeShapeData(e,i+2,s,n);return{order:{type:10,shapeType:s,shapeData:o},bytesRead:2+a}}decodeShapeData(e,t,n,i){let s=t,o=this.charCodeSize(i);switch(n){case 1:{let a=7+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++)+1,d=e.readUInt8(s++)+1,h=e.readUInt8(s++)===1,[f,p]=this.readCharCode(e,s,i);s=p;let m=e.readUInt8(s++),S=e.readUInt8(s++);return{shapeData:{posX:l,posY:u,width:c,height:d,filled:h,charCode:f,bgColorCode:m,fgColorCode:S},bytesRead:a}}case 2:{let a=6+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++)+1,d=e.readUInt8(s++)===1,[h,f]=this.readCharCode(e,s,i);s=f;let p=e.readUInt8(s++),m=e.readUInt8(s++);return{shapeData:{centerX:l,centerY:u,radius:c,filled:d,charCode:h,bgColorCode:p,fgColorCode:m},bytesRead:a}}case 3:{let a=6+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++),d=e.readUInt8(s++),[h,f]=this.readCharCode(e,s,i);s=f;let p=e.readUInt8(s++),m=e.readUInt8(s++);return{shapeData:{x1:l,y1:u,x2:c,y2:d,charCode:h,bgColorCode:p,fgColorCode:m},bytesRead:a}}case 4:{let a=7+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++)+1,d=e.readUInt8(s++)+1,h=e.readUInt8(s++)===1,[f,p]=this.readCharCode(e,s,i);s=p;let m=e.readUInt8(s++),S=e.readUInt8(s++);return{shapeData:{centerX:l,centerY:u,radiusX:c,radiusY:d,filled:h,charCode:f,bgColorCode:m,fgColorCode:S},bytesRead:a}}case 5:{let a=9+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++),d=e.readUInt8(s++),h=e.readUInt8(s++),f=e.readUInt8(s++),p=e.readUInt8(s++)===1,[m,S]=this.readCharCode(e,s,i);s=S;let w=e.readUInt8(s++),g=e.readUInt8(s++);return{shapeData:{x1:l,y1:u,x2:c,y2:d,x3:h,y3:f,filled:p,charCode:m,bgColorCode:w,fgColorCode:g},bytesRead:a}}default:throw new Error(`Unknown shape type: ${n}`)}}decodeDotCloudOrder(e,t,n){let i=1+this.charCodeSize(n)+2+2;this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let[o,a]=this.readCharCode(e,s,n);s=a;let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt16BE(s);s+=2,this.checkSize(e,t,i+c*2);let d=[];for(let h=0;h<c;h++)d.push({posX:e.readUInt8(s++),posY:e.readUInt8(s++)});return{order:{type:11,charCode:o,bgColorCode:l,fgColorCode:u,positions:d},bytesRead:i+c*2}}decodeDotCloudMultiColorOrder(e,t,n){this.checkSize(e,t,3);let i=this.charCodeSize(n),s=t,o=e.readUInt16BE(s+1),a=i+4;this.checkSize(e,t,3+o*a);let l=[],u=s+3;for(let c=0;c<o;c++){let[d,h]=this.readCharCode(e,u,n);u=h,l.push({charCode:d,bgColorCode:e.readUInt8(u++),fgColorCode:e.readUInt8(u++),posX:e.readUInt8(u++),posY:e.readUInt8(u++)})}return{order:{type:12,dots:l},bytesRead:3+o*a}}decodeBitmaskOrder(e,t,n){let i=8+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),l=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,[c,d]=this.readCharCode(e,s,n);s=d;let h=e.readUInt8(s++),f=e.readUInt8(s++),p=e.readUInt8(s++)===1,m=Math.ceil(l*u/8);this.checkSize(e,t,i+m);let S=new Uint8Array(m);for(let w=0;w<m;w++)S[w]=e.readUInt8(s+w);return{order:{type:17,posX:o,posY:a,sizeX:l,sizeY:u,charCode:c,bgColorCode:h,fgColorCode:f,override:p,mask:S},bytesRead:i+m}}decodeBitmask4Order(e,t,n){let i=6+3*(this.charCodeSize(n)+2);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),l=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,c=e.readUInt8(s++)===1,d=Math.ceil(l*u/4);this.checkSize(e,t,i+d);let h=[];for(let p=0;p<3;p++){let[m,S]=this.readCharCode(e,s,n);s=S,h.push({charCode:m,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let f=new Uint8Array(d);for(let p=0;p<d;p++)f[p]=e.readUInt8(s+p);return{order:{type:18,posX:o,posY:a,sizeX:l,sizeY:u,override:c,variants:h,mask:f},bytesRead:i+d}}decodeBitmask16Order(e,t,n){let i=6+15*(this.charCodeSize(n)+2);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),l=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,c=e.readUInt8(s++)===1,d=Math.ceil(l*u/2);this.checkSize(e,t,i+d);let h=[];for(let p=0;p<15;p++){let[m,S]=this.readCharCode(e,s,n);s=S,h.push({charCode:m,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let f=new Uint8Array(d);for(let p=0;p<d;p++)f[p]=e.readUInt8(s+p);return{order:{type:24,posX:o,posY:a,sizeX:l,sizeY:u,override:c,variants:h,mask:f},bytesRead:i+d}}decodePolylineOrder(e,t,n){let i=4+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let[o,a]=this.readCharCode(e,s,n);s=a;let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++);this.checkSize(e,t,i+c*2);let d=[];for(let h=0;h<c;h++)d.push({x:e.readUInt8(s++),y:e.readUInt8(s++)});return{order:{type:25,charCode:o,fgColorCode:l,bgColorCode:u,points:d},bytesRead:i+c*2}}decodeSpriteCloudOrder(e,t){this.checkSize(e,t,6);let n=t,i=e.readUInt16BE(n+4);this.checkSize(e,t,6+i*2);let s=[];for(let o=0;o<i;o++){let a=n+6+o*2;s.push({posX:e.readUInt8(a),posY:e.readUInt8(a+1)})}return{order:{type:13,spriteIndex:e.readUInt8(n+1),bgColorCode:e.readUInt8(n+2),fgColorCode:e.readUInt8(n+3),positions:s},bytesRead:6+i*2}}decodeSpriteCloudMultiColorOrder(e,t){this.checkSize(e,t,4);let n=t,i=e.readUInt16BE(n+2);this.checkSize(e,t,4+i*2);let s=[];for(let o=0;o<i;o++){let a=n+4+o*2;s.push({posX:e.readUInt8(a),posY:e.readUInt8(a+1)})}return{order:{type:14,spriteIndex:e.readUInt8(n+1),positions:s},bytesRead:4+i*2}}decodeSpriteCloudVariedOrder(e,t){this.checkSize(e,t,3);let n=t,i=e.readUInt16BE(n+1);this.checkSize(e,t,3+i*5);let s=[];for(let o=0;o<i;o++){let a=n+3+o*5;s.push({spriteIndex:e.readUInt8(a),bgColorCode:e.readUInt8(a+1),fgColorCode:e.readUInt8(a+2),posX:e.readUInt8(a+3),posY:e.readUInt8(a+4)})}return{order:{type:15,sprites:s},bytesRead:3+i*5}}decodeSpriteCloudVariedMultiColorOrder(e,t){this.checkSize(e,t,3);let n=t,i=e.readUInt16BE(n+1);this.checkSize(e,t,3+i*3);let s=[];for(let o=0;o<i;o++){let a=n+3+o*3;s.push({spriteIndex:e.readUInt8(a),posX:e.readUInt8(a+1),posY:e.readUInt8(a+2)})}return{order:{type:16,sprites:s},bytesRead:3+i*3}}decodeFillOrder(e,t,n){let i=3+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let[o,a]=this.readCharCode(e,s,n);s=a;let l=e.readUInt8(s++),u=e.readUInt8(s++);return{order:{type:19,charCode:o,bgColorCode:l,fgColorCode:u},bytesRead:i}}decodeFillCharOrder(e,t,n){this.checkSize(e,t,5);let i=this.charCodeSize(n),s=t,o=e.readUInt8(s+1)+1,a=e.readUInt8(s+2)+1,l=o*a,u=5+l*i;this.checkSize(e,t,u);let c=[],d=s+5;for(let h=0;h<l;h++){let[f,p]=this.readCharCode(e,d,n);c.push(f),d=p}return{order:{type:20,patternWidth:o,patternHeight:a,bgColorCode:e.readUInt8(s+3),fgColorCode:e.readUInt8(s+4),pattern:c},bytesRead:u}}decodeFillSpriteOrder(e,t){this.checkSize(e,t,4);let n=t;return{order:{type:21,spriteIndex:e.readUInt8(n+1),bgColorCode:e.readUInt8(n+2),fgColorCode:e.readUInt8(n+3)},bytesRead:4}}decodeFillSpriteMultiColorOrder(e,t){this.checkSize(e,t,2);let n=t;return{order:{type:22,spriteIndex:e.readUInt8(n+1)},bytesRead:2}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(Iv,"OrderDecoder");var BI=Iv,zI=32,DI=64,kv=class{constructor(){D(this,"orderDecoder"),this.orderDecoder=new BI}decode(e,t=0){this.checkSize(e,t,13);let n=t,i=e.readUInt16BE(n);n+=2;let s=e.readUInt8(n++),o=e.readUInt8(n++),a=e.readUInt16BE(n);n+=2;let l=e.readUInt16BE(n);n+=2;let u=e.readUInt16BE(n);n+=2;let c=e.readUInt16BE(n);n+=2;let d=e.readUInt8(n++),h=(s&zI)!==0,f=(s&DI)!==0,p=[],m=n;for(let S=0;S<d;S++){let w=this.orderDecoder.decode(e,m,f);p.push(w.order),m+=w.bytesRead}return{layer:{id:i,updateFlags:s,zIndex:o,originX:a,originY:l,width:u,height:c,orderCount:d,orders:p,isMacroLayer:h,is16bit:f},bytesRead:m-t}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for layer: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(kv,"LayerDecoder");var OI=kv,Ev=class{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode audio order type");let n=e.readUInt8(t);switch(n){case 1:return this.decodePlaySoundOrder(e,t);case 2:return this.decodePlayGlobalSoundOrder(e,t);case 3:return this.decodeStopSoundOrder(e,t);case 4:return this.decodeFadeOutSoundOrder(e,t);case 5:return this.decodePauseSoundOrder(e,t);case 6:return this.decodeResumeSoundOrder(e,t);case 7:return this.decodeSetListenerPositionOrder(e,t);case 8:return this.decodeConfigureSpatialOrder(e,t);case 9:return this.decodeSetSoundEffectsOrder(e,t);default:throw new Error(`Unknown audio order type: 0x${n.toString(16)}`)}}decodePlaySoundOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++),l={type:i,soundId:s,instanceId:o,flags:a};return a&2&&(this.checkSize(e,n,1),l.volume=e.readUInt8(n++)),a&4&&(this.checkSize(e,n,1),l.pitch=e.readUInt8(n++)),a&8&&(this.checkSize(e,n,1),l.fadeIn=e.readUInt8(n++)),a&16&&(this.checkSize(e,n,4),l.posX=e.readUInt16BE(n),n+=2,l.posY=e.readUInt16BE(n),n+=2),a&32&&(this.checkSize(e,n,1),l.lowpass=e.readUInt8(n++)),a&64&&(this.checkSize(e,n,1),l.highpass=e.readUInt8(n++)),a&128&&(this.checkSize(e,n,1),l.reverb=e.readUInt8(n++)),{order:l,bytesRead:n-t}}decodePlayGlobalSoundOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++),l={type:i,soundId:s,instanceId:o,flags:a};return a&2&&(this.checkSize(e,n,1),l.volume=e.readUInt8(n++)),a&4&&(this.checkSize(e,n,1),l.pitch=e.readUInt8(n++)),a&8&&(this.checkSize(e,n,1),l.fadeIn=e.readUInt8(n++)),a&32&&(this.checkSize(e,n,1),l.lowpass=e.readUInt8(n++)),a&64&&(this.checkSize(e,n,1),l.highpass=e.readUInt8(n++)),a&128&&(this.checkSize(e,n,1),l.reverb=e.readUInt8(n++)),{order:l,bytesRead:n-t}}decodeStopSoundOrder(e,t){this.checkSize(e,t,2);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o={type:i,targetType:s};return s===0?(this.checkSize(e,n,2),o.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),o.target=e.readUInt8(n++)),{order:o,bytesRead:n-t}}decodeFadeOutSoundOrder(e,t){this.checkSize(e,t,3);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++),a={type:i,targetType:s,duration:o};return s===0?(this.checkSize(e,n,2),a.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),a.target=e.readUInt8(n++)),{order:a,bytesRead:n-t}}decodePauseSoundOrder(e,t){this.checkSize(e,t,2);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o={type:i,targetType:s};return s===0?(this.checkSize(e,n,2),o.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),o.target=e.readUInt8(n++)),{order:o,bytesRead:n-t}}decodeResumeSoundOrder(e,t){this.checkSize(e,t,2);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o={type:i,targetType:s};return s===0?(this.checkSize(e,n,2),o.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),o.target=e.readUInt8(n++)),{order:o,bytesRead:n-t}}decodeSetListenerPositionOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let o=e.readUInt16BE(n);return n+=2,{order:{type:i,x:s,y:o},bytesRead:5}}decodeConfigureSpatialOrder(e,t){this.checkSize(e,t,5);let n=t;return{order:{type:e.readUInt8(n),maxDistance:e.readUInt8(n+1),referenceDistance:e.readUInt8(n+2),rolloffFactor:e.readUInt8(n+3),panSpread:e.readUInt8(n+4)},bytesRead:5}}decodeSetSoundEffectsOrder(e,t){this.checkSize(e,t,4);let n=t,i=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let o=e.readUInt8(n++),a={type:i,instanceId:s,flags:o};return o&1&&(this.checkSize(e,n,1),a.lowpass=e.readUInt8(n++)),o&2&&(this.checkSize(e,n,1),a.highpass=e.readUInt8(n++)),o&4&&(this.checkSize(e,n,1),a.reverb=e.readUInt8(n++)),{order:a,bytesRead:n-t}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for audio order: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(Ev,"AudioOrderDecoder");var FI=Ev,Mv=class{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode vibration order type");let n=e.readUInt8(t);switch(n){case 1:return this.decodeMobileVibrateOrder(e,t);case 2:return this.decodeMobileCancelOrder(e,t);case 16:return this.decodeGamepadVibrateOrder(e,t);case 17:return this.decodeGamepadCancelOrder(e,t);default:throw new Error(`Unknown vibration order type: 0x${n.toString(16)}`)}}decodeMobileVibrateOrder(e,t){let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++),a=[];for(let u=0;u<o;u++)a.push(e.readUInt16BE(n)),n+=2;let l={type:i,flags:s,pattern:a};return s&1&&(l.intensity=e.readUInt8(n++)/255),{order:l,bytesRead:n-t}}decodeMobileCancelOrder(e,t){return{order:{type:2},bytesRead:1}}decodeGamepadVibrateOrder(e,t){let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++),a=e.readUInt16BE(n);n+=2;let l=e.readUInt8(n++),u=e.readUInt8(n++),c={type:i,flags:s,gamepadIndex:o,duration:a,strongMagnitude:l,weakMagnitude:u};return s&1&&(c.startDelay=e.readUInt16BE(n),n+=2),{order:c,bytesRead:n-t}}decodeGamepadCancelOrder(e,t){let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++);return{order:{type:i,flags:s,gamepadIndex:o},bytesRead:n-t}}};J(Mv,"VibrationOrderDecoder");var LI=Mv,Uv=class{decode(e,t=0){let n=e.readUInt8(t);switch(n){case 1:return this.decodeCreateInstance(e,t);case 2:return this.decodeUpdateInstance(e,t);case 3:return this.decodeRemoveInstance(e,t);default:throw new Error(`Unknown macro order type: 0x${n.toString(16)}`)}}decodeAll(e,t,n){let i=[],s=0;for(let o=0;o<n;o++){let{order:a,bytesRead:l}=this.decode(e,t+s);i.push(a),s+=l}return{orders:i,bytesRead:s}}decodeCreateInstance(e,t){let n=t,i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt8(t++),a=e.readUInt8(t++),l=e.readInt16BE(t);t+=2;let u=e.readInt16BE(t);t+=2;let c=e.readUInt8(t++),d=e.readUInt16BE(t);t+=2;let h=e.toUint8Array().subarray(t,t+d);t+=d;let f=new TextDecoder().decode(h),p=JSON.parse(f);return{order:{type:i,instanceId:s,macroId:o,layerId:a,x:l,y:u,tabIndex:c,params:p},bytesRead:t-n}}decodeUpdateInstance(e,t){let n=t,i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+o);t+=o;let l=new TextDecoder().decode(a),u=JSON.parse(l);return{order:{type:i,instanceId:s,params:u},bytesRead:t-n}}decodeRemoveInstance(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1);return{order:{type:n,instanceId:i},bytesRead:2}}};J(Uv,"MacroOrderDecoder");var _I=Uv,Av=class{decode(e,t){let n=e[t];switch(n){case 1:return this.decodeSetConfigOrder(e,t);case 2:return this.decodeSetScanlinesOrder(e,t);case 3:return this.decodeSetAmbientEffectOrder(e,t);case 4:return this.decodeSetScalingModeOrder(e,t);case 5:return this.decodeSetGridOrder(e,t);case 6:return this.decodeSwitchPaletteOrder(e,t);case 7:return this.decodeSetCellSizeOrder(e,t);default:throw new Error(`Unknown post-process order type: ${n}`)}}decodeSetConfigOrder(e,t){let n=t,i=e[n++],s=e[n++],o=e[n++],a={type:i,displayId:s,flags:o};return o&1&&(a.scanlines={enabled:e[n++]===1,opacity:e[n++]/255,pattern:e[n++],colorR:e[n++],colorG:e[n++],colorB:e[n++]}),o&2&&(a.ambientEffect={enabled:e[n++]===1,blur:e[n++],scale:e[n++]/100,opacity:e[n++]/255}),{order:a,bytesRead:n-t}}decodeSetScanlinesOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],enabled:e[n++]===1,opacity:e[n++]/255,pattern:e[n++],colorR:e[n++],colorG:e[n++],colorB:e[n++]},bytesRead:n-t}}decodeSetAmbientEffectOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],enabled:e[n++]===1,blur:e[n++],scale:e[n++]/100,opacity:e[n++]/255},bytesRead:n-t}}decodeSetScalingModeOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],mode:e[n++]},bytesRead:n-t}}decodeSetGridOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],enabled:e[n++]===1,colorR:e[n++],colorG:e[n++],colorB:e[n++],colorA:e[n++],lineWidth:e[n++]},bytesRead:n-t}}decodeSwitchPaletteOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],slotId:e[n++]},bytesRead:n-t}}decodeSetCellSizeOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],cellWidth:e[n++],cellHeight:e[n++]},bytesRead:n-t}}};J(Av,"PostProcessOrderDecoder");var $I=Av,Tv=class{constructor(){D(this,"displayDecoder"),D(this,"layerDecoder"),D(this,"audioOrderDecoder"),D(this,"vibrationOrderDecoder"),D(this,"macroOrderDecoder"),D(this,"postProcessOrderDecoder"),this.displayDecoder=new PI,this.layerDecoder=new OI,this.audioOrderDecoder=new FI,this.vibrationOrderDecoder=new LI,this.macroOrderDecoder=new _I,this.postProcessOrderDecoder=new $I}decode(e,t=0){let n=ie.from(e);this.checkSize(n,t,15);let i=t,s=Number(n.readBigUInt64BE(i));i+=8;let o=n.readUInt8(i);i+=1;let a=[],l=0;for(let A=0;A<o;A++){let R=this.displayDecoder.decode(n,i);a.push(R.display),i+=R.bytesRead,l+=R.bytesRead}this.checkSize(n,i,2);let u=n.readUInt16BE(i);i+=2;let c=[],d=0;for(let A=0;A<u;A++){let R=this.layerDecoder.decode(n,i);c.push({...R.layer,byteSize:R.bytesRead}),i+=R.bytesRead,d+=R.bytesRead}this.checkSize(n,i,1);let h=n.readUInt8(i);i+=1;let f=[],p=0;for(let A=0;A<h;A++){let R=this.audioOrderDecoder.decode(n,i);f.push(R.order),i+=R.bytesRead,p+=R.bytesRead}this.checkSize(n,i,1);let m=n.readUInt8(i);i+=1;let S=[],w=0;for(let A=0;A<m;A++){let R=this.vibrationOrderDecoder.decode(n,i);S.push(R.order),i+=R.bytesRead,w+=R.bytesRead}this.checkSize(n,i,1);let g=n.readUInt8(i);i+=1;let y=[],C=0;for(let A=0;A<g;A++){let R=this.macroOrderDecoder.decode(n,i);y.push(R.order),i+=R.bytesRead,C+=R.bytesRead}this.checkSize(n,i,1);let x=n.readUInt8(i);i+=1;let I=[],E=0;for(let A=0;A<x;A++){let R=this.postProcessOrderDecoder.decode(n.toUint8Array(),i);I.push(R.order),i+=R.bytesRead,E+=R.bytesRead}return{tick:s,displayCount:o,displays:a,layerCount:u,layers:c,audioOrderCount:h,audioOrders:f,vibrationOrderCount:m,vibrationOrders:S,macroOrderCount:g,macroOrders:y,postProcessOrderCount:x,postProcessOrders:I,__byteSizes:{displays:l,layers:d,audioOrders:p,vibrationOrders:w,macroOrders:C,postProcessOrders:E}}}isValid(e,t=0){let n=ie.from(e);try{return this.checkSize(n,t,15),!0}catch{return!1}}decodeHeader(e,t=0){let n=ie.from(e);this.checkSize(n,t,13);let i=t,s=Number(n.readBigUInt64BE(i));i+=8;let o=n.readUInt8(i);i+=1;for(let l=0;l<o;l++){let u=this.displayDecoder.decode(n,i);i+=u.bytesRead}this.checkSize(n,i,2);let a=n.readUInt16BE(i);return{tick:s,displayCount:o,layerCount:a}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for update packet: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(Tv,"UpdatePacketDecoder");var NI=Tv,nh=class Ts{constructor(e){this.engine=e,D(this,"colorCache",new Array(256)),D(this,"cellsBuffer",[]),D(this,"opacityBuffer",new Uint8Array(0)),D(this,"visibleLayersBuffer",[]),D(this,"visibleLayerIdsBuffer",[]),D(this,"passCellsBuffers",[]),D(this,"passOpacityBuffers",[]),this.rebuildColorCache()}static getChar(e){let t=Ts.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),Ts.charCache.set(e,t)),t}getLastVisibleLayerIds(){return this.visibleLayerIdsBuffer}rebuildColorCache(){for(let e=0;e<256;e++){let t=this.engine.getColor(e);t?this.colorCache[e]={r:t.r,g:t.g,b:t.b,a:t.a}:this.colorCache[e]={r:0,g:0,b:0,a:0}}}getColorRGB(e){return this.colorCache[e]??this.colorCache[255]}getColorEmission(e){let t=this.engine.getColor(e);return t?t.e:0}isLayerVisible(e,t){let n=e.x,i=e.x+e.width,s=e.y,o=e.y+e.height,a=t.x,l=t.x+256,u=t.y,c=t.y+256;return!(i<=a||n>=l||o<=u||s>=c)}rasterize(e,t,n){let i=this.normalizePasses(n);return this.rasterizeMultiPass(e,t,i)}rasterizeSinglePass(e,t){let n=e.width*e.height,i=this.cellsBuffer;i.length=n;for(let u=0;u<n;u++)i[u]?(i[u].char=" ",i[u].fgColorIndex=255,i[u].bgColorIndex=255,i[u].fgEmission=0,i[u].bgEmission=0):i[u]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<n?this.opacityBuffer=new Uint8Array(n):this.opacityBuffer.fill(0,0,n);let s=this.opacityBuffer,o=this.visibleLayersBuffer;o.length=0;for(let u=0;u<t.length;u++){let c=t[u];c.isEnabled()&&this.isLayerVisible(e,c.getOrigin())&&o.push(c)}o.sort((u,c)=>c.getZOrder()-u.getZOrder());let a=this.visibleLayerIdsBuffer;a.length=o.length;for(let u=0;u<o.length;u++)a[u]=o[u].getId();for(let u=0;u<e.height;u++)for(let c=0;c<e.width;c++){let d=u*e.width+c;if(s[d])continue;let h=e.x+c,f=e.y+u;for(let p=0;p<o.length;p++){let m=o[p],S=h-m.getOrigin().x,w=f-m.getOrigin().y,g=m.getWidth(),y=m.getHeight();if(S<0||S>=g||w<0||w>=y)continue;let C=w*g+S,x=m.getData(),I=x.getCharCode(C),E=x.getFgColorCode(C),A=x.getBgColorCode(C),R=i[d];if(I!==0&&R.char===" "&&(R.char=Ts.getChar(I)),E!==255&&R.fgColorIndex===255&&(R.fgColorIndex=E,R.fgEmission=this.getColorEmission(E)),A!==255){R.bgColorIndex===255&&(R.bgColorIndex=A,R.bgEmission=this.getColorEmission(A)),s[d]=1;break}}}let l=new Array(n);for(let u=0;u<n;u++)l[u]={char:i[u].char,fgColorIndex:i[u].fgColorIndex,bgColorIndex:i[u].bgColorIndex,fgEmission:i[u].fgEmission,bgEmission:i[u].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:l,palette:this.colorCache}}rasterizeMultiPass(e,t,n){let i=e.width*e.height;this.ensurePassBuffers(n.length,i),this.visibleLayerIdsBuffer.length=0;let s=this.visibleLayersBuffer;s.length=0;for(let c=0;c<t.length;c++){let d=t[c];d.isEnabled()&&this.isLayerVisible(e,d.getOrigin())&&s.push(d)}s.sort((c,d)=>d.getZOrder()-c.getZOrder());for(let c=0;c<n.length;c++){let d=n[c],h=this.passCellsBuffers[c],f=this.preparePassBuffers(h,this.passOpacityBuffers[c],i);this.passOpacityBuffers[c]=f;let p=[];for(let S=0;S<s.length;S++){let w=s[S],g=w.getZOrder();g<d.zMin||g>d.zMax||p.push(w)}let m=this.visibleLayerIdsBuffer.length;for(let S=0;S<p.length;S++)this.visibleLayerIdsBuffer[m+S]=p[S].getId();this.composePass(e,p,h,f)}let o=this.cellsBuffer,a=this.preparePassBuffers(o,this.opacityBuffer,i);this.opacityBuffer=a;let l=new Array(i),u=[];for(let c=0;c<n.length;c++){let d=this.passCellsBuffers[c],h=new Array(i);for(let f=0;f<i;f++){let p=d[f];h[f]={char:p.char,fgColorIndex:p.fgColorIndex,bgColorIndex:p.bgColorIndex,fgEmission:p.fgEmission,bgEmission:p.bgEmission}}u.push({id:n[c].id,zMin:n[c].zMin,zMax:n[c].zMax,cells:h})}for(let c=0;c<i;c++){let d=o[c];for(let h=n.length-1;h>=0;h--){let f=this.passCellsBuffers[h][c];if(d.char===" "&&f.char!==" "&&(d.char=f.char),d.fgColorIndex===255&&f.fgColorIndex!==255&&(d.fgColorIndex=f.fgColorIndex,d.fgEmission=f.fgEmission),f.bgColorIndex!==255){d.bgColorIndex===255&&(d.bgColorIndex=f.bgColorIndex,d.bgEmission=f.bgEmission);break}}l[c]={char:d.char,fgColorIndex:d.fgColorIndex,bgColorIndex:d.bgColorIndex,fgEmission:d.fgEmission,bgEmission:d.bgEmission}}return{id:e.id,width:e.width,height:e.height,cells:l,palette:this.colorCache,passes:u}}composePass(e,t,n,i){let s=e.width,o=e.height;for(let a=0;a<o;a++)for(let l=0;l<s;l++){let u=a*s+l;if(i[u])continue;let c=e.x+l,d=e.y+a;for(let h=0;h<t.length;h++){let f=t[h],p=c-f.getOrigin().x,m=d-f.getOrigin().y,S=f.getWidth(),w=f.getHeight();if(p<0||p>=S||m<0||m>=w)continue;let g=m*S+p,y=f.getData(),C=y.getCharCode(g),x=y.getFgColorCode(g),I=y.getBgColorCode(g),E=n[u];if(C!==0&&E.char===" "&&(E.char=Ts.getChar(C)),x!==255&&E.fgColorIndex===255&&(E.fgColorIndex=x,E.fgEmission=this.getColorEmission(x)),I!==255){E.bgColorIndex===255&&(E.bgColorIndex=I,E.bgEmission=this.getColorEmission(I)),i[u]=1;break}}}}preparePassBuffers(e,t,n){e.length=n;for(let i=0;i<n;i++)e[i]?(e[i].char=" ",e[i].fgColorIndex=255,e[i].bgColorIndex=255,e[i].fgEmission=0,e[i].bgEmission=0):e[i]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};return t.length<n?t=new Uint8Array(n):t.fill(0,0,n),t}ensurePassBuffers(e,t){for(;this.passCellsBuffers.length<e;)this.passCellsBuffers.push([]);for(;this.passOpacityBuffers.length<e;)this.passOpacityBuffers.push(new Uint8Array(t));this.passCellsBuffers.length>e&&(this.passCellsBuffers.length=e),this.passOpacityBuffers.length>e&&(this.passOpacityBuffers.length=e);for(let n=0;n<e;n++)this.passOpacityBuffers[n].length<t?this.passOpacityBuffers[n]=new Uint8Array(t):this.passOpacityBuffers[n].fill(0,0,t)}normalizePasses(e){let t={id:0,zMin:0,zMax:255,enabled:!0};if(!e||e.length===0)return[t];let n=e.filter(i=>i.enabled!==!1);return n.length===0?[t]:n.slice(0,4)}rasterizeWithSortedLayers(e,t){let n=e.width*e.height,i=this.cellsBuffer;i.length=n;for(let l=0;l<n;l++)i[l]?(i[l].char=" ",i[l].fgColorIndex=255,i[l].bgColorIndex=255,i[l].fgEmission=0,i[l].bgEmission=0):i[l]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<n?this.opacityBuffer=new Uint8Array(n):this.opacityBuffer.fill(0,0,n);let s=this.opacityBuffer,o=this.visibleLayersBuffer;o.length=0;for(let l=0;l<t.length;l++){let u=t[l];this.isLayerVisible(e,u.getOrigin())&&o.push(u)}for(let l=0;l<e.height;l++)for(let u=0;u<e.width;u++){let c=l*e.width+u;if(s[c])continue;let d=e.x+u,h=e.y+l;for(let f=0;f<o.length;f++){let p=o[f],m=d-p.getOrigin().x,S=h-p.getOrigin().y,w=p.getWidth(),g=p.getHeight();if(m<0||m>=w||S<0||S>=g)continue;let y=S*w+m,C=p.getData(),x=C.getCharCode(y),I=C.getFgColorCode(y),E=C.getBgColorCode(y),A=i[c];if(x!==0&&A.char===" "&&(A.char=Ts.getChar(x)),I!==255&&A.fgColorIndex===255&&(A.fgColorIndex=I,A.fgEmission=this.getColorEmission(I)),E!==255){A.bgColorIndex===255&&(A.bgColorIndex=E,A.bgEmission=this.getColorEmission(E)),s[c]=1;break}}}let a=new Array(n);for(let l=0;l<n;l++)a[l]={char:i[l].char,fgColorIndex:i[l].fgColorIndex,bgColorIndex:i[l].bgColorIndex,fgEmission:i[l].fgEmission,bgEmission:i[l].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:a,palette:this.colorCache}}calculateIntersection(e,t){let n=e.x,i=e.x+e.width,s=e.y,o=e.y+e.height,a=t.x,l=t.x+256,u=t.y,c=t.y+256,d=Math.max(n,a),h=Math.min(i,l),f=Math.max(s,u),p=Math.min(o,c);return{visible:d<h&&f<p,originStart:{x:d-e.x,y:f-e.y},originEnd:{x:h-e.x,y:p-e.y},layerStart:{x:d-t.x,y:f-t.y},layerEnd:{x:h-t.x,y:p-t.y}}}};J(nh,"DisplayRasterizer"),D(nh,"charCache",(()=>{let r=new Map;for(let e=0;e<256;e++)r.set(e,String.fromCharCode(e));return r})());var VI=nh,Rv=class{constructor(){D(this,"enabled",!1),D(this,"currentStats",null)}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get tick(){var e;return((e=this.currentStats)==null?void 0:e.tick)??0}get timestamp(){var e;return((e=this.currentStats)==null?void 0:e.timestamp)??0}get totalOrders(){var e;return((e=this.currentStats)==null?void 0:e.totalOrders)??0}get ordersByLayer(){var e;return((e=this.currentStats)==null?void 0:e.ordersByLayer)??new Map}get ordersByType(){var e;return((e=this.currentStats)==null?void 0:e.ordersByType)??new Map}get totalLayers(){var e;return((e=this.currentStats)==null?void 0:e.totalLayers)??0}get visibleLayers(){var e;return((e=this.currentStats)==null?void 0:e.visibleLayers)??0}get layersPerDisplay(){var e;return((e=this.currentStats)==null?void 0:e.layersPerDisplay)??new Map}get displayCompositeLayerIds(){var e;return((e=this.currentStats)==null?void 0:e.displayCompositeLayerIds)??new Map}get updatePacketSize(){var e;return((e=this.currentStats)==null?void 0:e.updatePacketSize)??0}get displayHeaderSize(){var e;return((e=this.currentStats)==null?void 0:e.displayHeaderSize)??0}get layerHeaderSize(){var e;return((e=this.currentStats)==null?void 0:e.layerHeaderSize)??0}get orderDataSize(){var e;return((e=this.currentStats)==null?void 0:e.orderDataSize)??0}get compressionRatio(){var e;return((e=this.currentStats)==null?void 0:e.compressionRatio)??0}get compressedPacketSize(){return Math.round(this.updatePacketSize*this.compressionRatio)}get totalCells(){var e;return((e=this.currentStats)==null?void 0:e.totalCells)??0}get nonEmptyCells(){var e;return((e=this.currentStats)==null?void 0:e.nonEmptyCells)??0}get cellsWithBackground(){var e;return((e=this.currentStats)==null?void 0:e.cellsWithBackground)??0}get rasterizationTimeMs(){var e;return((e=this.currentStats)==null?void 0:e.rasterizationTimeMs)??0}get encodingTimeMs(){var e;return((e=this.currentStats)==null?void 0:e.encodingTimeMs)??0}get packetSplit(){var e;return(e=this.currentStats)==null?void 0:e.packetSplit}get layerDetails(){var e;return(e=this.currentStats)==null?void 0:e.layerDetails}startTick(e){this.enabled&&(this.currentStats={tick:e,timestamp:Date.now(),totalOrders:0,ordersByLayer:new Map,ordersByType:new Map,totalLayers:0,visibleLayers:0,layersPerDisplay:new Map,updatePacketSize:0,displayHeaderSize:0,layerHeaderSize:0,orderDataSize:0,compressionRatio:0,totalCells:0,nonEmptyCells:0,cellsWithBackground:0,rasterizationTimeMs:0,encodingTimeMs:0,displayCompositeLayerIds:new Map})}recordDisplayComposite(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCompositeLayerIds||(this.currentStats.displayCompositeLayerIds=new Map),this.currentStats.displayCompositeLayerIds.set(e,[...t]))}recordLayerOrders(e,t){if(!(!this.enabled||!this.currentStats)){this.currentStats.totalOrders+=t.length,this.currentStats.ordersByLayer.set(e,t.length);for(let n of t){let i=this.currentStats.ordersByType.get(n.type)||0;this.currentStats.ordersByType.set(n.type,i+1)}}}recordLayers(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t)}recordDisplayLayers(e,t){!this.enabled||!this.currentStats||this.currentStats.layersPerDisplay.set(e,t)}recordUpdatePacketSize(e,t,n,i){!this.enabled||!this.currentStats||(this.currentStats.updatePacketSize=e,this.currentStats.displayHeaderSize=t,this.currentStats.layerHeaderSize=n,this.currentStats.orderDataSize=i,this.currentStats.compressionRatio=.25)}recordPacketSplit(e,t,n,i){!this.enabled||!this.currentStats||(this.currentStats.packetSplit={userId:e,displayCount:t,staticLayerCount:n,dynamicLayerCount:i})}recordLayerInfo(e,t,n,i){!this.enabled||!this.currentStats||(this.currentStats.layerDetails||(this.currentStats.layerDetails=[]),this.currentStats.layerDetails.push({layerId:e,mustBeReliable:t,orderCount:n,updateFlags:i}))}recordRenderStats(e,t,n){!this.enabled||!this.currentStats||(this.currentStats.totalCells=e,this.currentStats.nonEmptyCells=t,this.currentStats.cellsWithBackground=n)}recordRasterizationTime(e){!this.enabled||!this.currentStats||(this.currentStats.rasterizationTimeMs=e)}recordEncodingTime(e){!this.enabled||!this.currentStats||(this.currentStats.encodingTimeMs=e)}endTick(){}reset(){this.currentStats=null}};J(Rv,"CoreStats");var HI=Rv,Pv=[[0,0],[9786,1],[9787,2],[9829,3],[9830,4],[9827,5],[9824,6],[8226,7],[9688,8],[9675,9],[9689,10],[9794,11],[9792,12],[9834,13],[9835,14],[9788,15],[9658,16],[9668,17],[8597,18],[8252,19],[182,20],[167,21],[9644,22],[8616,23],[8593,24],[8595,25],[8594,26],[8592,27],[8735,28],[8596,29],[9650,30],[9660,31],[8962,127],[199,128],[252,129],[233,130],[226,131],[228,132],[224,133],[229,134],[231,135],[234,136],[235,137],[232,138],[239,139],[238,140],[236,141],[196,142],[197,143],[201,144],[230,145],[198,146],[244,147],[246,148],[242,149],[251,150],[249,151],[255,152],[214,153],[220,154],[162,155],[163,156],[165,157],[8359,158],[402,159],[225,160],[237,161],[243,162],[250,163],[241,164],[209,165],[170,166],[186,167],[191,168],[8976,169],[172,170],[189,171],[188,172],[161,173],[171,174],[187,175],[9617,176],[9618,177],[9619,178],[9474,179],[9508,180],[9569,181],[9570,182],[9558,183],[9557,184],[9571,185],[9553,186],[9559,187],[9565,188],[9564,189],[9563,190],[9488,191],[9492,192],[9524,193],[9516,194],[9500,195],[9472,196],[9532,197],[9566,198],[9567,199],[9562,200],[9556,201],[9577,202],[9574,203],[9568,204],[9552,205],[9580,206],[9575,207],[9576,208],[9572,209],[9573,210],[9561,211],[9560,212],[9554,213],[9555,214],[9579,215],[9578,216],[9496,217],[9484,218],[9608,219],[9604,220],[9612,221],[9616,222],[9600,223],[945,224],[223,225],[915,226],[960,227],[931,228],[963,229],[181,230],[964,231],[934,232],[920,233],[937,234],[948,235],[8734,236],[966,237],[949,238],[8745,239],[8801,240],[177,241],[8805,242],[8804,243],[8992,244],[8993,245],[247,246],[8776,247],[176,248],[8729,249],[183,250],[8730,251],[8319,252],[178,253],[9632,254],[160,255]],jI=new Map(Pv);new Map(Pv.map(([r,e])=>[e,r]));function Qs(r){if(r<128)return r;let e=jI.get(r);return e!==void 0?e:r&255}J(Qs,"unicodeToCp437");var Bv=class{constructor(){D(this,"unicolorSprites",new Map),D(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){if("loadType"in e){this.loadUnicolorSpritesFromPacket(e);return}for(let t of e){let{spriteId:n,sizeX:i,sizeY:s,data:o}=t,a=new Vg(i*s);if(typeof o=="string"){let u=o.replace(/\n/g,"");for(let c=0;c<Math.min(u.length,i*s);c++)a.set(c,Qs(u.charCodeAt(c)))}else if(Array.isArray(o)&&o.length>0&&typeof o[0]=="string"){let u=o;for(let c=0;c<Math.min(u.length,s);c++){let d=u[c];if(d)for(let h=0;h<Math.min(d.length,i);h++)a.set(c*i+h,Qs(d.charCodeAt(h)))}}else{let u=o;for(let c=0;c<Math.min(u.length,i*s);c++)a.set(c,u[c])}let l={id:n,sizeX:i,sizeY:s,data:a};this.unicolorSprites.set(l.id,l)}}loadUnicolorSpritesFromPacket(e){for(let t of e.sprites){let n=new Vg(t.sizeX*t.sizeY);for(let s=0;s<t.data.length;s++)n.set(s,t.data[s]);let i={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:n};this.unicolorSprites.set(i.id,i)}}loadMulticolorSprites(e){if("loadType"in e){this.loadMulticolorSpritesFromPacket(e);return}for(let t of e){let{spriteId:n,sizeX:i,sizeY:s,data:o}=t,a=new th(i*s);for(let u=0;u<Math.min(o.length,i*s);u++){let c=o[u],d=typeof c.charCode=="string"?Qs(c.charCode.charCodeAt(0)):c.charCode;a.set(u,d,c.fgColorId,c.bgColorId)}let l={id:n,sizeX:i,sizeY:s,data:a};this.multicolorSprites.set(l.id,l)}}loadMulticolorSpritesFromPacket(e){for(let t of e.sprites){let n=new th(t.sizeX*t.sizeY);for(let s=0;s<t.data.length;s++){let o=t.data[s];n.set(s,o.charCode,o.fgColorId,o.bgColorId)}let i={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:n};this.multicolorSprites.set(i.id,i)}}getUnicolorSprite(e){return this.unicolorSprites.get(e)}getMulticolorSprite(e){return this.multicolorSprites.get(e)}hasUnicolorSprite(e){return this.unicolorSprites.has(e)}hasMulticolorSprite(e){return this.multicolorSprites.has(e)}unloadUnicolorSprite(e){return this.unicolorSprites.delete(e)}unloadMulticolorSprite(e){return this.multicolorSprites.delete(e)}clearUnicolorSprites(){this.unicolorSprites.clear()}clearMulticolorSprites(){this.multicolorSprites.clear()}clearAll(){this.unicolorSprites.clear(),this.multicolorSprites.clear()}getUnicolorSpriteCount(){return this.unicolorSprites.size}getMulticolorSpriteCount(){return this.multicolorSprites.size}getTotalSpriteCount(){return this.unicolorSprites.size+this.multicolorSprites.size}};J(Bv,"SpriteRegistry");var YI=Bv,WI=(r=>(r.Bitmap="bitmap",r.Image="image",r))(WI||{});function Ef(r){return Math.sqrt(r)*16}J(Ef,"getAtlasColumns");function zv(r){return r*256-1}J(zv,"getMaxCharCode");function GI(r,e){let t=Ef(r)*e;return{width:t,height:t}}J(GI,"getAtlasDimensions");var Dv=class{constructor(e,t){this.fontId=e,this.config=t,D(this,"atlasColumns"),D(this,"maxCharCode"),D(this,"blocks",new Map),this.atlasColumns=Ef(t.atlasBlocks),this.maxCharCode=zv(t.atlasBlocks)}addBlock(e,t){if(e<0||e>=this.config.atlasBlocks)throw new Error(`Invalid block index ${e} for font with ${this.config.atlasBlocks} blocks`);this.blocks.set(e,t)}getBlock(e){return this.blocks.get(e)}getFontId(){return this.fontId}getConfig(){return{glyphWidth:this.config.glyphWidth,glyphHeight:this.config.glyphHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,atlasBlocks:this.config.atlasBlocks}}getGlyphWidth(){return this.config.glyphWidth}getGlyphHeight(){return this.config.glyphHeight}getCellWidth(){return this.config.cellWidth??this.config.glyphWidth}getCellHeight(){return this.config.cellHeight??this.config.glyphHeight}getAtlasBlocks(){return this.config.atlasBlocks}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}getAtlasDimensions(){return{width:this.atlasColumns*this.config.glyphWidth,height:this.atlasColumns*this.config.glyphHeight}}getCharUV(e){if(e<0||e>this.maxCharCode)return null;let t=e%this.atlasColumns,n=Math.floor(e/this.atlasColumns),i=t/this.atlasColumns,s=n/this.atlasColumns,o=(t+1)/this.atlasColumns,a=(n+1)/this.atlasColumns;return{u1:i,v1:s,u2:o,v2:a}}isValidCharCode(e){return e>=0&&e<=this.maxCharCode}};J(Dv,"ImageFont");var qg=Dv,Ov=class{constructor(){D(this,"fonts",new Map),D(this,"nameToId",new Map),D(this,"nextId",0)}allocateId(e){if(this.nextId>255)throw new Error(`Cannot register font "${e}": maximum 256 fonts reached`);return this.nextId++}registerFont(e,t){if(this.nameToId.has(e))throw new Error(`ImageFont with name "${e}" already exists`);let n=this.allocateId(e),i={glyphWidth:t.glyphWidth,glyphHeight:t.glyphHeight,cellWidth:t.cellWidth,cellHeight:t.cellHeight,atlasBlocks:t.atlasBlocks??1},s=new qg(n,i);return this.fonts.set(n,s),this.nameToId.set(e,n),n}addBlock(e,t,n){let i=this.fonts.get(e);if(!i)throw new Error(`ImageFont with ID ${e} not found`);i.addBlock(t,n)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`ImageFont with ID ${e} already exists`);let n=new qg(e,t);this.fonts.set(e,n),e>=this.nextId&&(this.nextId=e+1)}getFont(e){return this.fonts.get(e)}getFontByName(e){let t=this.nameToId.get(e);if(t!==void 0)return this.fonts.get(t)}getFontId(e){return this.nameToId.get(e)}getFontName(e){for(let[t,n]of this.nameToId.entries())if(n===e)return t}hasFont(e){return this.fonts.has(e)}hasFontByName(e){return this.nameToId.has(e)}unloadFont(e){if(!this.fonts.get(e))return!1;for(let[t,n]of this.nameToId.entries())if(n===e){this.nameToId.delete(t);break}return this.fonts.delete(e)}unloadFontByName(e){let t=this.nameToId.get(e);return t===void 0?!1:(this.nameToId.delete(e),this.fonts.delete(t))}clearFonts(){this.fonts.clear(),this.nameToId.clear(),this.nextId=0}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getFontNames(){return Array.from(this.nameToId.keys())}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};J(Ov,"ImageFontRegistry");var XI=Ov,Fv=class{constructor(){D(this,"sounds",new Map),D(this,"nameToId",new Map),D(this,"nextId",0)}registerFile(e,t,n){let i=this.allocateId(e),s={soundId:i,name:e,loadType:"file",format:t,data:n};return this.sounds.set(i,s),this.nameToId.set(e,i),i}registerFileWithId(e,t,n,i){this.validateId(e),this.checkIdAvailable(e,t);let s={soundId:e,name:t,loadType:"file",format:n,data:i};this.sounds.set(e,s),this.nameToId.set(t,e)}registerExternal(e,t,n,i,s){let o=this.allocateId(e),a={soundId:o,name:e,loadType:"external",format:t,url:n,size:i,checksum:s};return this.sounds.set(o,a),this.nameToId.set(e,o),o}registerExternalWithId(e,t,n,i,s,o){this.validateId(e),this.checkIdAvailable(e,t);let a={soundId:e,name:t,loadType:"external",format:n,url:i,size:s,checksum:o};this.sounds.set(e,a),this.nameToId.set(t,e)}get(e){if(typeof e=="number")return this.sounds.get(e);let t=this.nameToId.get(e);return t!==void 0?this.sounds.get(t):void 0}has(e){return this.get(e)!==void 0}getAll(){return Array.from(this.sounds.values())}getFileSounds(){return this.getAll().filter(e=>e.loadType==="file")}getExternalSounds(){return this.getAll().filter(e=>e.loadType==="external")}getNames(){return Array.from(this.nameToId.keys())}getId(e){return this.nameToId.get(e)}toLoadPackets(){let e=[],t=this.sounds.size,n=this.getFileSounds();if(n.length>0){let s=n.map(o=>({soundId:o.soundId,name:o.name,format:o.format,data:o.data}));e.push({type:"sound",mode:"file",sounds:s,totalSounds:t})}let i=this.getExternalSounds();if(i.length>0){let s=i.map(o=>({soundId:o.soundId,name:o.name,format:o.format,url:o.url,size:o.size,checksum:o.checksum}));e.push({type:"sound",mode:"external",sounds:s,totalSounds:t})}return e}toLoadPacket(e){let t=this.get(e);return t?t.loadType==="file"?{type:"sound",mode:"file",sounds:[{soundId:t.soundId,name:t.name,format:t.format,data:t.data}]}:{type:"sound",mode:"external",sounds:[{soundId:t.soundId,name:t.name,format:t.format,url:t.url,size:t.size,checksum:t.checksum}]}:null}unregister(e){let t=this.get(e);return t?(this.sounds.delete(t.soundId),this.nameToId.delete(t.name),!0):!1}clear(){this.sounds.clear(),this.nameToId.clear(),this.nextId=0}get size(){return this.sounds.size}getStats(){let e=this.getAll(),t=e.filter(i=>i.loadType==="file"),n=t.reduce((i,s)=>{var o;return i+(((o=s.data)==null?void 0:o.length)??0)},0);return{total:e.length,file:t.length,external:e.length-t.length,totalFileSize:n}}allocateId(e){if(this.nameToId.has(e))throw new Error(`Sound with name "${e}" already exists`);for(;this.sounds.has(this.nextId);)if(this.nextId++,this.nextId>255)throw new Error("Maximum number of sounds (256) reached");return this.nextId++}validateId(e){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`Invalid sound ID: ${e}. Must be an integer between 0 and 255.`)}checkIdAvailable(e,t){if(this.sounds.has(e)){let n=this.sounds.get(e);throw new Error(`Sound ID ${e} is already used by "${n.name}". Cannot register "${t}".`)}if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" already exists`)}};J(Fv,"SoundRegistry");var KI=Fv,Lv=class{constructor(e){this.soundRegistry=e}collectFromUser(e){let t=[],n=e.flushSoundCommands();for(let s of n){let o=this.convertSoundCommand(s);o&&t.push(o)}let i=e.flushAudioConfigCommands();for(let s of i){let o=this.convertConfigCommand(s);o&&t.push(o)}return t}convertSoundCommand(e){return"setEffects"in e&&e.setEffects===!0?this.convertSetEffectsCommand(e):"fadeOut"in e&&e.fadeOut===!0?this.convertFadeOutCommand(e):"pause"in e&&e.pause===!0?this.convertPauseCommand(e):"resume"in e&&e.resume===!0?this.convertResumeCommand(e):"instanceId"in e||"volume"in e||"pitch"in e||"loop"in e||"fadeIn"in e||"x"in e||"y"in e||"lowpass"in e||"highpass"in e||"reverb"in e?this.convertPlayCommand(e):this.convertStopCommand(e)}convertPlayCommand(e){let t=this.resolveSoundId(e.sound);if(t===null)return console.warn(`[AudioOrderCollector] Unknown sound: ${e.sound}`),null;let n=0;e.loop&&(n|=1),e.volume!==void 0&&(n|=2),e.pitch!==void 0&&(n|=4),e.fadeIn!==void 0&&(n|=8),e.lowpass!==void 0&&e.lowpass>0&&(n|=32),e.highpass!==void 0&&e.highpass>0&&(n|=64),e.reverb!==void 0&&e.reverb>0&&(n|=128);let i=e.x!==void 0&&e.y!==void 0;return i&&(n|=16),i?{type:1,soundId:t,instanceId:e.instanceId??0,flags:n,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,posX:this.encodePosition(e.x),posY:this.encodePosition(e.y),lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}:{type:2,soundId:t,instanceId:e.instanceId??0,flags:n&-17,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}}convertStopCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:3,targetType:t,target:n}}convertFadeOutCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:4,targetType:t,duration:this.encodeFadeTime(e.duration),target:n}}convertPauseCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:5,targetType:t,target:n}}convertResumeCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:6,targetType:t,target:n}}convertSetEffectsCommand(e){let t=0;return e.lowpass!==void 0&&(t|=1),e.highpass!==void 0&&(t|=2),e.reverb!==void 0&&(t|=4),{type:9,instanceId:e.instanceId,flags:t,lowpass:e.lowpass!==void 0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0?this.encodeReverb(e.reverb):void 0}}convertConfigCommand(e){return e.type==="set-listener-position"?{type:7,x:this.encodePosition(e.x),y:this.encodePosition(e.y)}:e.type==="configure-spatial"?{type:8,maxDistance:this.encodeDistance(e.maxDistance??1e3),referenceDistance:this.encodeDistance(e.referenceDistance??100),rolloffFactor:this.encodeRolloff(e.rolloffFactor??1),panSpread:this.encodePanSpread(e.panSpread??.5)}:null}resolveSoundId(e){if(typeof e=="number")return e>=0&&e<=255?e:null;let t=this.soundRegistry.getId(e);return t!==void 0?t:null}resolveTarget(e){if(e==="all")return{targetType:2,target:void 0};if(typeof e=="number")return{targetType:0,target:e};let t=this.soundRegistry.getId(e);return t!==void 0?{targetType:1,target:t}:(console.warn(`[AudioOrderCollector] Unknown sound name: ${e}, treating as 'all'`),{targetType:2,target:void 0})}encodeVolume(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePitch(e){let t=Math.max(.25,Math.min(4,e)),n=64*Math.log2(t/.25);return Math.round(Math.max(0,Math.min(255,n)))}encodeFadeTime(e){return Math.round(Math.max(0,Math.min(25.5,e))*10)}encodeDistance(e){return Math.round(Math.max(0,Math.min(25500,e))/100)}encodeRolloff(e){return Math.round(Math.max(0,Math.min(2.55,e))*100)}encodePanSpread(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePosition(e){return Math.round(Math.max(0,Math.min(65535,e)))}encodeFilterFreq(e){return e<=0?0:Math.round(Math.max(1,Math.min(255,e/100)))}encodeReverb(e){return Math.round(Math.max(0,Math.min(1,e))*255)}};J(Lv,"AudioOrderCollector");var ZI=Lv,_v=class{collectFromUser(e){let t=[];if(e.hasMobileVibrationCommands()){let n=e.flushMobileVibrationCommands();for(let i of n){let s=this.convertMobileCommand(i);s&&t.push(s)}}if(e.hasGamepadVibrationCommands()){let n=e.flushGamepadVibrationCommands();for(let i of n){let s=this.convertGamepadCommand(i);s&&t.push(s)}}return t}convertMobileCommand(e){return"cancel"in e&&e.cancel===!0?this.convertMobileCancelCommand():"pattern"in e?this.convertMobileVibrateCommand(e):null}convertMobileVibrateCommand(e){let t=0;e.intensity!==void 0&&e.intensity!==1&&(t|=1);let n=e.pattern,i=Array.isArray(n)?[...n]:[n],s={type:1,flags:t,pattern:i.map(o=>Math.round(o))};return t&1&&(s.intensity=Math.round(Math.min(1,Math.max(0,e.intensity))*255)/255),s}convertMobileCancelCommand(){return{type:2}}convertGamepadCommand(e){if("cancel"in e&&e.cancel===!0){let t=e.gamepadIndex??"all";return this.convertGamepadCancelCommand({gamepadIndex:t})}if("options"in e&&e.options){let t=e.gamepadIndex??0;return this.convertGamepadVibrateCommand({gamepadIndex:t,options:e.options})}return null}convertGamepadVibrateCommand(e){let{gamepadIndex:t,options:n}=e,i=0;n.startDelay!==void 0&&n.startDelay>0&&(i|=1);let s=t==="all"?255:t;t==="all"&&(i|=2);let o={type:16,flags:i,gamepadIndex:s,duration:Math.round(n.duration),strongMagnitude:Math.round(Math.min(1,Math.max(0,n.strongMagnitude??1))*255),weakMagnitude:Math.round(Math.min(1,Math.max(0,n.weakMagnitude??.5))*255)};return n.startDelay!==void 0&&n.startDelay>0&&(o.startDelay=Math.round(n.startDelay)),o}convertGamepadCancelCommand(e){let{gamepadIndex:t}=e,n=0,i=t==="all"?255:t;return t==="all"&&(n|=2),{type:17,flags:n,gamepadIndex:i}}};J(_v,"VibrationOrderCollector");var qI=_v,$v=class{collectFromUser(e){let t=e.flushPostProcessCommands();return this.convertCommands(t)}convertCommands(e){let t=[];for(let n of e){let i=this.convertCommand(n);i&&t.push(i)}return t}convertCommand(e){let t=e.displayId;switch(e.type){case"set-config":return this.convertSetConfig(e);case"set-scanlines-enabled":return this.createSetScanlinesOrder(t,e.enabled??!1,e.opacity);case"set-scanlines-opacity":return this.createSetScanlinesOrder(t,!0,e.opacity??Ge.scanlines.opacity);case"set-ambient-effect-enabled":return this.createSetAmbientEffectOrder(t,e.enabled??!1);case"set-ambient-effect-blur":return this.createSetAmbientEffectOrder(t,!0,e.blur);case"set-ambient-effect-scale":return this.createSetAmbientEffectOrder(t,!0,void 0,e.scale);case"set-scaling-mode":return this.createSetScalingModeOrder(t,e.scalingMode);case"set-grid":return this.createSetGridOrder(t,e.gridConfig);case"switch-palette":return this.createSwitchPaletteOrder(t,e.paletteSlotId);case"set-cell-size":return this.createSetCellSizeOrder(t,e.cellWidth,e.cellHeight);default:return console.warn(`[PostProcessOrderCollector] Unknown command type: ${e.type}`),null}}convertSetConfig(e){var s,o,a;let t=e.displayId;if(!e.config)return{type:1,displayId:t,flags:3,scanlines:{enabled:!1,opacity:0,pattern:0,colorR:0,colorG:0,colorB:0},ambientEffect:{enabled:!1,blur:0,scale:1,opacity:0}};let n=0,i={type:1,displayId:t,flags:0};if(e.config.scanlines){n|=1;let l=e.config.scanlines;i.scanlines={enabled:l.enabled,opacity:l.opacity??Ge.scanlines.opacity,pattern:this.patternToType(l.pattern??"horizontal"),colorR:((s=l.color)==null?void 0:s.r)??0,colorG:((o=l.color)==null?void 0:o.g)??0,colorB:((a=l.color)==null?void 0:a.b)??0}}if(e.config.ambientEffect){n|=2;let l=e.config.ambientEffect;i.ambientEffect={enabled:l.enabled,blur:l.blur??Ge.ambientEffect.blur,scale:l.scale??Ge.ambientEffect.scale,opacity:l.opacity??Ge.ambientEffect.opacity}}return i.flags=n,i}createSetScanlinesOrder(e,t,n){return{type:2,displayId:e,enabled:t,opacity:n??Ge.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,n,i){return{type:3,displayId:e,enabled:t,blur:n??Ge.ambientEffect.blur,scale:i??Ge.ambientEffect.scale,opacity:Ge.ambientEffect.opacity}}patternToType(e){switch(e){case"horizontal":return 0;case"vertical":return 1;case"grid":return 2;default:return 0}}createSetScalingModeOrder(e,t){return{type:4,displayId:e,mode:E1(t)}}createSetGridOrder(e,t){let{r:n,g:i,b:s,a:o}=this.parseColor(t.color??js.color);return{type:5,displayId:e,enabled:t.enabled,colorR:n,colorG:i,colorB:s,colorA:o,lineWidth:t.lineWidth??js.lineWidth}}createSwitchPaletteOrder(e,t){return{type:6,displayId:e,slotId:t}}createSetCellSizeOrder(e,t,n){return{type:7,displayId:e,cellWidth:t,cellHeight:n}}parseColor(e){let t=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?Math.round(parseFloat(t[4])*255):255};let n=e.match(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/);if(n){let i=n[1];return i.length===3?{r:parseInt(i[0]+i[0],16),g:parseInt(i[1]+i[1],16),b:parseInt(i[2]+i[2],16),a:255}:{r:parseInt(i.slice(0,2),16),g:parseInt(i.slice(2,4),16),b:parseInt(i.slice(4,6),16),a:255}}return{r:144,g:24,b:24,a:255}}};J($v,"PostProcessOrderCollector");var Mf=$v,ih=class sh{constructor(e={}){D(this,"mode"),D(this,"maxUsers"),D(this,"strictMode",!1),D(this,"currentTick",0),D(this,"stats",new HI),D(this,"spriteRegistry",new YI),D(this,"imageFontRegistry",new XI),D(this,"soundRegistry",new KI),D(this,"audioOrderCollector",new ZI(this.soundRegistry)),D(this,"vibrationOrderCollector",new qI),D(this,"postProcessOrderCollector",new Mf),D(this,"encoder",new EI),D(this,"users",new Map),D(this,"colorPalette",new Map),D(this,"paletteSlots",new Map),D(this,"displayRasterizer",new VI(this)),D(this,"updatePacketDecoder",new NI),D(this,"loadDecoder",new TI),D(this,"cachedLoadPackets",null),D(this,"_renderCallCount",0),D(this,"onPaletteChangedCallback"),D(this,"onFontAllocatedCallback"),D(this,"onFontBlockAddedCallback"),D(this,"onImageFontChangedCallback"),this.mode=e.mode??"standalone",this.maxUsers=e.maxUsers??(this.mode==="client"?1:100),this.initializeDefaultPalette(),this.loadFont(8,8,1,8,8)}initializeDefaultPalette(){[{r:0,g:0,b:0},{r:170,g:0,b:0},{r:0,g:170,b:0},{r:170,g:85,b:0},{r:0,g:0,b:170},{r:170,g:0,b:170},{r:0,g:170,b:170},{r:170,g:170,b:170},{r:85,g:85,b:85},{r:255,g:85,b:85},{r:85,g:255,b:85},{r:255,g:255,b:85},{r:85,g:85,b:255},{r:255,g:85,b:255},{r:85,g:255,b:255},{r:255,g:255,b:255}].forEach((e,t)=>this.colorPalette.set(t,{...e,a:255,e:0})),sh.ANSI_VGA_COLORS.forEach(e=>this.colorPalette.set(e.colorId,e)),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0})}isServer(){return this.mode==="server"}isClient(){return this.mode==="client"}isStandalone(){return this.mode==="standalone"}createUser(e,t){if(this.users.has(e))throw new Error(`User with ID ${e} already exists`);if(this.mode==="server"&&this.users.size>=this.maxUsers)throw new Error(`Maximum number of users reached (${this.maxUsers}). Cannot create user ${e}`);if(this.mode==="client"&&this.users.size>=1)throw new Error(`Client mode only allows one user. Cannot create user ${e}`);let n=new vI(e,t,this.mode);return n.setSpriteRegistry(this.spriteRegistry),this.users.set(e,n),n}getUser(e){return this.users.get(e)??null}getUsers(){return Array.from(this.users.values())}hasUser(e){return this.users.has(e)}removeUser(e){return this.users.delete(e)}getUserCount(){return this.users.size}clearAllUsers(){this.users.clear()}setColor(e,t,n,i,s=255,o=0){if(e<0||e>255)throw new Error(`Color ID must be between 0 and 255, got ${e}`);if(e>=240)throw new Error("Color IDs 240-255 are reserved (240-254: UI palette, 255: skip color). Use IDs 0-239 for custom colors.");if(t<0||t>255||n<0||n>255||i<0||i>255||s<0||s>255||o<0||o>255)throw new Error("Color components must be between 0 and 255");this.colorPalette.set(e,{r:t,g:n,b:i,a:s,e:o}),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}onPaletteChanged(e){this.onPaletteChangedCallback=e}getColor(e){return this.colorPalette.get(e)??null}getPalette(){return new Map(this.colorPalette)}resetPalette(){this.colorPalette.clear(),this.initializeDefaultPalette(),this.cachedLoadPackets=null,this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}loadPaletteToSlot(e,t){if(e<0||e>255)throw new Error(`Palette slot ID must be between 0 and 255, got ${e}`);let n=new Map;for(let i of t)i.colorId<0||i.colorId>255||n.set(i.colorId,{r:i.r,g:i.g,b:i.b,a:i.a??255,e:i.e??0});sh.ANSI_VGA_COLORS.forEach(i=>{n.set(i.colorId,{r:i.r,g:i.g,b:i.b,a:i.a,e:i.e})}),n.set(255,{r:0,g:0,b:0,a:0,e:0}),this.paletteSlots.set(e,n)}getPaletteFromSlot(e){return this.paletteSlots.get(e)??null}hasPaletteSlot(e){return this.paletteSlots.has(e)}clearPaletteSlot(e){this.paletteSlots.delete(e)}clearAllPaletteSlots(){this.paletteSlots.clear()}getColorCSS(e){let t=this.getColor(e);if(!t)return null;let n=t.a/255;return`rgba(${t.r}, ${t.g}, ${t.b}, ${n})`}getUserIds(){return Array.from(this.users.keys())}forEachUser(e){this.users.forEach(e)}filterUsers(e){return this.getUsers().filter(e)}findUser(e){return this.getUsers().find(e)}getCurrentTick(){return this.currentTick}getStats(){return this.stats}endTick(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,n=0;return this.users.forEach((i,s)=>{let o=i.getLayers(),a=i.getDisplays();t+=o.length,i.getStats().isEnabled()&&i.getStats().startTick(this.currentTick);let l=a.map(w=>{let g=w.getOrigin(),y=w.getSize();return{id:w.getId(),originX:g.x,originY:g.y,sizeX:y.x,sizeY:y.y,renderPasses:w.getRenderPasses()}});a.forEach(w=>w.resetChangeTracking());let u=[],c=[];o.forEach((w,g)=>{if(!w.getNeedsCommit())return;let y=w.getOrigin(),C=w.getOrders(),x=w.getMustBeReliable(),I=w.calculateUpdateFlags();w.resetChangeTracking(),w.resetCommit(),w.getId()===0&&Aa(w,g);let E={id:w.getId(),updateFlags:I,zIndex:w.getZOrder(),originX:y.x,originY:y.y,width:w.getWidth(),height:w.getHeight(),isMacroLayer:w.getIsMacroLayer(),is16bit:w.getCharCodeMode()==="16bit",orderCount:C.length,orders:C};C.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(w.getId(),x,C.length,I),x?u.push(E):c.push(E)}),n+=u.length+c.length;let d=this.audioOrderCollector.collectFromUser(i),h=this.vibrationOrderCollector.collectFromUser(i),f=this.postProcessOrderCollector.collectFromUser(i),p=i.flushMacroOrders(),m=null,S=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(s,l.length,u.length,c.length),(u.length>0||d.length>0||p.length>0)&&(m=this.encoder.encode({tick:this.currentTick,displayCount:l.length,displays:l,layerCount:u.length,layers:u,audioOrderCount:d.length,audioOrders:d,vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:p.length,macroOrders:p,postProcessOrderCount:0,postProcessOrders:[]})),S=this.encoder.encode({tick:this.currentTick,displayCount:l.length,displays:l,layerCount:c.length,layers:c,audioOrderCount:0,audioOrders:[],vibrationOrderCount:h.length,vibrationOrders:h,macroOrderCount:0,macroOrders:[],postProcessOrderCount:f.length,postProcessOrders:f}),e.set(s,{static:m,dynamic:S}),i.getStats().isEnabled()){let w=a.reduce((x,I)=>{let E=I.getSize();return x+E.x*E.y},0);i.getStats().recordDisplays(a.length,w),i.getStats().recordLayers(o.length,u.length+c.length,u.length,c.length),[...u,...c].forEach(x=>{i.getStats().recordLayerOrders(x.id,x.orders.length)});let g=(m==null?void 0:m.length)||0,y=(S==null?void 0:S.length)||0;i.getStats().recordPacketSizes(g,y);let C=i.getInputBindingRegistry();i.getStats().recordInput(!1,C.getAxisCount(),C.getButtonCount()),i.getStats().endTick()}if(i.endTickBytes(),this.stats.isEnabled()){let w=[...u,...c];w.forEach((I,E)=>{this.stats.recordLayerOrders(E,I.orders)}),a.forEach((I,E)=>{this.stats.recordDisplayLayers(E,w.length)});let g=((m==null?void 0:m.length)||0)+((S==null?void 0:S.length)||0),y=l.reduce((I,E)=>{var R;let A=Math.min(((R=E.renderPasses)==null?void 0:R.length)??0,4);return I+8+A*4},0),C=w.length*20,x=g-y-C;this.stats.recordUpdatePacketSize(g,y,C,x>0?x:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,n),this.stats.endTick()),this.currentTick++,e}getSnapshot(e){let t=this.getUser(e);if(!t)return null;let n=t.getDisplays(),i=t.getLayers(),s=n.map((a,l)=>{let u=a.getOrigin(),c=a.getSize();return{id:l,originX:u.x,originY:u.y,sizeX:c.x,sizeY:c.y,renderPasses:a.getRenderPasses()}}),o=i.map((a,l)=>{let u=a.getOrigin(),c=a.getOrders();return a.getId()===0&&Aa(a,l),{id:a.getId(),updateFlags:7,zIndex:a.getZOrder(),originX:u.x,originY:u.y,width:a.getWidth(),height:a.getHeight(),isMacroLayer:a.getIsMacroLayer(),is16bit:a.getCharCodeMode()==="16bit",orderCount:c.length,orders:c}});return this.encoder.encode({tick:this.currentTick,displayCount:s.length,displays:s,layerCount:o.length,layers:o,audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})}resetTick(){this.currentTick=0}applyUpdatePacket(e,t){let n=this.getUser(e);if(!n){if(this.strictMode)throw new Error(`Cannot apply update packet: user ${e} does not exist`);return!1}return n.applyUpdate(t),t.audioOrders&&t.audioOrders.length>0&&n.applyAudioOrders(t.audioOrders),t.vibrationOrders&&t.vibrationOrders.length>0&&n.applyVibrationOrders(t.vibrationOrders),!0}applyUpdatePacketBuffer(e,t){let n=this.updatePacketDecoder.decode(t);return this.applyUpdatePacket(e,n)?n:null}applyLoadPacket(e){try{let t=this.loadDecoder.decode(e).load;switch(t.loadType){case 1:t.slotId!==void 0?this.loadPaletteToSlot(t.slotId,t.colors):(console.warn("[Core] ColorPalette load without slotId is deprecated. Loading into slot 0."),this.loadPaletteToSlot(0,t.colors));break;case 2:this.spriteRegistry.loadUnicolorSprites(t);break;case 3:this.spriteRegistry.loadMulticolorSprites(t);break;case 5:console.warn("[Core] Sound loading not yet implemented");break;case 8:this.loadFont(t.glyphWidth,t.glyphHeight,t.atlasBlocks,t.cellWidth,t.cellHeight);break;case 9:this.loadFontBlock(t.blockIndex,t.imageData);break;case 7:{for(let n of this.users.values())n.loadMacroTemplate(t.macroId,t.template);break}default:return console.error(`[Core] Unknown LoadType: ${t.loadType}`),!1}return!0}catch(t){return console.error("[Core] Failed to apply LoadPacket:",t),!1}}generatePaletteSlotLoadPacket(e){let t=this.getPaletteFromSlot(e);if(!t||t.size===0)return null;let n=new Lc,i=[];return t.forEach((s,o)=>{o!==255&&i.push({colorId:o,r:s.r,g:s.g,b:s.b,a:s.a,e:s.e})}),n.encode({loadType:1,slotId:e,colors:i})}generateAllPaletteSlotLoadPackets(){let e=[];return this.paletteSlots.forEach((t,n)=>{let i=this.generatePaletteSlotLoadPacket(n);i&&e.push(i)}),e}generateUnicolorSpritesLoadPacket(){if(this.spriteRegistry.getUnicolorSpriteCount()===0)return null;let e=[];for(let t=0;t<=255;t++){let n=this.spriteRegistry.getUnicolorSprite(t);if(n){let i=[];for(let s=0;s<n.sizeX*n.sizeY;s++)i.push(n.data.get(s));e.push({spriteId:n.id,sizeX:n.sizeX,sizeY:n.sizeY,data:i})}}return e.length===0?null:new Lc().encode({loadType:2,sprites:e})}generateMulticolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let i=e.getMulticolorSprite(n);if(i){let s=[];for(let o=0;o<i.sizeX*i.sizeY;o++){let a=i.data.get(o);s.push({charCode:a.charCode,fgColorId:a.fgColorCode,bgColorId:a.bgColorCode})}t.push({spriteId:i.id,sizeX:i.sizeX,sizeY:i.sizeY,data:s})}}return t.length===0?null:new Lc().encode({loadType:3,sprites:t})}generateAllLoadPackets(){if(this.cachedLoadPackets)return this.cachedLoadPackets;let e=[],t=this.generateAllPaletteSlotLoadPackets();e.push(...t);let n=this.generateUnicolorSpritesLoadPacket();n&&e.push(n);let i=this.generateMulticolorSpritesLoadPacket();return i&&e.push(i),this.cachedLoadPackets=e,e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let n=t.getMacroLoads();if(n.length===0)return[];let i=new UI;return n.map(s=>i.encode(s))}generateInitialUpdatePacket(e){let t=this.getUser(e);if(!t||!t.hasPostProcessCommands())return null;let n=this.postProcessOrderCollector.collectFromUser(t);if(n.length===0)return null;let i=t.getDisplays().map(s=>{let o=s.getSize();return{id:s.getId(),originX:0,originY:0,sizeX:o.x,sizeY:o.y}});return this.encoder.encode({tick:0,displayCount:i.length,displays:i,layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:n.length,postProcessOrders:n})}applyInputBindingsLoadPacket(e,t){let n=this.getUser(e);if(!n){if(this.strictMode)throw new Error(`Cannot apply input bindings: user ${e} does not exist`);return!1}try{return n.applyInputBindingsLoadPacket(t),!0}catch(i){return console.error(`[Core] Failed to apply input bindings for user ${e}:`,i),!1}}getRenderState(e,t){let n=this.getUser(e);if(!n)return null;let i=n.getDisplays(),s=t?n.getLayers().filter(t):n.getLayers(),o=performance.now(),a=[];for(let l of i){if(!l)continue;let u=l.getOrigin(),c=l.getSize();if(a.push(this.displayRasterizer.rasterize({id:l.getId(),x:u.x,y:u.y,width:c.x,height:c.y},s,l.getRenderPasses())),this.stats.isEnabled()){let d=l.getId();this.stats.recordDisplayComposite(d,this.displayRasterizer.getLastVisibleLayerIds())}}return performance.now()-o,this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:n.id,userName:n.name,tick:this.currentTick,displays:a}}getAllRenderStates(){let e=new Map;return this.users.forEach((t,n)=>{let i=this.getRenderState(n);i&&e.set(n,i)}),e}enableStats(e){this.stats.setEnabled(e)}getStatsInstance(){return this.stats}resetStats(){this.stats.reset()}loadUnicolorSprites(e){this.spriteRegistry.loadUnicolorSprites(e)}loadMulticolorSprites(e){this.spriteRegistry.loadMulticolorSprites(e)}loadFont(e,t,n,i,s){let o={glyphWidth:e,glyphHeight:t,cellWidth:i,cellHeight:s,atlasBlocks:n};this.imageFontRegistry.hasFont(0)&&this.imageFontRegistry.unloadFont(0),this.imageFontRegistry.loadFont(0,o),this.onFontAllocatedCallback&&this.onFontAllocatedCallback()}loadFontBlock(e,t){if(typeof t=="string")return this.readResource(t).then(n=>{this.imageFontRegistry.addBlock(0,e,n),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(e),e===0&&this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0)});this.imageFontRegistry.addBlock(0,e,t),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(e),e===0&&this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0)}unloadUnicolorSprite(e){return this.spriteRegistry.unloadUnicolorSprite(e)}unloadMulticolorSprite(e){return this.spriteRegistry.unloadMulticolorSprite(e)}clearUnicolorSprites(){this.spriteRegistry.clearUnicolorSprites()}clearMulticolorSprites(){this.spriteRegistry.clearMulticolorSprites()}clearAllSprites(){this.spriteRegistry.clearAll()}getUnicolorSpriteCount(){return this.spriteRegistry.getUnicolorSpriteCount()}getMulticolorSpriteCount(){return this.spriteRegistry.getMulticolorSpriteCount()}getTotalSpriteCount(){return this.spriteRegistry.getTotalSpriteCount()}hasUnicolorSprite(e){return this.spriteRegistry.hasUnicolorSprite(e)}hasMulticolorSprite(e){return this.spriteRegistry.hasMulticolorSprite(e)}getSpriteRegistry(){return this.spriteRegistry}getSoundRegistry(){return this.soundRegistry}async loadSound(e,t){let n=this.detectSoundFormat(t),i=await this.readResource(t);return this.soundRegistry.registerFile(e,n,i)}async loadSounds(e){let t={},n=Object.entries(e).map(async([i,s])=>{let o=await this.loadSound(i,s);t[i]=o});return await Promise.all(n),t}detectSoundFormat(e){var s;let t=((s=e.split(".").pop())==null?void 0:s.toLowerCase())??"",n={mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"},i=n[t];if(!i)throw new Error(`Unsupported audio format: .${t}. Supported: ${Object.keys(n).join(", ")}`);return i}async readResource(e){let t=globalThis,n=typeof t.window<"u"||typeof t.document<"u",i=typeof t.fetch=="function",s=/^https?:\/\//i.test(e),o=e.startsWith("file:");if(n)try{let f=await fetch(e);if(!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);let p=await f.arrayBuffer();return new Uint8Array(p)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Error(`Failed to load resource "${e}": ${p}`)}if((s||o)&&i)try{let f=await fetch(e);if(!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);let p=await f.arrayBuffer();return new Uint8Array(p)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Error(`Failed to load resource "${e}": ${p}`)}let a=typeof ll<"u"?ll:null;if(!a)throw new Error("Node.js require is not available");let l="fs",u=a("path"),c=a(l),d=u.resolve(e),h=c.readFileSync(d);return new Uint8Array(h)}registerSound(e,t,n){return this.soundRegistry.registerFile(e,t,n)}registerExternalSound(e,t,n,i){return this.soundRegistry.registerExternal(e,t,n,i)}hasSound(e){return this.soundRegistry.has(e)}generateSoundLoadPackets(){return this.soundRegistry.toLoadPackets()}async loadImageFont(e,t,n){let i=await this.loadImageData(t),s=this.imageFontRegistry.registerFont(e,n);return this.imageFontRegistry.addBlock(0,0,i),this.onFontAllocatedCallback&&this.onFontAllocatedCallback(),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(0),this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0),s}async loadImageFonts(e){let t={},n=Object.entries(e).map(async([i,{path:s,options:o}])=>{let a=await this.loadImageFont(i,s,o);t[i]=a});return await Promise.all(n),t}async loadImageData(e){let t=globalThis;if(typeof t.document<"u"||typeof t.window<"u"||typeof t.fetch=="function")try{let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let i=await n.arrayBuffer();return new Uint8Array(i)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`Failed to load image font "${e}": ${i}`)}else{let n=typeof ll<"u"?ll:null;if(!n)throw new Error("Node.js require is not available");let i=n("fs").readFileSync(e);return new Uint8Array(i)}}getImageFontId(e){return this.imageFontRegistry.getFontId(e)}getImageFontByName(e){return this.imageFontRegistry.getFontByName(e)??null}onFontAllocated(e){this.onFontAllocatedCallback=e}onFontBlockAdded(e){this.onFontBlockAddedCallback=e}onImageFontChanged(e){this.onImageFontChangedCallback=e}getImageFontRegistry(){return this.imageFontRegistry}loadImageFontById(e,t){this.imageFontRegistry.loadFont(e,t),this.onImageFontChangedCallback&&this.onImageFontChangedCallback(e)}getImageFont(e){return this.imageFontRegistry.getFont(e)??null}hasImageFont(e){return this.imageFontRegistry.hasFont(e)}hasImageFontByName(e){return this.imageFontRegistry.hasFontByName(e)}unloadImageFont(e){return this.imageFontRegistry.unloadFont(e)}unloadImageFontByName(e){return this.imageFontRegistry.unloadFontByName(e)}clearImageFonts(){this.imageFontRegistry.clearFonts()}getImageFontCount(){return this.imageFontRegistry.getFontCount()}getImageFontIds(){return this.imageFontRegistry.getFontIds()}getImageFontNames(){return this.imageFontRegistry.getFontNames()}};J(ih,"Core"),D(ih,"ANSI_VGA_COLORS",[{colorId:240,r:0,g:0,b:0,a:255,e:0},{colorId:241,r:60,g:60,b:75,a:255,e:0},{colorId:242,r:160,g:160,b:180,a:255,e:0},{colorId:243,r:255,g:255,b:255,a:255,e:0},{colorId:244,r:230,g:50,b:80,a:255,e:0},{colorId:245,r:255,g:120,b:50,a:255,e:0},{colorId:246,r:255,g:210,b:60,a:255,e:0},{colorId:247,r:130,g:220,b:50,a:255,e:0},{colorId:248,r:35,g:100,b:55,a:255,e:0},{colorId:249,r:40,g:200,b:220,a:255,e:0},{colorId:250,r:60,g:120,b:240,a:255,e:0},{colorId:251,r:35,g:55,b:125,a:255,e:0},{colorId:252,r:150,g:70,b:210,a:255,e:0},{colorId:253,r:130,g:80,b:50,a:255,e:0},{colorId:254,r:240,g:210,b:170,a:255,e:0}]);var Nv=ih,Ru=new Map([[0,new Uint8Array([0,0,0,0,0,0,0,0])],[1,new Uint8Array([0,60,102,102,102,60,0,0])],[2,new Uint8Array([0,60,126,126,126,60,0,0])],[3,new Uint8Array([0,108,254,254,124,56,16,0])],[4,new Uint8Array([0,16,56,124,56,16,0,0])],[5,new Uint8Array([0,56,124,56,108,16,56,0])],[6,new Uint8Array([0,16,56,124,124,16,56,0])],[7,new Uint8Array([0,0,24,60,60,24,0,0])],[8,new Uint8Array([255,255,231,195,195,231,255,255])],[9,new Uint8Array([0,60,66,66,66,60,0,0])],[10,new Uint8Array([255,195,189,189,189,195,255,255])],[11,new Uint8Array([0,30,14,26,120,204,120,0])],[12,new Uint8Array([0,60,102,102,60,24,126,24])],[13,new Uint8Array([0,6,14,14,14,124,120,0])],[14,new Uint8Array([0,102,118,126,126,60,24,0])],[15,new Uint8Array([0,153,90,60,60,90,153,0])],[16,new Uint8Array([0,16,48,112,48,16,0,0])],[17,new Uint8Array([0,8,12,14,12,8,0,0])],[18,new Uint8Array([0,24,60,126,24,126,60,24])],[19,new Uint8Array([0,102,102,102,102,0,102,0])],[20,new Uint8Array([0,127,219,219,123,27,27,0])],[21,new Uint8Array([62,99,56,108,108,56,204,120])],[22,new Uint8Array([0,0,0,0,126,126,126,0])],[23,new Uint8Array([0,24,60,126,24,126,60,24])],[24,new Uint8Array([0,24,60,126,255,255,0,0])],[25,new Uint8Array([0,0,255,255,126,60,24,0])],[26,new Uint8Array([0,48,120,252,252,120,48,0])],[27,new Uint8Array([0,12,30,63,63,30,12,0])],[28,new Uint8Array([0,0,24,24,24,126,0,0])],[29,new Uint8Array([0,16,48,127,48,16,0,0])],[30,new Uint8Array([0,0,24,60,126,24,24,0])],[31,new Uint8Array([0,0,24,24,126,60,24,0])],[32,new Uint8Array([0,0,0,0,0,0,0,0])],[33,new Uint8Array([24,24,24,24,24,0,24,0])],[34,new Uint8Array([108,108,108,0,0,0,0,0])],[35,new Uint8Array([54,54,127,54,127,54,54,0])],[36,new Uint8Array([12,63,104,62,11,126,24,0])],[37,new Uint8Array([96,102,12,24,48,102,6,0])],[38,new Uint8Array([56,108,108,56,109,102,59,0])],[39,new Uint8Array([24,24,24,0,0,0,0,0])],[40,new Uint8Array([12,24,48,48,48,24,12,0])],[41,new Uint8Array([48,24,12,12,12,24,48,0])],[42,new Uint8Array([0,102,60,255,60,102,0,0])],[43,new Uint8Array([0,24,24,126,24,24,0,0])],[44,new Uint8Array([0,0,0,0,0,24,24,48])],[45,new Uint8Array([0,0,0,126,0,0,0,0])],[46,new Uint8Array([0,0,0,0,0,24,24,0])],[47,new Uint8Array([0,6,12,24,48,96,0,0])],[48,new Uint8Array([60,102,110,126,118,102,60,0])],[49,new Uint8Array([24,56,24,24,24,24,126,0])],[50,new Uint8Array([60,102,6,12,24,48,126,0])],[51,new Uint8Array([60,102,6,28,6,102,60,0])],[52,new Uint8Array([12,28,60,108,126,12,12,0])],[53,new Uint8Array([126,96,124,6,6,102,60,0])],[54,new Uint8Array([28,48,96,124,102,102,60,0])],[55,new Uint8Array([126,6,12,24,48,48,48,0])],[56,new Uint8Array([60,102,102,60,102,102,60,0])],[57,new Uint8Array([60,102,102,62,6,12,56,0])],[58,new Uint8Array([0,0,24,24,0,24,24,0])],[59,new Uint8Array([0,0,24,24,0,24,24,48])],[60,new Uint8Array([12,24,48,96,48,24,12,0])],[61,new Uint8Array([0,0,126,0,126,0,0,0])],[62,new Uint8Array([48,24,12,6,12,24,48,0])],[63,new Uint8Array([60,102,12,24,24,0,24,0])],[64,new Uint8Array([60,102,110,106,110,96,60,0])],[65,new Uint8Array([60,102,102,126,102,102,102,0])],[66,new Uint8Array([124,102,102,124,102,102,124,0])],[67,new Uint8Array([60,102,96,96,96,102,60,0])],[68,new Uint8Array([120,108,102,102,102,108,120,0])],[69,new Uint8Array([126,96,96,124,96,96,126,0])],[70,new Uint8Array([126,96,96,124,96,96,96,0])],[71,new Uint8Array([60,102,96,110,102,102,60,0])],[72,new Uint8Array([102,102,102,126,102,102,102,0])],[73,new Uint8Array([126,24,24,24,24,24,126,0])],[74,new Uint8Array([62,12,12,12,12,108,56,0])],[75,new Uint8Array([102,108,120,112,120,108,102,0])],[76,new Uint8Array([96,96,96,96,96,96,126,0])],[77,new Uint8Array([99,119,127,107,99,99,99,0])],[78,new Uint8Array([102,102,118,126,110,102,102,0])],[79,new Uint8Array([60,102,102,102,102,102,60,0])],[80,new Uint8Array([124,102,102,124,96,96,96,0])],[81,new Uint8Array([60,102,102,102,106,108,54,0])],[82,new Uint8Array([124,102,102,124,108,102,102,0])],[83,new Uint8Array([60,102,96,60,6,102,60,0])],[84,new Uint8Array([126,24,24,24,24,24,24,0])],[85,new Uint8Array([102,102,102,102,102,102,60,0])],[86,new Uint8Array([102,102,102,102,102,60,24,0])],[87,new Uint8Array([99,99,99,107,127,119,99,0])],[88,new Uint8Array([102,102,60,24,60,102,102,0])],[89,new Uint8Array([102,102,102,60,24,24,24,0])],[90,new Uint8Array([126,6,12,24,48,96,126,0])],[91,new Uint8Array([60,48,48,48,48,48,60,0])],[92,new Uint8Array([0,96,48,24,12,6,0,0])],[93,new Uint8Array([60,12,12,12,12,12,60,0])],[94,new Uint8Array([24,60,102,0,0,0,0,0])],[95,new Uint8Array([0,0,0,0,0,0,255,0])],[96,new Uint8Array([48,24,12,0,0,0,0,0])],[97,new Uint8Array([0,0,60,6,62,102,62,0])],[98,new Uint8Array([96,96,124,102,102,102,124,0])],[99,new Uint8Array([0,0,60,102,96,102,60,0])],[100,new Uint8Array([6,6,62,102,102,102,62,0])],[101,new Uint8Array([0,0,60,102,126,96,60,0])],[102,new Uint8Array([28,54,48,124,48,48,48,0])],[103,new Uint8Array([0,0,62,102,102,62,6,60])],[104,new Uint8Array([96,96,124,102,102,102,102,0])],[105,new Uint8Array([24,0,56,24,24,24,60,0])],[106,new Uint8Array([12,0,28,12,12,12,108,56])],[107,new Uint8Array([96,96,102,108,120,108,102,0])],[108,new Uint8Array([56,24,24,24,24,24,60,0])],[109,new Uint8Array([0,0,102,127,107,107,99,0])],[110,new Uint8Array([0,0,124,102,102,102,102,0])],[111,new Uint8Array([0,0,60,102,102,102,60,0])],[112,new Uint8Array([0,0,124,102,102,124,96,96])],[113,new Uint8Array([0,0,62,102,102,62,6,6])],[114,new Uint8Array([0,0,108,118,96,96,96,0])],[115,new Uint8Array([0,0,62,96,60,6,124,0])],[116,new Uint8Array([48,48,124,48,48,54,28,0])],[117,new Uint8Array([0,0,102,102,102,102,62,0])],[118,new Uint8Array([0,0,102,102,102,60,24,0])],[119,new Uint8Array([0,0,99,107,107,127,54,0])],[120,new Uint8Array([0,0,102,60,24,60,102,0])],[121,new Uint8Array([0,0,102,102,102,62,6,60])],[122,new Uint8Array([0,0,126,12,24,48,126,0])],[123,new Uint8Array([14,24,24,112,24,24,14,0])],[124,new Uint8Array([24,24,24,24,24,24,24,0])],[125,new Uint8Array([112,24,24,14,24,24,112,0])],[126,new Uint8Array([49,107,70,0,0,0,0,0])],[127,new Uint8Array([0,24,60,126,126,24,60,0])],[128,new Uint8Array([60,102,96,96,102,60,24,48])],[129,new Uint8Array([102,0,102,102,102,102,62,0])],[130,new Uint8Array([12,24,60,102,126,96,60,0])],[131,new Uint8Array([24,102,60,6,62,102,62,0])],[132,new Uint8Array([102,0,60,6,62,102,62,0])],[133,new Uint8Array([48,24,60,6,62,102,62,0])],[134,new Uint8Array([24,36,60,6,62,102,62,0])],[135,new Uint8Array([0,0,60,96,96,60,24,48])],[136,new Uint8Array([24,102,60,102,126,96,60,0])],[137,new Uint8Array([102,0,60,102,126,96,60,0])],[138,new Uint8Array([48,24,60,102,126,96,60,0])],[139,new Uint8Array([102,0,24,24,24,24,24,0])],[140,new Uint8Array([24,102,0,24,24,24,24,0])],[141,new Uint8Array([48,24,0,24,24,24,24,0])],[142,new Uint8Array([102,0,60,102,126,102,102,0])],[143,new Uint8Array([24,36,60,102,126,102,102,0])],[144,new Uint8Array([12,24,126,96,124,96,126,0])],[145,new Uint8Array([0,0,110,27,127,216,119,0])],[146,new Uint8Array([63,108,108,127,108,108,111,0])],[147,new Uint8Array([24,102,60,102,102,102,60,0])],[148,new Uint8Array([102,0,60,102,102,102,60,0])],[149,new Uint8Array([48,24,60,102,102,102,60,0])],[150,new Uint8Array([24,102,0,102,102,102,62,0])],[151,new Uint8Array([48,24,0,102,102,102,62,0])],[152,new Uint8Array([102,0,102,102,62,6,60,0])],[153,new Uint8Array([102,0,60,102,102,102,60,0])],[154,new Uint8Array([102,0,102,102,102,102,60,0])],[155,new Uint8Array([0,24,62,96,96,62,24,0])],[156,new Uint8Array([28,54,48,124,48,48,126,0])],[157,new Uint8Array([102,102,60,126,24,126,24,0])],[158,new Uint8Array([124,102,124,98,102,111,102,3])],[159,new Uint8Array([14,27,24,60,24,24,216,112])],[160,new Uint8Array([12,24,60,6,62,102,62,0])],[161,new Uint8Array([12,24,0,24,24,24,24,0])],[162,new Uint8Array([12,24,60,102,102,102,60,0])],[163,new Uint8Array([12,24,0,102,102,102,62,0])],[164,new Uint8Array([54,108,0,124,102,102,102,0])],[165,new Uint8Array([54,108,102,118,126,110,102,0])],[166,new Uint8Array([28,6,30,54,30,0,62,0])],[167,new Uint8Array([28,54,54,54,28,0,62,0])],[168,new Uint8Array([24,0,24,48,96,102,60,0])],[169,new Uint8Array([0,0,0,254,192,192,0,0])],[170,new Uint8Array([0,0,0,254,6,6,0,0])],[171,new Uint8Array([96,224,98,102,108,24,48,110])],[172,new Uint8Array([96,224,98,102,108,24,62,6])],[173,new Uint8Array([24,0,24,24,60,60,24,0])],[174,new Uint8Array([0,0,54,108,216,108,54,0])],[175,new Uint8Array([0,0,216,108,54,108,216,0])],[176,new Uint8Array([34,136,34,136,34,136,34,136])],[177,new Uint8Array([136,34,136,34,136,34,136,34])],[178,new Uint8Array([170,85,170,85,170,85,170,85])],[179,new Uint8Array([24,24,24,24,24,24,24,24])],[180,new Uint8Array([24,24,24,248,24,24,24,24])],[181,new Uint8Array([24,24,24,252,28,24,24,24])],[182,new Uint8Array([54,54,54,246,54,54,54,54])],[183,new Uint8Array([0,0,0,254,54,54,54,54])],[184,new Uint8Array([0,0,0,252,28,24,24,24])],[185,new Uint8Array([54,54,54,252,54,54,54,54])],[186,new Uint8Array([54,54,54,54,54,54,54,54])],[187,new Uint8Array([0,0,0,252,54,54,54,54])],[188,new Uint8Array([54,54,54,252,0,0,0,0])],[189,new Uint8Array([54,54,54,247,0,0,0,0])],[190,new Uint8Array([24,24,24,252,0,0,0,0])],[191,new Uint8Array([0,0,0,248,24,24,24,24])],[192,new Uint8Array([24,24,24,31,0,0,0,0])],[193,new Uint8Array([24,24,24,255,0,0,0,0])],[194,new Uint8Array([0,0,0,255,24,24,24,24])],[195,new Uint8Array([24,24,24,31,24,24,24,24])],[196,new Uint8Array([0,0,0,255,0,0,0,0])],[197,new Uint8Array([24,24,24,255,24,24,24,24])],[198,new Uint8Array([24,24,31,31,24,24,24,24])],[199,new Uint8Array([54,54,55,55,54,54,54,54])],[200,new Uint8Array([54,54,54,63,0,0,0,0])],[201,new Uint8Array([0,0,0,63,54,54,54,54])],[202,new Uint8Array([54,54,54,255,0,0,0,0])],[203,new Uint8Array([0,0,0,255,54,54,54,54])],[204,new Uint8Array([54,54,54,63,54,54,54,54])],[205,new Uint8Array([0,0,0,255,0,255,0,0])],[206,new Uint8Array([54,54,54,255,54,54,54,54])],[207,new Uint8Array([24,24,24,255,0,255,0,0])],[208,new Uint8Array([54,54,54,255,0,0,0,0])],[209,new Uint8Array([0,0,0,255,0,255,24,24])],[210,new Uint8Array([0,0,0,255,54,54,54,54])],[211,new Uint8Array([24,24,24,31,0,31,0,0])],[212,new Uint8Array([54,54,54,62,0,0,0,0])],[213,new Uint8Array([0,0,0,31,0,31,24,24])],[214,new Uint8Array([0,0,0,62,54,54,54,54])],[215,new Uint8Array([24,24,24,255,24,255,24,24])],[216,new Uint8Array([54,54,54,255,54,54,54,54])],[217,new Uint8Array([24,24,24,248,0,0,0,0])],[218,new Uint8Array([0,0,0,31,24,24,24,24])],[219,new Uint8Array([255,255,255,255,255,255,255,255])],[220,new Uint8Array([0,0,0,0,255,255,255,255])],[221,new Uint8Array([240,240,240,240,240,240,240,240])],[222,new Uint8Array([15,15,15,15,15,15,15,15])],[223,new Uint8Array([255,255,255,255,0,0,0,0])],[224,new Uint8Array([0,0,123,207,207,123,0,0])],[225,new Uint8Array([124,102,102,124,102,102,108,96])],[226,new Uint8Array([126,102,96,96,96,96,96,0])],[227,new Uint8Array([0,0,127,54,54,54,54,0])],[228,new Uint8Array([126,96,48,24,48,96,126,0])],[229,new Uint8Array([0,0,63,102,102,102,60,0])],[230,new Uint8Array([0,0,102,102,102,124,96,96])],[231,new Uint8Array([0,0,126,24,24,24,24,0])],[232,new Uint8Array([24,126,219,219,219,126,24,0])],[233,new Uint8Array([60,102,102,126,102,102,60,0])],[234,new Uint8Array([60,102,102,102,60,102,102,0])],[235,new Uint8Array([28,48,24,60,102,102,60,0])],[236,new Uint8Array([0,0,110,219,219,118,0,0])],[237,new Uint8Array([6,12,126,219,219,126,96,192])],[238,new Uint8Array([30,48,96,126,96,48,30,0])],[239,new Uint8Array([60,102,102,102,102,102,0,0])],[240,new Uint8Array([0,126,0,126,0,126,0,0])],[241,new Uint8Array([24,24,126,24,24,0,126,0])],[242,new Uint8Array([48,24,12,24,48,0,126,0])],[243,new Uint8Array([12,24,48,24,12,0,126,0])],[244,new Uint8Array([14,27,27,24,24,24,24,24])],[245,new Uint8Array([24,24,24,24,24,216,216,112])],[246,new Uint8Array([0,24,0,126,0,24,0,0])],[247,new Uint8Array([0,118,220,0,118,220,0,0])],[248,new Uint8Array([56,108,108,56,0,0,0,0])],[249,new Uint8Array([0,0,0,24,24,0,0,0])],[250,new Uint8Array([0,0,0,0,24,0,0,0])],[251,new Uint8Array([15,12,12,12,236,108,60,28])],[252,new Uint8Array([108,54,54,54,54,0,0,0])],[253,new Uint8Array([120,12,24,48,124,0,0,0])],[254,new Uint8Array([0,0,60,60,60,60,0,0])],[255,new Uint8Array([0,0,0,0,0,0,0,0])]]);function QI(r){return Ru.get(r)}J(QI,"getCharBitmap");function JI(r){return Ru.has(r)}J(JI,"hasChar");function ek(){return Array.from(Ru.keys()).sort((r,e)=>r-e)}J(ek,"getAllCharCodes");function tk(){return{charWidth:8,charHeight:8,glyphs:new Map(Ru)}}J(tk,"getASCII8x8FontConfig");var Vv=class{encode(e){switch(e.type){case 1:return this.encodeClick(e);case 2:return this.encodeChange(e);case 3:return this.encodeSubmit(e);case 4:return this.encodeSelect(e);default:throw new Error(`Unknown macro event type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return 2;case 2:return this.calculateChangeSize(e);case 3:return this.calculateSubmitSize(e);case 4:return 4;default:throw new Error(`Unknown macro event type: ${e.type}`)}}encodeClick(e){let t=ie.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let t=ie.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt8(1,2),t.writeUInt8(e.value?1:0,3),t.toUint8Array()}else{let t=ie.allocUnsafe(7);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt8(0,2),t.writeFloatBE(e.value,3),t.toUint8Array()}}calculateChangeSize(e){return typeof e.value=="boolean"?4:7}encodeSubmit(e){let t=new TextEncoder().encode(e.text);if(t.length>65535)throw new Error(`Submit text too large: ${t.length} bytes (max 65535)`);let n=4+t.length,i=ie.allocUnsafe(n),s=0;return i.writeUInt8(e.type,s++),i.writeUInt8(e.instanceId,s++),i.writeUInt16BE(t.length,s),s+=2,i.toUint8Array().set(t,s),i.toUint8Array()}calculateSubmitSize(e){return 4+new TextEncoder().encode(e.text).length}encodeSelect(e){let t=ie.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};J(Vv,"MacroEventEncoder");var rk=Vv;function Hv(r,e,t,n,i,s,o,a=[],l=[],u=[],c=[],d=!1){let h=Array.from(e.entries()).sort((T,_)=>T[0]-_[0]),f=Array.from(t.entries()).sort((T,_)=>T[0]-_[0]),p=h.length,m=f.length,S=sv(p,m),w=new TextEncoder,g=a.map(T=>w.encode(T)),y=1+g.reduce((T,_)=>T+1+_.length,0),C=new rk,x=l.map(T=>C.encode(T)),I=1+x.reduce((T,_)=>T+_.length,0),E=Math.min(u.length,255),A=1+E*5,R=Math.min(c.length,10),F=1+R*4,z=S+y+I+A+F,P=new Uint8Array(z),O=new DataView(P.buffer),L=0;O.setBigUint64(L,r,!0),L+=8;for(let[,T]of h){let _=nv(T);P[L]=_+256&255,L+=1}let V=Tu(m);for(let T=0;T<V;T++){let _=0;for(let j=0;j<8;j++){let G=T*8+j;if(G<m){let[,ee]=f[G];ee&&(_|=1<<j)}}P[L]=_,L+=1}P[L]=n&255,L+=1,P[L]=i&255,L+=1,P[L]=s&255,L+=1;let X=0;o&&(X|=1),d&&(X|=2),P[L]=X,L+=1,P[L]=Math.min(a.length,255),L+=1;for(let T of g)P[L]=Math.min(T.length,255),L+=1,P.set(T.slice(0,255),L),L+=T.length;P[L]=Math.min(l.length,255),L+=1;for(let T of x)P.set(T,L),L+=T.length;P[L]=E,L+=1;for(let T=0;T<E;T++){let _=u[T];P[L]=_.displayId&255,L+=1,O.setUint16(L,Math.min(_.pixelWidth,65535),!1),L+=2,O.setUint16(L,Math.min(_.pixelHeight,65535),!1),L+=2}P[L]=R,L+=1;for(let T=0;T<R;T++){let _=c[T];P[L]=_.id&15,L+=1,P[L]=_.x&255,L+=1,P[L]=_.y&255,L+=1,P[L]=_.over?1:0,L+=1}return P}J(Hv,"encodeCompressedInput");var nk=class gt{static toCharCode(e){if(typeof e=="number")return e&65535;if(e.length===0)return 0;let t=e.charCodeAt(0);return Qs(t)}static dedent(e){let t=e.split(`
|
|
52
|
+
`}),e}};J(tv,"InputBindingRegistry");var fI=tv;function rv(r=0n){return{tick:r,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[],isTabHidden:!1}}J(rv,"createEmptyCompressedInputPacket");function nv(r){let e=Math.max(-1,Math.min(1,r));return Math.round(e*127)}J(nv,"encodeAxisToInt8");function iv(r){return r/127}J(iv,"decodeInt8ToAxis");function Tu(r){return r===0?0:Math.ceil(r/8)}J(Tu,"getButtonByteCount");function sv(r,e){let t=r,n=Tu(e);return 8+t+n+4}J(sv,"getCompressedPacketSize");var ov=class{decode(e,t=0){let n=e.readUInt8(t);switch(n){case 1:return this.decodeClick(e,t);case 2:return this.decodeChange(e,t);case 3:return this.decodeSubmit(e,t);case 4:return this.decodeSelect(e,t);default:throw new Error(`Unknown macro event type: 0x${n.toString(16)}`)}}decodeAll(e,t,n){let i=[],s=0;for(let o=0;o<n;o++){let{event:a,bytesRead:l}=this.decode(e,t+s);i.push(a),s+=l}return{events:i,bytesRead:s}}decodeClick(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1);return{event:{type:n,instanceId:i},bytesRead:2}}decodeChange(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1),s=e.readUInt8(t+2),o,a;return s===1?(o=e.readUInt8(t+3)===1,a=4):(o=e.readFloatBE(t+3),a=7),{event:{type:n,instanceId:i,value:o},bytesRead:a}}decodeSubmit(e,t){let n=t,i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+o);t+=o;let l=new TextDecoder().decode(a);return{event:{type:i,instanceId:s,text:l},bytesRead:t-n}}decodeSelect(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1),s=e.readUInt16BE(t+2);return{event:{type:n,instanceId:i,index:s},bytesRead:4}}};J(ov,"MacroEventDecoder");var pI=ov,av=class Zi{constructor(e){O(this,"data"),O(this,"view"),this.data=new Uint8Array(e),this.view=new DataView(this.data.buffer)}static from(e){let t=new Zi(0);return t.data=e,t.view=new DataView(e.buffer,e.byteOffset,e.byteLength),t}static allocUnsafe(e){return new Zi(e)}get length(){return this.data.length}toUint8Array(){return this.data}readUInt8(e){return this.view.getUint8(e)}readInt8(e){return this.view.getInt8(e)}readUInt16BE(e){return this.view.getUint16(e,!1)}readInt16BE(e){return this.view.getInt16(e,!1)}readUInt16LE(e){return this.view.getUint16(e,!0)}readInt16LE(e){return this.view.getInt16(e,!0)}readUInt32BE(e){return this.view.getUint32(e,!1)}readInt32BE(e){return this.view.getInt32(e,!1)}readUInt32LE(e){return this.view.getUint32(e,!0)}readInt32LE(e){return this.view.getInt32(e,!0)}readBigUInt64BE(e){return this.view.getBigUint64(e,!1)}readBigInt64BE(e){return this.view.getBigInt64(e,!1)}readBigUInt64LE(e){return this.view.getBigUint64(e,!0)}readBigInt64LE(e){return this.view.getBigInt64(e,!0)}writeUInt8(e,t){this.view.setUint8(t,e)}writeInt8(e,t){this.view.setInt8(t,e)}writeUInt16BE(e,t){this.view.setUint16(t,e,!1)}writeInt16BE(e,t){this.view.setInt16(t,e,!1)}writeUInt16LE(e,t){this.view.setUint16(t,e,!0)}writeInt16LE(e,t){this.view.setInt16(t,e,!0)}writeUInt32BE(e,t){this.view.setUint32(t,e,!1)}writeInt32BE(e,t){this.view.setInt32(t,e,!1)}writeUInt32LE(e,t){this.view.setUint32(t,e,!0)}writeInt32LE(e,t){this.view.setInt32(t,e,!0)}writeBigUInt64BE(e,t){this.view.setBigUint64(t,e,!1)}writeBigInt64BE(e,t){this.view.setBigInt64(t,e,!1)}writeBigUInt64LE(e,t){this.view.setBigUint64(t,e,!0)}writeBigInt64LE(e,t){this.view.setBigInt64(t,e,!0)}readFloatBE(e){return this.view.getFloat32(e,!1)}readFloatLE(e){return this.view.getFloat32(e,!0)}writeFloatBE(e,t){this.view.setFloat32(t,e,!1)}writeFloatLE(e,t){this.view.setFloat32(t,e,!0)}copy(e,t=0,n=0,i=this.length){let s=this.data.subarray(n,i);return e.data.set(s,t),s.length}slice(e,t){let n=this.data.slice(e,t);return Zi.from(n)}subarray(e,t){let n=this.data.subarray(e,t);return Zi.from(n)}toBuffer(){return typeof Buffer<"u"&&Buffer.from?Buffer.from(this.data):this.data}static fromNodeBuffer(e){return e instanceof Uint8Array?Zi.from(e):Zi.from(new Uint8Array(e))}};J(av,"BufferCompat");var ie=av,gI=new TextDecoder,mI=new pI;function lv(r,e){let t=e.getAllAxes().length,n=e.getAllButtons().length,i=Tu(n),s=8+t+i+4;if(r.length<s)throw new Error(`Invalid compressed input packet: expected at least ${s} bytes (${t} axes + ${n} buttons), got ${r.length}`);let o=new DataView(r.buffer,r.byteOffset,r.byteLength),a=0,l=rv();l.tick=o.getBigUint64(a,!0),a+=8;for(let c=0;c<t;c++){let d=r[a],h=d>127?d-256:d,f=iv(h);l.axes.set(c,f),a+=1}for(let c=0;c<i;c++){let d=r[a];for(let h=0;h<8;h++){let f=c*8+h;if(f<n){let p=(d&1<<h)!==0;l.buttons.set(f,p)}}a+=1}l.displayId=r[a],a+=1,l.mouseX=r[a],a+=1,l.mouseY=r[a],a+=1;let u=r[a];if(l.mouseOverDisplay=(u&1)!==0,l.isTabHidden=(u&2)!==0,a+=1,a<r.length){let c=r[a];a+=1,l.textInputs=[];for(let d=0;d<c&&a<r.length;d++){let h=r[a];if(a+=1,a+h<=r.length){let f=r.slice(a,a+h),p=gI.decode(f);l.textInputs.push(p),a+=h}}}if(a<r.length){let c=r[a];a+=1;let d=[],h=ie.from(r);for(let f=0;f<c&&a<r.length;f++){let p=mI.decode(h,a);d.push(p.event),a+=p.bytesRead}l.macroEvents=d}if(a<r.length){let c=r[a];a+=1;for(let d=0;d<c&&a+5<=r.length;d++){let h=r[a];a+=1;let f=o.getUint16(a,!1);a+=2;let p=o.getUint16(a,!1);a+=2,l.displayViewports.push({displayId:h,pixelWidth:f,pixelHeight:p})}}if(a<r.length){let c=Math.min(r[a],10);a+=1;for(let d=0;d<c&&a+4<=r.length;d++){let h=r[a]&15;a+=1;let f=r[a];a+=1;let p=r[a];a+=1;let m=(r[a]&1)!==0;a+=1,l.touchPositions.push({id:h,x:f,y:p,over:m})}}return l}J(lv,"decodeCompressedInput");var uv=class{constructor(e,t){O(this,"enabled",!1),O(this,"currentStats",null),O(this,"_userId"),O(this,"_userName"),this._userId=e,this._userName=t}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get userId(){var e;return((e=this.currentStats)==null?void 0:e.userId)??this._userId}get userName(){var e;return((e=this.currentStats)==null?void 0:e.userName)??this._userName}get tick(){var e;return((e=this.currentStats)==null?void 0:e.tick)??0}get timestamp(){var e;return((e=this.currentStats)==null?void 0:e.timestamp)??0}get displayCount(){var e;return((e=this.currentStats)==null?void 0:e.displayCount)??0}get totalDisplayArea(){var e;return((e=this.currentStats)==null?void 0:e.totalDisplayArea)??0}get totalLayers(){var e;return((e=this.currentStats)==null?void 0:e.totalLayers)??0}get visibleLayers(){var e;return((e=this.currentStats)==null?void 0:e.visibleLayers)??0}get staticLayers(){var e;return((e=this.currentStats)==null?void 0:e.staticLayers)??0}get dynamicLayers(){var e;return((e=this.currentStats)==null?void 0:e.dynamicLayers)??0}get totalOrders(){var e;return((e=this.currentStats)==null?void 0:e.totalOrders)??0}get ordersByLayer(){var e;return((e=this.currentStats)==null?void 0:e.ordersByLayer)??new Map}get staticPacketSize(){var e;return((e=this.currentStats)==null?void 0:e.staticPacketSize)??0}get dynamicPacketSize(){var e;return((e=this.currentStats)==null?void 0:e.dynamicPacketSize)??0}get totalPacketSize(){var e;return((e=this.currentStats)==null?void 0:e.totalPacketSize)??0}get compressedPacketSize(){return Math.round(this.totalPacketSize*.25)}get hasInput(){var e;return((e=this.currentStats)==null?void 0:e.hasInput)??!1}get axisCount(){var e;return((e=this.currentStats)==null?void 0:e.axisCount)??0}get buttonCount(){var e;return((e=this.currentStats)==null?void 0:e.buttonCount)??0}startTick(e){this.enabled&&(this.currentStats={userId:this._userId,userName:this._userName,tick:e,timestamp:Date.now(),displayCount:0,totalDisplayArea:0,totalLayers:0,visibleLayers:0,staticLayers:0,dynamicLayers:0,totalOrders:0,ordersByLayer:new Map,staticPacketSize:0,dynamicPacketSize:0,totalPacketSize:0,hasInput:!1,axisCount:0,buttonCount:0})}recordDisplays(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCount=e,this.currentStats.totalDisplayArea=t)}recordLayers(e,t,n,i){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t,this.currentStats.staticLayers=n,this.currentStats.dynamicLayers=i)}recordLayerOrders(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalOrders+=t,this.currentStats.ordersByLayer.set(e,t))}recordPacketSizes(e,t){!this.enabled||!this.currentStats||(this.currentStats.staticPacketSize=e,this.currentStats.dynamicPacketSize=t,this.currentStats.totalPacketSize=e+t)}recordInput(e,t,n){!this.enabled||!this.currentStats||(this.currentStats.hasInput=e,this.currentStats.axisCount=t,this.currentStats.buttonCount=n)}endTick(){}reset(){this.currentStats=null}};J(uv,"UserStats");var yI=uv,cv=class{constructor(e,t,n){this.id=e,this.name=t,O(this,"displays",[]),O(this,"layers",[]),O(this,"spriteRegistry"),O(this,"mode"),O(this,"axes",new Map),O(this,"buttons",new Map),O(this,"textInputs",[]),O(this,"mouseX",0),O(this,"mouseY",0),O(this,"mouseOver",!1),O(this,"mouseDisplayId",0),O(this,"isTabHidden",!1),O(this,"touchPositions",new Map),O(this,"activeTouchId",null),O(this,"inputBindings",new fI),O(this,"stats"),O(this,"soundCommands",[]),O(this,"nextSoundInstanceId",1),O(this,"audioConfigCommands",[]),O(this,"lastListenerX",-1),O(this,"lastListenerY",-1),O(this,"pendingSendSounds",!1),O(this,"audioProcessor"),O(this,"loadedSounds",new Map),O(this,"soundLoadErrors",new Map),O(this,"playingSounds",new Map),O(this,"mobileVibrationCommands",[]),O(this,"mobileVibrationProcessor"),O(this,"gamepadVibrationCommands",[]),O(this,"gamepadVibrationProcessor"),O(this,"macroRegistry",new nI),O(this,"macroEngine",new hI),O(this,"macroEventHandlers",new Map),O(this,"postProcessCommands",[]),O(this,"currentPostProcessConfig",null),O(this,"bridgeMessages",[]),O(this,"totalBytesSent",0),O(this,"totalBytesReceived",0),O(this,"bytesSentPerTick",[]),O(this,"bytesReceivedPerTick",[]),O(this,"bytesTickIndex",0),O(this,"bytesTickRate",20),O(this,"currentTickBytesSent",0),O(this,"currentTickBytesReceived",0),O(this,"lastInputTick",-1n),O(this,"availableViewports",new Map),O(this,"displayCommandSink",{setPostProcess:(i,s)=>this.setPostProcess(i,s),setScanlinesEnabled:(i,s)=>this.setScanlinesEnabled(i,s),setScanlinesOpacity:(i,s)=>this.setScanlinesOpacity(i,s),setScanlinesPattern:(i,s)=>this.setScanlinesPattern(i,s),setAmbientEffect:(i,s)=>this.setAmbientEffect(i,s),setAmbientEffectEnabled:(i,s)=>this.setAmbientEffectEnabled(i,s),setAmbientEffectBlur:(i,s)=>this.setAmbientEffectBlur(i,s),setAmbientEffectScale:(i,s)=>this.setAmbientEffectScale(i,s),isAmbientEffectEnabled:()=>this.isAmbientEffectEnabled(),getAmbientEffectConfig:()=>this.getAmbientEffectConfig(),getPostProcessConfig:()=>this.getPostProcessConfig(),setScalingMode:(i,s)=>this.setScalingMode(i,s),getScalingMode:i=>this.getScalingMode(i),setCellSize:(i,s,o)=>this.setCellSize(i,s,o),getCellSize:i=>this.getCellSize(i),setGrid:(i,s)=>this.setGrid(i,s),setGridEnabled:(i,s)=>this.setGridEnabled(i,s),isGridEnabled:i=>this.isGridEnabled(i),getGridConfig:i=>this.getGridConfig(i),switchPalette:(i,s)=>this.switchPalette(i,s),getCurrentPaletteSlotId:i=>this.getCurrentPaletteSlotId(i)}),O(this,"data"),O(this,"currentScalingModes",new Map),O(this,"currentCellSizes",new Map),O(this,"currentGridConfigs",new Map),O(this,"currentPaletteSlotIds",new Map),this.mode=n,this.stats=new yI(e,t),this.data={}}setSpriteRegistry(e){this.spriteRegistry=e;for(let t of this.layers)t.setSpriteRegistry(e);this.macroEngine.setSpriteRegistry(e)}getDisplays(){return this.displays}addDisplay(e){e.setCommandSink(this.displayCommandSink),this.displays.push(e)}removeDisplay(e){let t=this.displays.indexOf(e);return t!==-1?(this.displays.splice(t,1),!0):!1}clearDisplays(){this.displays=[]}setDisplayViewport(e,t,n){this.availableViewports.set(e,{pixelWidth:t,pixelHeight:n})}getDisplayViewport(e){return this.availableViewports.get(e)??null}getAllDisplayViewports(){return this.availableViewports}calculateMaxCells(e,t,n){let i=this.availableViewports.get(e);return i?{cols:Math.floor(i.pixelWidth/t),rows:Math.floor(i.pixelHeight/n)}:null}getLayers(){return this.layers}getLayerById(e){return this.layers.find(t=>t.getId()===e)}addLayer(e,t){e.setMode(this.mode);let n=this.layers.length+1;Aa(e,n),this.layers.push(e),this.spriteRegistry&&e.setSpriteRegistry(this.spriteRegistry),t&&this.macroRegistry.setLayerMapping(t,e.getId())}removeLayer(e){let t=this.layers.indexOf(e);return t!==-1?(this.layers.splice(t,1),!0):!1}clearLayers(){this.layers=[]}setMousePosition(e,t,n=!0){this.mouseX=Math.max(0,Math.min(255,e)),this.mouseY=Math.max(0,Math.min(255,t)),this.mouseOver=n}setTouchPosition(e,t,n,i=!0,s=0){if(e<0||e>9){console.warn(`Invalid touchId ${e}, must be 0-9`);return}i?(this.touchPositions.set(e,{x:Math.max(0,Math.min(255,t)),y:Math.max(0,Math.min(255,n)),over:!0,displayId:s}),this.activeTouchId=e):(this.touchPositions.delete(e),this.activeTouchId===e&&(this.activeTouchId=null))}setAxis(e,t){let n=Math.max(-1,Math.min(1,t));this.axes.set(e,n)}getAxis(e){return this.axes.get(e)??0}setButton(e,t){this.buttons.set(e,t)}getButton(e){return this.buttons.get(e)??!1}getButtonJustPressed(e){let t=`${e}_justPressed`;return this.buttons.get(t)??!1}getButtonJustReleased(e){let t=`${e}_justReleased`;return this.buttons.get(t)??!1}setTextInputs(e){this.textInputs=e}getTextInputs(){return this.textInputs}clearTextInputs(){this.textInputs=[]}getAxisNames(){return Array.from(this.axes.keys())}getButtonNames(){return Array.from(this.buttons.keys())}clearAxes(){this.axes.clear()}clearButtons(){this.buttons.clear()}getMouseDisplayInfo(){if(!this.mouseOver||this.displays.length===0)return null;let e=this.displays[0],t=0,n=this.mouseX,i=this.mouseY,s=e.getOrigin(),o=s.x+n,a=s.y+i;return{displayId:t,localX:n,localY:i,worldX:o,worldY:a}}getTouchDisplayInfo(e=0){if(e<0||e>9)return console.warn(`Invalid touchId ${e}, must be 0-9`),null;let t=this.touchPositions.get(e);if(!t||!t.over||this.displays.length===0)return null;let n=this.displays[0],i=t.displayId,s=t.x,o=t.y,a=n.getOrigin(),l=a.x+s,u=a.y+o;return{displayId:i,localX:s,localY:o,worldX:l,worldY:u}}getIsMouseOnADisplay(){return this.mouseOver}getMouseDisplayHover(){let e=this.getMouseDisplayInfo();return e?e.displayId:null}findLayerById(e){return this.layers.find(t=>t.getId()===e)??null}applyUpdate(e){if(this.updateDisplaysFromPacket(e.displays),this.updateLayersFromPacket(e.layers),e.macroOrders&&e.macroOrders.length>0)for(let t of e.macroOrders)this.macroEngine.applyOrder(t)}updateDisplaysFromPacket(e){for(let t of e){let n=this.displays[t.id];if(!n){for(n=new px(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=n}n.setCommandSink(this.displayCommandSink),n.setOrigin(new Yt(t.originX,t.originY)),n.setSize(new Yt(t.sizeX,t.sizeY)),n.setRenderPasses(t.renderPasses)}}updateLayersFromPacket(e){for(let t of e){let n=this.findLayerById(t.id);n||(n=new Zx(new Yt(t.originX,t.originY),t.zIndex,t.width,t.height,{mustBeReliable:!1,isMacroLayer:t.isMacroLayer,charCodeMode:t.is16bit?"16bit":"8bit"}),Aa(n,t.id),n.setMode(this.mode),this.spriteRegistry&&n.setSpriteRegistry(this.spriteRegistry),this.addLayer(n)),t.updateFlags&1&&n.setOrigin(new Yt(t.originX,t.originY)),t.updateFlags&2&&n.setZOrder(t.zIndex),t.updateFlags&4&&n.setOrders(t.orders)}}defineAxisBinding(e,t,n=[],i=-1,s=1,o=0){this.inputBindings.defineAxis(e,t,n,i,s,o)}defineButtonBinding(e,t,n=[],i=!1){this.inputBindings.defineButton(e,t,n,i)}defineAxisBindings(e){e.forEach(({bindingId:t,name:n,sources:i,min:s,max:o,defaultValue:a})=>{this.defineAxisBinding(t,n,i??[],s,o,a)})}defineButtonBindings(e){e.forEach(({bindingId:t,name:n,sources:i,defaultValue:s})=>{this.defineButtonBinding(t,n,i??[],s)})}getInputBindingsLoadPacket(){return this.inputBindings.toLoadPacket()}applyInputBindingsLoadPacket(e){try{let t=JSON.parse(e);if(t.type!=="input-binding")throw new Error(`Invalid packet type: ${t.type}`);this.inputBindings.clear();for(let n of t.axes)this.defineAxisBinding(n.bindingId,n.name,n.sources||[],n.min,n.max,n.defaultValue);for(let n of t.buttons)this.defineButtonBinding(n.bindingId,n.name,n.sources||[],n.defaultValue)}catch(t){throw console.error("[User] Failed to apply input bindings:",t),t}}getInputBindingRegistry(){return this.inputBindings}getStats(){return this.stats}getTotalBytesSent(){return this.totalBytesSent}getTotalBytesReceived(){return this.totalBytesReceived}recordBytesSent(e){this.totalBytesSent+=e,this.currentTickBytesSent+=e}recordBytesReceived(e){this.totalBytesReceived+=e,this.currentTickBytesReceived+=e}resetByteCounters(){this.totalBytesSent=0,this.totalBytesReceived=0}setBytesTickRate(e){e<=0||(this.bytesTickRate=e,this.bytesSentPerTick=new Array(e).fill(0),this.bytesReceivedPerTick=new Array(e).fill(0),this.bytesTickIndex=0)}endTickBytes(){this.bytesSentPerTick.length!==this.bytesTickRate&&(this.bytesSentPerTick=new Array(this.bytesTickRate).fill(0),this.bytesReceivedPerTick=new Array(this.bytesTickRate).fill(0)),this.bytesSentPerTick[this.bytesTickIndex]=this.currentTickBytesSent,this.bytesReceivedPerTick[this.bytesTickIndex]=this.currentTickBytesReceived,this.bytesTickIndex=(this.bytesTickIndex+1)%this.bytesTickRate,this.currentTickBytesSent=0,this.currentTickBytesReceived=0}getBytesSentPerSecond(){return this.bytesSentPerTick.reduce((e,t)=>e+t,0)}getBytesReceivedPerSecond(){return this.bytesReceivedPerTick.reduce((e,t)=>e+t,0)}getAxisBindingId(e){return this.inputBindings.getAxisBindingId(e)}getButtonBindingId(e){return this.inputBindings.getButtonBindingId(e)}decodeAndApplyCompressedInput(e){let t=lv(e,this.inputBindings);this.lastInputTick=t.tick;let n=this.inputBindings.getAllAxes(),i=this.inputBindings.getAllButtons(),s=n.sort((a,l)=>a.bindingId-l.bindingId),o=i.sort((a,l)=>a.bindingId-l.bindingId);for(let[a,l]of t.axes)if(a<s.length){let u=s[a];this.setAxis(u.name,l)}for(let[a,l]of t.buttons)if(a<o.length){let u=o[a],c=this.getButton(u.name);this.setButton(u.name,l);let d=l&&!c,h=!l&&c;this.setButton(`${u.name}_justPressed`,d),this.setButton(`${u.name}_justReleased`,h)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId,this.isTabHidden=t.isTabHidden;for(let a of t.touchPositions)this.setTouchPosition(a.id,a.x,a.y,a.over);for(let a of t.displayViewports)this.setDisplayViewport(a.displayId,a.pixelWidth,a.pixelHeight)}playSound(e,t){let n=this.nextSoundInstanceId++,i={sound:e,instanceId:n,volume:t==null?void 0:t.volume,pitch:t==null?void 0:t.pitch,loop:t==null?void 0:t.loop,fadeIn:t==null?void 0:t.fadeIn,x:t==null?void 0:t.x,y:t==null?void 0:t.y,lowpass:t==null?void 0:t.lowpass,highpass:t==null?void 0:t.highpass,reverb:t==null?void 0:t.reverb};return this.soundCommands.push(i),n}stopSound(e){let t={sound:e};this.soundCommands.push(t)}fadeOutSound(e,t){let n={fadeOut:!0,sound:e,duration:t};this.soundCommands.push(n)}fadeOutAllSounds(e){let t={fadeOut:!0,sound:"all",duration:e};this.soundCommands.push(t)}stopAllSounds(){let e={sound:"all"};this.soundCommands.push(e)}pauseSound(e){let t={pause:!0,sound:e};this.soundCommands.push(t)}pauseAllSounds(){let e={pause:!0,sound:"all"};this.soundCommands.push(e)}resumeSound(e){let t={resume:!0,sound:e};this.soundCommands.push(t)}resumeAllSounds(){let e={resume:!0,sound:"all"};this.soundCommands.push(e)}setSoundEffects(e,t){let n={setEffects:!0,instanceId:e,lowpass:t.lowpass,highpass:t.highpass,reverb:t.reverb};this.soundCommands.push(n)}setListenerPosition(e,t){e===this.lastListenerX&&t===this.lastListenerY||(this.lastListenerX=e,this.lastListenerY=t,this.audioConfigCommands.push({type:"set-listener-position",x:e,y:t}))}configureSpatialAudio(e){this.audioConfigCommands.push({type:"configure-spatial",...e})}flushAudioConfigCommands(){let e=this.audioConfigCommands;return this.audioConfigCommands=[],e}hasAudioConfigCommands(){return this.audioConfigCommands.length>0}flushSoundCommands(){let e=this.soundCommands;return this.soundCommands=[],e}hasSoundCommands(){return this.soundCommands.length>0}sendSounds(){this.pendingSendSounds=!0}needsSendSounds(){return this.pendingSendSounds}clearSendSounds(){this.pendingSendSounds=!1}setAudioProcessor(e){this.audioProcessor=e,this.macroEngine.setAudioCallback(t=>{e.play(t)})}getAudioProcessor(){return this.audioProcessor}applyAudioCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e){if("setEffects"in t&&t.setEffects===!0){let n=t;this.audioProcessor.setEffects(n.instanceId,n.lowpass,n.highpass,n.reverb);continue}if("fadeOut"in t&&t.fadeOut===!0){let n=t;this.audioProcessor.fadeOut(n.sound,n.duration);continue}if("pause"in t&&t.pause===!0){let n=t;this.audioProcessor.pause(n.sound);continue}if("resume"in t&&t.resume===!0){let n=t;this.audioProcessor.resume(n.sound);continue}if("instanceId"in t||"volume"in t||"pitch"in t||"loop"in t||"fadeIn"in t||"x"in t||"y"in t||"lowpass"in t||"highpass"in t||"reverb"in t){let n=t,i=n.x!==void 0&&n.y!==void 0?{x:n.x,y:n.y}:void 0;this.audioProcessor.play(n.sound,{volume:n.volume,pitch:n.pitch,loop:n.loop,fadeIn:n.fadeIn,position:i,instanceId:n.instanceId,lowpass:n.lowpass,highpass:n.highpass,reverb:n.reverb})}else{let n=t;n.sound==="all"?this.audioProcessor.stopAll():this.audioProcessor.stop(n.sound)}}}applyAudioConfigCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e)t.type==="set-listener-position"?this.audioProcessor.setListenerPosition(t.x,t.y):t.type==="configure-spatial"&&this.audioProcessor.configureSpatial({maxDistance:t.maxDistance,referenceDistance:t.referenceDistance,rolloffFactor:t.rolloffFactor,panSpread:t.panSpread})}vibrate(e){let t={pattern:e};this.mobileVibrationCommands.push(t)}cancelVibration(){let e={cancel:!0};this.mobileVibrationCommands.push(e)}vibrateTap(){this.vibrate(10)}vibrateMediumTap(){this.vibrate(25)}vibrateHeavyTap(){this.vibrate(50)}vibrateSuccess(){this.vibrate([30,50,30])}vibrateError(){this.vibrate([50,30,50,30,50])}vibrateWarning(){this.vibrate([100])}vibrateSelection(){this.vibrate(5)}vibrateImpact(e="medium"){let t={light:15,medium:30,heavy:50};this.vibrate(t[e])}vibrateNotification(){this.vibrate([100,100,100,100,100])}vibrateGamepad(e,t){let n={gamepadIndex:e,options:t};this.gamepadVibrationCommands.push(n)}stopGamepadVibration(e="all"){let t={gamepadIndex:e,cancel:!0};this.gamepadVibrationCommands.push(t)}gamepadTap(e=0){this.vibrateGamepad(e,{duration:50,strongMagnitude:.3,weakMagnitude:.5})}gamepadImpact(e=0){this.vibrateGamepad(e,{duration:100,strongMagnitude:.7,weakMagnitude:.3})}gamepadHeavy(e=0){this.vibrateGamepad(e,{duration:200,strongMagnitude:1,weakMagnitude:.2})}gamepadExplosion(e=0){this.vibrateGamepad(e,{duration:400,strongMagnitude:1,weakMagnitude:.8})}gamepadSuccess(e=0){this.vibrateGamepad(e,{duration:150,strongMagnitude:.4,weakMagnitude:.6})}gamepadError(e=0){this.vibrateGamepad(e,{duration:300,strongMagnitude:.8,weakMagnitude:.4})}hasGamepadVibrationCommands(){return this.gamepadVibrationCommands.length>0}flushGamepadVibrationCommands(){let e=this.gamepadVibrationCommands;return this.gamepadVibrationCommands=[],e}setGamepadVibrationProcessor(e){this.gamepadVibrationProcessor=e}applyGamepadVibrationCommands(e){if(this.gamepadVibrationProcessor&&this.mode!=="server"){for(let t of e)if("cancel"in t&&t.cancel===!0)t.gamepadIndex==="all"?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(t.gamepadIndex);else if("options"in t){let n=t;if(n.gamepadIndex==="all")for(let i=0;i<4;i++)this.gamepadVibrationProcessor.vibrate(i,n.options);else this.gamepadVibrationProcessor.vibrate(n.gamepadIndex,n.options)}}}hasMobileVibrationCommands(){return this.mobileVibrationCommands.length>0}flushMobileVibrationCommands(){let e=this.mobileVibrationCommands;return this.mobileVibrationCommands=[],e}setMobileVibrationProcessor(e){this.mobileVibrationProcessor=e}getMobileVibrationProcessor(){return this.mobileVibrationProcessor}applyMobileVibrationCommands(e){if(this.mobileVibrationProcessor&&this.mode!=="server")for(let t of e)"cancel"in t&&t.cancel===!0?this.mobileVibrationProcessor.cancel():"pattern"in t&&this.mobileVibrationProcessor.vibrate(t.pattern)}applyVibrationOrders(e){if(this.mode==="server")return;let{VibrationOrderType:t}=(A1(),ul(U1)),{MobileVibrateFlags:n,GamepadVibrateFlags:i}=(R1(),ul(T1));for(let s of e)switch(s.type){case t.MobileVibrate:{if(!this.mobileVibrationProcessor)break;let o=s,a=o.pattern;o.flags&n.HasIntensity&&o.intensity!==void 0&&(a=a.map(l=>Math.round(l*o.intensity))),this.mobileVibrationProcessor.vibrate(a);break}case t.MobileCancel:{if(!this.mobileVibrationProcessor)break;this.mobileVibrationProcessor.cancel();break}case t.GamepadVibrate:{if(!this.gamepadVibrationProcessor)break;let o=s,a={duration:o.duration,strongMagnitude:o.strongMagnitude/255,weakMagnitude:o.weakMagnitude/255,startDelay:o.startDelay};if(o.flags&i.AllGamepads)for(let l=0;l<4;l++)this.gamepadVibrationProcessor.vibrate(l,a);else this.gamepadVibrationProcessor.vibrate(o.gamepadIndex,a);break}case t.GamepadCancel:{if(!this.gamepadVibrationProcessor)break;let o=s;o.flags&i.AllGamepads?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(o.gamepadIndex);break}}}applyAudioOrders(e){if(!this.audioProcessor||this.mode==="server")return;let{AudioOrderType:t,AudioTargetType:n}=(O1(),ul(P1)),{PlaySoundFlags:i}=(F1(),ul(D1));for(let s of e)switch(s.type){case t.PlaySound:case t.PlayGlobalSound:{let o=s,a=o.volume!==void 0?o.volume/255:void 0,l=o.pitch!==void 0?.25*Math.pow(2,o.pitch/64):void 0,u=o.fadeIn!==void 0?o.fadeIn/10:void 0,c=(o.flags&i.Loop)!==0,d=o.posX!==void 0&&o.posY!==void 0?{x:o.posX,y:o.posY}:void 0;this.audioProcessor.play(o.soundId,{volume:a,pitch:l,loop:c,fadeIn:u,position:d,instanceId:o.instanceId,lowpass:o.lowpass,highpass:o.highpass,reverb:o.reverb});break}case t.StopSound:{let o=s;o.targetType===n.All?this.audioProcessor.stopAll():o.targetType===n.InstanceId?this.audioProcessor.stop(o.target):this.audioProcessor.stop(o.target);break}case t.FadeOutSound:{let o=s,a=o.duration/10;o.targetType===n.All?this.audioProcessor.fadeOut("all",a):this.audioProcessor.fadeOut(o.target,a);break}case t.PauseSound:{let o=s;o.targetType===n.All?this.audioProcessor.pause("all"):this.audioProcessor.pause(o.target);break}case t.ResumeSound:{let o=s;o.targetType===n.All?this.audioProcessor.resume("all"):this.audioProcessor.resume(o.target);break}case t.SetListenerPosition:{let o=s;this.audioProcessor.setListenerPosition(o.x,o.y);break}case t.ConfigureSpatial:{let o=s;this.audioProcessor.configureSpatial({maxDistance:o.maxDistance*100,referenceDistance:o.referenceDistance*100,rolloffFactor:o.rolloffFactor/100,panSpread:o.panSpread/255});break}case t.SetSoundEffects:{let o=s;this.audioProcessor.setEffects(o.instanceId,o.lowpass,o.highpass,o.reverb);break}}}handleAudioAck(e){switch(e.type){case"sound-loaded":this.loadedSounds.set(e.soundId,{name:e.name,loadedAt:Date.now()}),this.soundLoadErrors.delete(e.soundId);break;case"sound-error":this.soundLoadErrors.set(e.soundId,{name:e.name,error:e.error,at:Date.now()});break;case"playback-started":this.playingSounds.set(e.instanceId,{soundId:e.soundId,startedAt:Date.now()});break;case"playback-ended":this.playingSounds.delete(e.instanceId);break;case"playback-error":e.instanceId!==void 0&&this.playingSounds.delete(e.instanceId);break}}isSoundLoaded(e){return this.loadedSounds.has(e)}getSoundLoadError(e){var t;return(t=this.soundLoadErrors.get(e))==null?void 0:t.error}getLoadedSounds(){return this.loadedSounds}getSoundLoadErrors(){return this.soundLoadErrors}isSoundPlaying(e){return this.playingSounds.has(e)}getPlayingSounds(){return this.playingSounds}getPlayingSoundCount(){return this.playingSounds.size}getAudioLoadingState(e){let t=this.loadedSounds.size,n=this.soundLoadErrors.size,i=e>0&&t>=e,s=Array.from(this.soundLoadErrors.values()).map(o=>o.name);return{loadedCount:t,totalExpected:e,errorCount:n,isComplete:i,errors:s}}loadMacro(e,t){let n={...t,id:e},i=this.macroRegistry.registerMacro(n);return this.mode==="client"&&this.macroEngine.loadTemplate(i,n),i}createInstance(e){return this.updateLayerMappings(),this.macroRegistry.createInstance(e)}updateInstance(e,t){return this.macroRegistry.updateInstance(e,t)}removeInstance(e){return this.macroEventHandlers.delete(e),this.macroRegistry.removeInstance(e)}onMacroEvent(e,t,n){this.macroEventHandlers.has(e)||this.macroEventHandlers.set(e,new Map),this.macroEventHandlers.get(e).set(t,n)}offMacroEvent(e,t){var n;t?(n=this.macroEventHandlers.get(e))==null||n.delete(t):this.macroEventHandlers.delete(e)}handleMacroEvent(e){let t=this.macroRegistry.getInstanceName(e.instanceId);if(!t){console.warn(`MacroEvent: Unknown instance ID ${e.instanceId}`);return}let n=this.macroEventHandlers.get(t);if(!n)return;let i,s;switch(e.type){case 1:i="click",s=void 0;break;case 2:i="change",s=e.value;break;case 3:i="submit",s=e.text;break;case 4:i="select",s=e.index;break;default:return}let o=n.get(i);o&&o(s)}flushMacroOrders(){return this.macroRegistry.flushPendingOrders()}hasPendingMacroOrders(){return this.macroRegistry.hasPendingOrders()}applyMacroOrders(e){for(let t of e)this.macroEngine.applyOrder(t)}getMacroRegistry(){return this.macroRegistry}getMacroLoads(){return this.macroRegistry.toAllMacroLoads()}updateLayerMappings(){for(let e of this.layers){let t=e.getName();t&&this.macroRegistry.setLayerMapping(t,e.getId())}}registerLayerName(e,t){this.macroRegistry.setLayerMapping(e,t.getId())}loadMacroTemplate(e,t){this.macroEngine.loadTemplate(e,t)}updateMacros(){return this.macroEngine.update()}processMacroEvents(e){for(let t of e.events){let n=this.macroRegistry.getInstanceName(t.instanceId);if(!n)continue;let i=this.macroEventHandlers.get(n);if(!i)continue;let s=i.get(t.event);s&&s(t.data)}}updateMacroMouse(e,t,n){let i=this.displays.find(s=>s.getId()===this.mouseDisplayId);if(!i&&this.displays.length>0&&(i=this.displays[0]),i){let s=i.getOrigin(),o=e+s.x,a=t+s.y;this.macroEngine.updateMouse(o,a,n)}else this.macroEngine.updateMouse(e,t,n)}getMacroRenderOrders(){let e=this.macroEngine.getOrdersByLayer(),t=this.displays[0];if(!t)return e;let n=t.getOrigin();if(n.x===0&&n.y===0)return e;let i=new Map;for(let[s,o]of e){let a=o.map(l=>{let u={...l};return"posX"in u&&typeof u.posX=="number"&&(u.posX=u.posX-n.x),"posY"in u&&typeof u.posY=="number"&&(u.posY=u.posY-n.y),u});i.set(s,a)}return i}getMacroEffectOffset(){return this.macroEngine.getEffectOffset()}getMacroEngine(){return this.macroEngine}macroFocusNext(){this.macroEngine.focusNext()}macroFocusPrevious(){this.macroEngine.focusPrevious()}macroActivateFocused(){this.macroEngine.activateFocused()}setPostProcess(e,t){let n=JSON.stringify(t),i=JSON.stringify(this.currentPostProcessConfig);n!==i&&(this.currentPostProcessConfig=t,this.postProcessCommands.push({type:"set-config",displayId:e,config:t??void 0}))}setScanlinesEnabled(e,t){var n;if(t){let i=(n=this.currentPostProcessConfig)==null?void 0:n.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:(i==null?void 0:i.opacity)??Ge.scanlines.opacity,pattern:(i==null?void 0:i.pattern)??Ge.scanlines.pattern,color:(i==null?void 0:i.color)??Ge.scanlines.color}})}else this.setPostProcess(e,{scanlines:{enabled:!1}})}setScanlinesOpacity(e,t){var s;let n=Math.max(0,Math.min(1,t)),i=(s=this.currentPostProcessConfig)==null?void 0:s.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:n,pattern:(i==null?void 0:i.pattern)??"horizontal",color:(i==null?void 0:i.color)??{r:0,g:0,b:0}}})}setScanlinesPattern(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.scanlines;this.setPostProcess(e,{scanlines:{enabled:(n==null?void 0:n.enabled)??!0,opacity:(n==null?void 0:n.opacity)??Ge.scanlines.opacity,pattern:t,color:(n==null?void 0:n.color)??{r:0,g:0,b:0}}})}setAmbientEffect(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.ambientEffect;typeof t=="boolean"?this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:t,blur:(n==null?void 0:n.blur)??Ge.ambientEffect.blur,scale:(n==null?void 0:n.scale)??Ge.ambientEffect.scale}}):this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:t.blur??(n==null?void 0:n.blur)??Ge.ambientEffect.blur,scale:t.scale??(n==null?void 0:n.scale)??Ge.ambientEffect.scale}})}setAmbientEffectEnabled(e,t){this.setAmbientEffect(e,t)}setAmbientEffectBlur(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:(n==null?void 0:n.enabled)??!0,blur:Math.max(0,t),scale:(n==null?void 0:n.scale)??Ge.ambientEffect.scale}})}setAmbientEffectScale(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:(n==null?void 0:n.enabled)??!0,blur:(n==null?void 0:n.blur)??Ge.ambientEffect.blur,scale:Math.max(1,t)}})}isAmbientEffectEnabled(){var e,t;return((t=(e=this.currentPostProcessConfig)==null?void 0:e.ambientEffect)==null?void 0:t.enabled)??!1}getAmbientEffectConfig(){var t;let e=(t=this.currentPostProcessConfig)==null?void 0:t.ambientEffect;return e?{enabled:e.enabled,blur:e.blur??Ge.ambientEffect.blur,scale:e.scale??Ge.ambientEffect.scale}:null}getPostProcessConfig(){return this.currentPostProcessConfig}hasPostProcessCommands(){return this.postProcessCommands.length>0}flushPostProcessCommands(){let e=this.postProcessCommands;return this.postProcessCommands=[],e}setScalingMode(e,t){this.currentScalingModes.get(e)!==t&&(this.currentScalingModes.set(e,t),this.postProcessCommands.push({type:"set-scaling-mode",displayId:e,scalingMode:t}))}getScalingMode(e){return this.currentScalingModes.get(e)??null}setCellSize(e,t,n){let i=Math.max(1,Math.min(255,Math.round(t))),s=Math.max(1,Math.min(255,Math.round(n))),o=this.currentCellSizes.get(e);o&&o.width===i&&o.height===s||(this.currentCellSizes.set(e,{width:i,height:s}),this.postProcessCommands.push({type:"set-cell-size",displayId:e,cellWidth:i,cellHeight:s}))}getCellSize(e){let t=this.currentCellSizes.get(e);return{cellWidth:(t==null?void 0:t.width)??8,cellHeight:(t==null?void 0:t.height)??8}}setGrid(e,t){let n;typeof t=="boolean"?n={enabled:t,color:js.color,lineWidth:js.lineWidth}:n={enabled:t.enabled,color:t.color??js.color,lineWidth:t.lineWidth??js.lineWidth},this.currentGridConfigs.set(e,n),this.postProcessCommands.push({type:"set-grid",displayId:e,gridConfig:n})}setGridEnabled(e,t){this.setGrid(e,t)}isGridEnabled(e){var t;return((t=this.currentGridConfigs.get(e))==null?void 0:t.enabled)??!1}getGridConfig(e){return this.currentGridConfigs.get(e)??null}switchPalette(e,t){if(t<0||t>255)throw new Error(`Palette slot ID must be between 0 and 255, got ${t}`);this.currentPaletteSlotIds.get(e)!==t&&(this.currentPaletteSlotIds.set(e,t),this.postProcessCommands.push({type:"switch-palette",displayId:e,paletteSlotId:t}))}getCurrentPaletteSlotId(e){return this.currentPaletteSlotIds.get(e)??null}sendBridge(e,t){this.bridgeMessages.push({channel:e,data:t})}getBridgeMessages(){let e=this.bridgeMessages;return this.bridgeMessages=[],e}hasBridgeMessages(){return this.bridgeMessages.length>0}getDebugInfo(){let e=Array.from(this.availableViewports.entries()).map(([t,n])=>({displayId:t,pixelWidth:n.pixelWidth,pixelHeight:n.pixelHeight}));return{id:this.id,name:this.name,bytesSentTotal:this.totalBytesSent,bytesSentTick:this.currentTickBytesSent,availableViewports:e,layers:this.layers.map(t=>t.getDebugInfo()),displays:this.displays.map(t=>t.getDebugInfo())}}};J(cv,"User");var vI=cv,dv=class{constructor(){O(this,"charCodeSize",_1)}encode(e,t=!1){switch(e.type){case 1:return this.encodeCharOrder(e,t);case 2:return this.encodeTextOrder(e);case 23:return this.encodeTextMultilineOrder(e);case 3:return this.encodeSubFrameOrder(e,t);case 4:return this.encodeSubFrameMultiColorOrder(e,t);case 5:return this.encodeFullFrameOrder(e,t);case 6:return this.encodeFullFrameMultiColorOrder(e,t);case 7:return this.encodeSpriteOrder(e);case 8:return this.encodeSpriteMultiColorOrder(e);case 9:return this.encodeColorMapOrder(e);case 10:return this.encodeShapeOrder(e,t);case 11:return this.encodeDotCloudOrder(e,t);case 12:return this.encodeDotCloudMultiColorOrder(e,t);case 17:return this.encodeBitmaskOrder(e,t);case 18:return this.encodeBitmask4Order(e,t);case 24:return this.encodeBitmask16Order(e,t);case 25:return this.encodePolylineOrder(e,t);case 13:return this.encodeSpriteCloudOrder(e);case 14:return this.encodeSpriteCloudMultiColorOrder(e);case 15:return this.encodeSpriteCloudVariedOrder(e);case 16:return this.encodeSpriteCloudVariedMultiColorOrder(e);case 19:return this.encodeFillOrder(e,t);case 20:return this.encodeFillCharOrder(e,t);case 21:return this.encodeFillSpriteOrder(e);case 22:return this.encodeFillSpriteMultiColorOrder(e);default:throw new Error(`Unknown order type: ${e.type}`)}}writeCharCode(e,t,n,i){return i?(e.writeUInt16LE(t,n),n+2):(e.writeUInt8(t,n),n+1)}encodeCharOrder(e,t){let n=ie.allocUnsafe(gx+(t?1:0)),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),i=this.writeCharCode(n,e.charCode,i,t),n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeTextOrder(e){let t=new TextEncoder().encode(e.text),n=ie.allocUnsafe(mx+t.length),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),n.writeUInt8(t.length,i++);for(let s=0;s<t.length;s++)n.writeUInt8(t[s],i++);return n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeTextMultilineOrder(e){let t=new TextEncoder().encode(e.text),n=ie.allocUnsafe(yx+t.length),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),n.writeUInt8(t.length,i++);for(let s=0;s<t.length;s++)n.writeUInt8(t[s],i++);return n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeSubFrameOrder(e,t){let n=e.sizeX*e.sizeY,i=this.charCodeSize(t),s=ie.allocUnsafe(vx+n*i),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.posX,o++),s.writeUInt8(e.posY,o++),s.writeUInt8(e.sizeX-1,o++),s.writeUInt8(e.sizeY-1,o++),s.writeUInt8(e.bgColorCode,o++),s.writeUInt8(e.fgColorCode,o++);for(let a of e.frame)o=this.writeCharCode(s,a,o,t);return s.toUint8Array()}encodeSubFrameMultiColorOrder(e,t){let n=e.sizeX*e.sizeY,i=this.charCodeSize(t),s=ie.allocUnsafe(wx+n*(i+2)),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.posX,o++),s.writeUInt8(e.posY,o++),s.writeUInt8(e.sizeX-1,o++),s.writeUInt8(e.sizeY-1,o++);for(let a of e.frame)o=this.writeCharCode(s,a.charCode,o,t),s.writeUInt8(a.bgColorCode,o++),s.writeUInt8(a.fgColorCode,o++);return s.toUint8Array()}encodeFullFrameOrder(e,t){let n=e.frame.length,i=this.charCodeSize(t),s=ie.allocUnsafe(Cx+n*i),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.bgColorCode,o++),s.writeUInt8(e.fgColorCode,o++);for(let a of e.frame)o=this.writeCharCode(s,a,o,t);return s.toUint8Array()}encodeFullFrameMultiColorOrder(e,t){let n=e.frame.length,i=this.charCodeSize(t),s=ie.allocUnsafe(bx+n*(i+2)),o=0;s.writeUInt8(e.type,o++);for(let a of e.frame)o=this.writeCharCode(s,a.charCode,o,t),s.writeUInt8(a.bgColorCode,o++),s.writeUInt8(a.fgColorCode,o++);return s.toUint8Array()}encodeSpriteOrder(e){let t=ie.allocUnsafe(Sx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.posX,n++),t.writeUInt8(e.posY,n++),t.writeUInt8(e.spriteIndex,n++),t.writeUInt8(e.bgColorCode,n++),t.writeUInt8(e.fgColorCode,n++),t.toUint8Array()}encodeSpriteMultiColorOrder(e){let t=ie.allocUnsafe(xx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.posX,n++),t.writeUInt8(e.posY,n++),t.writeUInt8(e.spriteIndex,n++),t.toUint8Array()}encodeColorMapOrder(e){let t=e.sizeX*e.sizeY,n=ie.allocUnsafe(Ix+t*2),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),n.writeUInt8(e.sizeX-1,i++),n.writeUInt8(e.sizeY-1,i++);for(let s of e.colorData)n.writeUInt8(s.bgColorCode,i++),n.writeUInt8(s.fgColorCode,i++);return n.toUint8Array()}encodeShapeOrder(e,t){let n=this.encodeShapeData(e.shapeType,e.shapeData,t),i=ie.allocUnsafe(kx+n.length),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.shapeType,s++);for(let o=0;o<n.length;o++)i.writeUInt8(n[o],s++);return i.toUint8Array()}encodeShapeData(e,t,n){switch(this.charCodeSize(n),e){case 1:{let i=ie.allocUnsafe(Ex+(n?1:0)),s=0;return i.writeUInt8(t.posX,s++),i.writeUInt8(t.posY,s++),i.writeUInt8(t.width-1,s++),i.writeUInt8(t.height-1,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 2:{let i=ie.allocUnsafe(Mx+(n?1:0)),s=0;return i.writeUInt8(t.centerX,s++),i.writeUInt8(t.centerY,s++),i.writeUInt8(t.radius-1,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 3:{let i=ie.allocUnsafe(Ux+(n?1:0)),s=0;return i.writeUInt8(t.x1,s++),i.writeUInt8(t.y1,s++),i.writeUInt8(t.x2,s++),i.writeUInt8(t.y2,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 4:{let i=ie.allocUnsafe(Ax+(n?1:0)),s=0;return i.writeUInt8(t.centerX,s++),i.writeUInt8(t.centerY,s++),i.writeUInt8(t.radiusX-1,s++),i.writeUInt8(t.radiusY-1,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 5:{let i=ie.allocUnsafe(Tx+(n?1:0)),s=0;return i.writeUInt8(t.x1,s++),i.writeUInt8(t.y1,s++),i.writeUInt8(t.x2,s++),i.writeUInt8(t.y2,s++),i.writeUInt8(t.x3,s++),i.writeUInt8(t.y3,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}default:throw new Error(`Unknown shape type: ${e}`)}}encodeDotCloudOrder(e,t){let n=e.positions.length;this.charCodeSize(t);let i=ie.allocUnsafe(Rx+(t?1:0)+n*2),s=0;i.writeUInt8(e.type,s++),s=this.writeCharCode(i,e.charCode,s,t),i.writeUInt8(e.bgColorCode,s++),i.writeUInt8(e.fgColorCode,s++),i.writeUInt16BE(n,s),s+=2;for(let o of e.positions)i.writeUInt8(o.posX,s++),i.writeUInt8(o.posY,s++);return i.toUint8Array()}encodeDotCloudMultiColorOrder(e,t){let n=e.dots.length,i=this.charCodeSize(t),s=ie.allocUnsafe(Px+n*(i+4)),o=0;s.writeUInt8(e.type,o++),s.writeUInt16BE(n,o),o+=2;for(let a of e.dots)o=this.writeCharCode(s,a.charCode,o,t),s.writeUInt8(a.bgColorCode,o++),s.writeUInt8(a.fgColorCode,o++),s.writeUInt8(a.posX,o++),s.writeUInt8(a.posY,o++);return s.toUint8Array()}encodeBitmaskOrder(e,t){let n=e.mask.length,i=ie.allocUnsafe(Bx+(t?1:0)+n),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.posX,s++),i.writeUInt8(e.posY,s++),i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),s=this.writeCharCode(i,e.charCode,s,t),i.writeUInt8(e.bgColorCode,s++),i.writeUInt8(e.fgColorCode,s++),i.writeUInt8(e.override?1:0,s++);for(let o=0;o<n;o++)i.writeUInt8(e.mask[o],s++);return i.toUint8Array()}encodeBitmask4Order(e,t){let n=e.mask.length;this.charCodeSize(t);let i=ie.allocUnsafe(zx+3*(t?1:0)+n),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.posX,s++),i.writeUInt8(e.posY,s++),i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),i.writeUInt8(e.override?1:0,s++);for(let o of e.variants)s=this.writeCharCode(i,o.charCode,s,t),i.writeUInt8(o.bgColorCode,s++),i.writeUInt8(o.fgColorCode,s++);for(let o=0;o<n;o++)i.writeUInt8(e.mask[o],s++);return i.toUint8Array()}encodeBitmask16Order(e,t){let n=e.mask.length;this.charCodeSize(t);let i=ie.allocUnsafe(Ox+15*(t?1:0)+n),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.posX,s++),i.writeUInt8(e.posY,s++),i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),i.writeUInt8(e.override?1:0,s++);for(let o of e.variants)s=this.writeCharCode(i,o.charCode,s,t),i.writeUInt8(o.bgColorCode,s++),i.writeUInt8(o.fgColorCode,s++);for(let o=0;o<n;o++)i.writeUInt8(e.mask[o],s++);return i.toUint8Array()}encodePolylineOrder(e,t){let n=e.points.length,i=ie.allocUnsafe(Dx+(t?1:0)+n*2),s=0;i.writeUInt8(e.type,s++),s=this.writeCharCode(i,e.charCode,s,t),i.writeUInt8(e.fgColorCode,s++),i.writeUInt8(e.bgColorCode,s++),i.writeUInt8(n,s++);for(let o of e.points)i.writeUInt8(o.x,s++),i.writeUInt8(o.y,s++);return i.toUint8Array()}encodeSpriteCloudOrder(e){let t=e.positions.length,n=ie.allocUnsafe(Fx+t*2),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.spriteIndex,i++),n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.positions)n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeSpriteCloudMultiColorOrder(e){let t=e.positions.length,n=ie.allocUnsafe(Lx+t*2),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.spriteIndex,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.positions)n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeSpriteCloudVariedOrder(e){let t=e.sprites.length,n=ie.allocUnsafe(_x+t*5),i=0;n.writeUInt8(e.type,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.sprites)n.writeUInt8(s.spriteIndex,i++),n.writeUInt8(s.bgColorCode,i++),n.writeUInt8(s.fgColorCode,i++),n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeSpriteCloudVariedMultiColorOrder(e){let t=e.sprites.length,n=ie.allocUnsafe($x+t*3),i=0;n.writeUInt8(e.type,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.sprites)n.writeUInt8(s.spriteIndex,i++),n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeFillOrder(e,t){let n=ie.allocUnsafe(Nx+(t?1:0)),i=0;return n.writeUInt8(e.type,i++),i=this.writeCharCode(n,e.charCode,i,t),n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeFillCharOrder(e,t){let n=e.patternWidth*e.patternHeight,i=this.charCodeSize(t),s=ie.allocUnsafe(Vx+n*i),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.patternWidth-1,o++),s.writeUInt8(e.patternHeight-1,o++),s.writeUInt8(e.bgColorCode,o++),s.writeUInt8(e.fgColorCode,o++);for(let a of e.pattern)o=this.writeCharCode(s,a,o,t);return s.toUint8Array()}encodeFillSpriteOrder(e){let t=ie.allocUnsafe(Hx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.spriteIndex,n++),t.writeUInt8(e.bgColorCode,n++),t.writeUInt8(e.fgColorCode,n++),t.toUint8Array()}encodeFillSpriteMultiColorOrder(e){let t=ie.allocUnsafe(jx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.spriteIndex,n++),t.toUint8Array()}};J(dv,"OrderEncoder");var wI=dv,jg=255,Yg=32,Wg=64,hv=class{constructor(){O(this,"orderEncoder"),this.orderEncoder=new wI}encode(e){let t=e.is16bit;if(e.orders.length>jg)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${jg}. This would cause packet corruption! Split into multiple layers.`);let n=e.orders.map(c=>this.orderEncoder.encode(c,t)),i=13,s=n.reduce((c,d)=>c+d.length,0),o=i+s,a=ie.allocUnsafe(o),l=0;a.writeUInt16BE(e.id,l),l+=2;let u=e.updateFlags;e.isMacroLayer?u|=Yg:u&=~Yg,t?u|=Wg:u&=~Wg,a.writeUInt8(u,l++),a.writeUInt8(e.zIndex,l++),a.writeUInt16BE(e.originX,l),l+=2,a.writeUInt16BE(e.originY,l),l+=2,a.writeUInt16BE(e.width,l),l+=2,a.writeUInt16BE(e.height,l),l+=2,a.writeUInt8(e.orders.length,l++);for(let c of n)ie.from(c).copy(a,l),l+=c.length;return a.toUint8Array()}calculateSize(e){let t=e.is16bit;return 13+e.orders.reduce((n,i)=>n+this.orderEncoder.encode(i,t).length,0)}};J(hv,"LayerEncoder");var CI=hv,fv=class{encode(e){switch(e.type){case 1:return this.encodePlaySoundOrder(e);case 2:return this.encodePlayGlobalSoundOrder(e);case 3:return this.encodeStopSoundOrder(e);case 4:return this.encodeFadeOutSoundOrder(e);case 5:return this.encodePauseSoundOrder(e);case 6:return this.encodeResumeSoundOrder(e);case 7:return this.encodeSetListenerPositionOrder(e);case 8:return this.encodeConfigureSpatialOrder(e);case 9:return this.encodeSetSoundEffectsOrder(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculatePlaySoundSize(e);case 2:return this.calculatePlayGlobalSoundSize(e);case 3:case 5:case 6:return this.calculateTargetOrderSize(e);case 4:return this.calculateFadeOutSize(e);case 7:return zg;case 8:return Og;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.soundId,i++),n.writeUInt16BE(e.instanceId,i),i+=2,n.writeUInt8(e.flags,i++),e.flags&2&&n.writeUInt8(e.volume??255,i++),e.flags&4&&n.writeUInt8(e.pitch??128,i++),e.flags&8&&n.writeUInt8(e.fadeIn??0,i++),e.flags&16&&(n.writeUInt16BE(e.posX??0,i),i+=2,n.writeUInt16BE(e.posY??0,i),i+=2),e.flags&32&&n.writeUInt8(e.lowpass??0,i++),e.flags&64&&n.writeUInt8(e.highpass??0,i++),e.flags&128&&n.writeUInt8(e.reverb??0,i++),n.toUint8Array()}encodePlayGlobalSoundOrder(e){let t=this.calculatePlayGlobalSoundSize(e),n=ie.allocUnsafe(t),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.soundId,i++),n.writeUInt16BE(e.instanceId,i),i+=2;let s=e.flags&-17;return n.writeUInt8(s,i++),s&2&&n.writeUInt8(e.volume??255,i++),s&4&&n.writeUInt8(e.pitch??128,i++),s&8&&n.writeUInt8(e.fadeIn??0,i++),s&32&&n.writeUInt8(e.lowpass??0,i++),s&64&&n.writeUInt8(e.highpass??0,i++),s&128&&n.writeUInt8(e.reverb??0,i++),n.toUint8Array()}calculatePlaySoundSize(e){let t=Yx;return e.flags&2&&(t+=1),e.flags&4&&(t+=1),e.flags&8&&(t+=1),e.flags&16&&(t+=4),e.flags&32&&(t+=1),e.flags&64&&(t+=1),e.flags&128&&(t+=1),t}calculatePlayGlobalSoundSize(e){let t=Wx,n=e.flags&-17;return n&2&&(t+=1),n&4&&(t+=1),n&8&&(t+=1),n&32&&(t+=1),n&64&&(t+=1),n&128&&(t+=1),t}encodeStopSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodePauseSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeResumeSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeFadeOutSoundOrder(e){let t=this.calculateFadeOutSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.targetType,i++),n.writeUInt8(e.duration,i++),e.targetType===0?n.writeUInt16BE(e.target??0,i):e.targetType===1&&n.writeUInt8(e.target??0,i),n.toUint8Array()}encodeTargetOrder(e,t,n){let i=2;t===0?i+=2:t===1&&(i+=1);let s=ie.allocUnsafe(i),o=0;return s.writeUInt8(e,o++),s.writeUInt8(t,o++),t===0?s.writeUInt16BE(n??0,o):t===1&&s.writeUInt8(n??0,o),s.toUint8Array()}calculateTargetOrderSize(e){let t=2;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}calculateFadeOutSize(e){let t=3;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}encodeSetListenerPositionOrder(e){let t=ie.allocUnsafe(zg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt16BE(e.x,n),n+=2,t.writeUInt16BE(e.y,n),t.toUint8Array()}encodeConfigureSpatialOrder(e){let t=ie.allocUnsafe(Og),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.maxDistance,n++),t.writeUInt8(e.referenceDistance,n++),t.writeUInt8(e.rolloffFactor,n++),t.writeUInt8(e.panSpread,n++),t.toUint8Array()}encodeSetSoundEffectsOrder(e){let t=this.calculateSetSoundEffectsSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt16BE(e.instanceId,i),i+=2,n.writeUInt8(e.flags,i++),e.flags&1&&n.writeUInt8(e.lowpass??0,i++),e.flags&2&&n.writeUInt8(e.highpass??0,i++),e.flags&4&&n.writeUInt8(e.reverb??0,i++),n.toUint8Array()}calculateSetSoundEffectsSize(e){let t=4;return e.flags&1&&(t+=1),e.flags&2&&(t+=1),e.flags&4&&(t+=1),t}};J(fv,"AudioOrderEncoder");var bI=fv,pv=class{encode(e){switch(e.type){case 1:return this.encodeMobileVibrateOrder(e);case 2:return this.encodeMobileCancelOrder(e);case 16:return this.encodeGamepadVibrateOrder(e);case 17:return this.encodeGamepadCancelOrder(e);default:throw new Error(`Unknown vibration order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateMobileVibrateSize(e);case 2:return 1;case 16:return this.calculateGamepadVibrateSize(e);case 17:return 3;default:throw new Error(`Unknown vibration order type: ${e.type}`)}}calculateMobileVibrateSize(e){let t=3+e.pattern.length*2;return e.intensity!==void 0&&(t+=1),t}encodeMobileVibrateOrder(e){let t=this.calculateMobileVibrateSize(e),n=ie.allocUnsafe(t),i=0,s=0;e.intensity!==void 0&&(s|=1),n.writeUInt8(e.type,i++),n.writeUInt8(s,i++),n.writeUInt8(e.pattern.length,i++);for(let o of e.pattern){let a=Math.min(65535,Math.max(0,Math.round(o)));n.writeUInt16BE(a,i),i+=2}if(e.intensity!==void 0){let o=Math.round(Math.min(1,Math.max(0,e.intensity))*255);n.writeUInt8(o,i++)}return n.toUint8Array()}encodeMobileCancelOrder(e){let t=ie.allocUnsafe(1);return t.writeUInt8(2,0),t.toUint8Array()}calculateGamepadVibrateSize(e){let t=7;return e.startDelay!==void 0&&e.startDelay>0&&(t+=2),t}encodeGamepadVibrateOrder(e){let t=this.calculateGamepadVibrateSize(e),n=ie.allocUnsafe(t),i=0,s=0;e.startDelay!==void 0&&e.startDelay>0&&(s|=1),e.gamepadIndex===255&&(s|=2),n.writeUInt8(e.type,i++),n.writeUInt8(s,i++),n.writeUInt8(e.gamepadIndex,i++);let o=Math.min(65535,Math.max(0,Math.round(e.duration)));if(n.writeUInt16BE(o,i),i+=2,n.writeUInt8(e.strongMagnitude,i++),n.writeUInt8(e.weakMagnitude,i++),e.startDelay!==void 0&&e.startDelay>0){let a=Math.min(65535,Math.max(0,Math.round(e.startDelay)));n.writeUInt16BE(a,i),i+=2}return n.toUint8Array()}encodeGamepadCancelOrder(e){let t=ie.allocUnsafe(3),n=0,i=0;return e.gamepadIndex===255&&(i|=2),t.writeUInt8(e.type,n++),t.writeUInt8(i,n++),t.writeUInt8(e.gamepadIndex,n++),t.toUint8Array()}};J(pv,"VibrationOrderEncoder");var SI=pv,gv=class{encode(e){switch(e.type){case 1:return this.encodeCreateInstance(e);case 2:return this.encodeUpdateInstance(e);case 3:return this.encodeRemoveInstance(e);default:throw new Error(`Unknown macro order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateCreateInstanceSize(e);case 2:return this.calculateUpdateInstanceSize(e);case 3:return 2;default:throw new Error(`Unknown macro order type: ${e.type}`)}}encodeCreateInstance(e){let t=JSON.stringify(e.params),n=new TextEncoder().encode(t);if(n.length>65535)throw new Error(`Params JSON too large: ${n.length} bytes (max 65535)`);let i=11+n.length,s=ie.allocUnsafe(i),o=0;return s.writeUInt8(e.type,o++),s.writeUInt8(e.instanceId,o++),s.writeUInt8(e.macroId,o++),s.writeUInt8(e.layerId,o++),s.writeInt16BE(e.x,o),o+=2,s.writeInt16BE(e.y,o),o+=2,s.writeUInt8(e.tabIndex,o++),s.writeUInt16BE(n.length,o),o+=2,s.toUint8Array().set(n,o),s.toUint8Array()}calculateCreateInstanceSize(e){let t=JSON.stringify(e.params);return 11+new TextEncoder().encode(t).length}encodeUpdateInstance(e){let t=JSON.stringify(e.params),n=new TextEncoder().encode(t);if(n.length>65535)throw new Error(`Params JSON too large: ${n.length} bytes (max 65535)`);let i=4+n.length,s=ie.allocUnsafe(i),o=0;return s.writeUInt8(e.type,o++),s.writeUInt8(e.instanceId,o++),s.writeUInt16BE(n.length,o),o+=2,s.toUint8Array().set(n,o),s.toUint8Array()}calculateUpdateInstanceSize(e){let t=JSON.stringify(e.params);return 4+new TextEncoder().encode(t).length}encodeRemoveInstance(e){let t=ie.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};J(gv,"MacroOrderEncoder");var xI=gv,Xr=(r=>(r[r.SetConfig=1]="SetConfig",r[r.SetScanlines=2]="SetScanlines",r[r.SetAmbientEffect=3]="SetAmbientEffect",r[r.SetScalingMode=4]="SetScalingMode",r[r.SetGrid=5]="SetGrid",r[r.SwitchPalette=6]="SwitchPalette",r[r.SetCellSize=7]="SetCellSize",r))(Xr||{}),mv=class{encode(e){switch(e.type){case 1:return this.encodeSetConfigOrder(e);case 2:return this.encodeSetScanlinesOrder(e);case 3:return this.encodeSetAmbientEffectOrder(e);case 4:return this.encodeSetScalingModeOrder(e);case 5:return this.encodeSetGridOrder(e);case 6:return this.encodeSwitchPaletteOrder(e);case 7:return this.encodeSetCellSizeOrder(e);default:throw new Error(`Unknown post-process order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateSetConfigSize(e);case 2:return Dg;case 3:return Fg;case 4:return Lg;case 5:return _g;case 6:return $g;case 7:return Ng;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.displayId,i++),n.writeUInt8(e.flags,i++),e.flags&1&&e.scanlines&&(n.writeUInt8(e.scanlines.enabled?1:0,i++),n.writeUInt8(Math.round(e.scanlines.opacity*255),i++),n.writeUInt8(e.scanlines.pattern,i++),n.writeUInt8(e.scanlines.colorR,i++),n.writeUInt8(e.scanlines.colorG,i++),n.writeUInt8(e.scanlines.colorB,i++)),e.flags&2&&e.ambientEffect&&(n.writeUInt8(e.ambientEffect.enabled?1:0,i++),n.writeUInt8(Math.min(255,Math.round(e.ambientEffect.blur)),i++),n.writeUInt8(Math.min(255,Math.max(100,Math.round(e.ambientEffect.scale*100))),i++),n.writeUInt8(Math.round(e.ambientEffect.opacity*255),i++)),n.toUint8Array()}calculateSetConfigSize(e){let t=Gx;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=ie.allocUnsafe(Dg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.enabled?1:0,n++),t.writeUInt8(Math.round(e.opacity*255),n++),t.writeUInt8(e.pattern,n++),t.writeUInt8(e.colorR,n++),t.writeUInt8(e.colorG,n++),t.writeUInt8(e.colorB,n++),t.toUint8Array()}encodeSetAmbientEffectOrder(e){let t=ie.allocUnsafe(Fg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.enabled?1:0,n++),t.writeUInt8(Math.min(255,Math.round(e.blur)),n++),t.writeUInt8(Math.min(255,Math.max(100,Math.round(e.scale*100))),n++),t.writeUInt8(Math.round(e.opacity*255),n++),t.toUint8Array()}encodeSetScalingModeOrder(e){let t=ie.allocUnsafe(Lg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.mode,n++),t.toUint8Array()}encodeSetGridOrder(e){let t=ie.allocUnsafe(_g),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.enabled?1:0,n++),t.writeUInt8(e.colorR,n++),t.writeUInt8(e.colorG,n++),t.writeUInt8(e.colorB,n++),t.writeUInt8(e.colorA,n++),t.writeUInt8(Math.min(10,Math.max(1,e.lineWidth)),n++),t.toUint8Array()}encodeSwitchPaletteOrder(e){let t=ie.allocUnsafe($g),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.slotId,n++),t.toUint8Array()}encodeSetCellSizeOrder(e){let t=ie.allocUnsafe(Ng),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.cellWidth,n++),t.writeUInt8(e.cellHeight,n++),t.toUint8Array()}};J(mv,"PostProcessOrderEncoder");var II=mv,Gg=4,Fc=4,Xg=8,yv=class{encode(e){var o;let t=((o=e.renderPasses)==null?void 0:o.length)??0;if(t>Fc)throw new Error(`renderPasses supports up to ${Fc} entries, got ${t}`);let n=Xg+t*Gg,i=ie.allocUnsafe(n),s=0;if(i.writeUInt8(e.id,s++),i.writeUInt16BE(e.originX,s),s+=2,i.writeUInt16BE(e.originY,s),s+=2,i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),i.writeUInt8(t,s++),t>0&&e.renderPasses)for(let a of e.renderPasses){let l=Math.max(0,Math.min(255,a.id)),u=Math.max(0,Math.min(255,a.zMin)),c=Math.max(0,Math.min(255,a.zMax)),d=a.enabled===!1?0:1;i.writeUInt8(l,s++),i.writeUInt8(u,s++),i.writeUInt8(c,s++),i.writeUInt8(d,s++)}return i.toUint8Array()}calculateSize(e){var n;let t=Math.min(((n=e.renderPasses)==null?void 0:n.length)??0,Fc);return Xg+t*Gg}};J(yv,"DisplayEncoder");var kI=yv,vv=class{constructor(){O(this,"layerEncoder"),O(this,"audioOrderEncoder"),O(this,"vibrationOrderEncoder"),O(this,"macroOrderEncoder"),O(this,"postProcessOrderEncoder"),O(this,"displayEncoder"),this.layerEncoder=new CI,this.audioOrderEncoder=new bI,this.vibrationOrderEncoder=new SI,this.macroOrderEncoder=new xI,this.postProcessOrderEncoder=new II,this.displayEncoder=new kI}encode(e){let t=e.layers.map(z=>this.layerEncoder.encode(z)),n=e.audioOrders||[],i=n.map(z=>this.audioOrderEncoder.encode(z)),s=e.vibrationOrders||[],o=s.map(z=>this.vibrationOrderEncoder.encode(z)),a=e.macroOrders||[],l=a.map(z=>this.macroOrderEncoder.encode(z)),u=e.postProcessOrders||[],c=u.map(z=>this.postProcessOrderEncoder.encode(z)),d=9,h=e.displays.reduce((z,P)=>z+this.displayEncoder.calculateSize(P),0),f=2,p=t.reduce((z,P)=>z+P.length,0),m=1,S=i.reduce((z,P)=>z+P.length,0),w=1,g=o.reduce((z,P)=>z+P.length,0),y=1,C=l.reduce((z,P)=>z+P.length,0),x=1,I=c.reduce((z,P)=>z+P.length,0),E=d+h+f+p+m+S+w+g+y+C+x+I,A=ie.allocUnsafe(E),R=0,F=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);A.writeBigUInt64BE(F,R),R+=8,A.writeUInt8(e.displays.length,R),R+=1;for(let z of e.displays){let P=this.displayEncoder.encode(z);ie.from(P).copy(A,R),R+=P.length}A.writeUInt16BE(e.layers.length,R),R+=2;for(let z of t)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(n.length,R),R+=1;for(let z of i)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(s.length,R),R+=1;for(let z of o)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(a.length,R),R+=1;for(let z of l)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(u.length,R),R+=1;for(let z of c)ie.from(z).copy(A,R),R+=z.length;return A.toUint8Array()}calculateSize(e){let t=e.displays.reduce((f,p)=>f+this.displayEncoder.calculateSize(p),0),n=2,i=e.layers.reduce((f,p)=>f+this.layerEncoder.calculateSize(p),0),s=1,o=(e.audioOrders||[]).reduce((f,p)=>f+this.audioOrderEncoder.calculateSize(p),0),a=1,l=(e.vibrationOrders||[]).reduce((f,p)=>f+this.vibrationOrderEncoder.calculateSize(p),0),u=1,c=(e.macroOrders||[]).reduce((f,p)=>f+this.macroOrderEncoder.calculateSize(p),0),d=1,h=(e.postProcessOrders||[]).reduce((f,p)=>f+this.postProcessOrderEncoder.calculateSize(p),0);return 9+t+n+i+s+o+a+l+u+c+d+h}static createEmptyPacket(e){return{tick:typeof e=="bigint"?Number(e):e,displayCount:0,displays:[],layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]}}encodeEmpty(e){let t=ie.allocUnsafe(15),n=typeof e=="bigint"?e:BigInt(e);return t.writeBigUInt64BE(n,0),t.writeUInt8(0,8),t.writeUInt16BE(0,9),t.writeUInt8(0,11),t.writeUInt8(0,12),t.writeUInt8(0,13),t.writeUInt8(0,14),t.toUint8Array()}};J(vv,"UpdatePacketEncoder");var EI=vv,MI=(r=>(r[r.ColorPalette=1]="ColorPalette",r[r.Sprite=2]="Sprite",r[r.MulticolorSprite=3]="MulticolorSprite",r[r.Sound=5]="Sound",r[r.Macro=7]="Macro",r[r.ImageFont=8]="ImageFont",r[r.ImageFontBlock=9]="ImageFontBlock",r))(MI||{}),wv=class{encode(e){let t=JSON.stringify(e.template),n=new TextEncoder().encode(t);if(n.length>65535)throw new Error(`Macro template JSON too large: ${n.length} bytes (max 65535)`);let i=4+n.length,s=ie.allocUnsafe(i),o=0;return s.writeUInt8(7,o++),s.writeUInt8(e.macroId,o++),s.writeUInt16BE(n.length,o),o+=2,s.toUint8Array().set(n,o),s.toUint8Array()}calculateSize(e){let t=JSON.stringify(e.template);return 4+new TextEncoder().encode(t).length}};J(wv,"MacroLoadEncoder");var UI=wv,Cv=class{encode(e){switch(e.loadType){case 1:return this.encodeColorPalette(e);case 2:return this.encodeSprite(e);case 3:return this.encodeMulticolorSprite(e);case 5:return this.encodeSound(e);case 8:return this.encodeImageFont(e);case 9:return this.encodeImageFontBlock(e);default:throw new Error(`Unknown load type: ${e.loadType}`)}}encodeColorPalette(e){let t=e.colors.length;if(t>255)throw new Error(`Palette size ${t} exceeds maximum of 255`);let n=e.slotId!==void 0,i=n?4:3,s=ie.allocUnsafe(i+t*6),o=0;s.writeUInt8(1,o++),s.writeUInt8(n?255:0,o++),n&&s.writeUInt8(e.slotId,o++),s.writeUInt8(t,o++);for(let a of e.colors)s.writeUInt8(a.colorId,o++),s.writeUInt8(a.r,o++),s.writeUInt8(a.g,o++),s.writeUInt8(a.b,o++),s.writeUInt8(a.a??255,o++),s.writeUInt8(a.e??0,o++);return s.toUint8Array()}encodeSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let n=2;for(let o of e.sprites)n+=3,n+=o.data.length;let i=ie.allocUnsafe(n),s=0;i.writeUInt8(2,s++),i.writeUInt8(t,s++);for(let o of e.sprites){if(o.data.length!==o.sizeX*o.sizeY)throw new Error(`Sprite ${o.spriteId}: data length ${o.data.length} does not match size ${o.sizeX}x${o.sizeY}`);i.writeUInt8(o.spriteId,s++),i.writeUInt8(o.sizeX,s++),i.writeUInt8(o.sizeY,s++);for(let a of o.data)i.writeUInt8(a,s++)}return i.toUint8Array()}encodeMulticolorSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let n=2;for(let o of e.sprites)n+=3,n+=o.data.length*3;let i=ie.allocUnsafe(n),s=0;i.writeUInt8(3,s++),i.writeUInt8(t,s++);for(let o of e.sprites){if(o.data.length!==o.sizeX*o.sizeY)throw new Error(`Sprite ${o.spriteId}: data length ${o.data.length} does not match size ${o.sizeX}x${o.sizeY}`);i.writeUInt8(o.spriteId,s++),i.writeUInt8(o.sizeX,s++),i.writeUInt8(o.sizeY,s++);for(let a of o.data)i.writeUInt8(a.charCode,s++),i.writeUInt8(a.fgColorId,s++),i.writeUInt8(a.bgColorId,s++)}return i.toUint8Array()}encodeSound(e){let t=e.sounds.length;if(t>255)throw new Error(`Sound count ${t} exceeds maximum of 255`);let n=2;for(let o of e.sounds){if(o.midiData.length>65535)throw new Error(`Sound ${o.soundId}: MIDI data size ${o.midiData.length} exceeds maximum of 65535 bytes`);n+=3,n+=o.midiData.length}let i=ie.allocUnsafe(n),s=0;i.writeUInt8(5,s++),i.writeUInt8(t,s++);for(let o of e.sounds){i.writeUInt8(o.soundId,s++),i.writeUInt16BE(o.midiData.length,s),s+=2;for(let a=0;a<o.midiData.length;a++)i.writeUInt8(o.midiData[a],s++)}return i.toUint8Array()}encodeImageFont(e){if(![1,4,16].includes(e.atlasBlocks))throw new Error(`Invalid atlasBlocks value: ${e.atlasBlocks}. Must be 1, 4, or 16.`);let t=ie.allocUnsafe(6),n=0;return t.writeUInt8(8,n++),t.writeUInt8(e.glyphWidth,n++),t.writeUInt8(e.glyphHeight,n++),t.writeUInt8(e.cellWidth,n++),t.writeUInt8(e.cellHeight,n++),t.writeUInt8(e.atlasBlocks,n++),t.toUint8Array()}encodeImageFontBlock(e){let t=6+e.imageData.length,n=ie.allocUnsafe(t),i=0;n.writeUInt8(9,i++),n.writeUInt8(e.blockIndex,i++),n.writeUInt32LE(e.imageData.length,i),i+=4;for(let s=0;s<e.imageData.length;s++)n.writeUInt8(e.imageData[s],i++);return n.toUint8Array()}};J(Cv,"LoadEncoder");var Lc=Cv,bv=class{decode(e,t=0){let n=t,i=e.readUInt8(t++);if(i!==7)throw new Error(`Expected LoadType.Macro (0x07), got 0x${i.toString(16)}`);let s=e.readUInt8(t++),o=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+o);t+=o;let l=new TextDecoder().decode(a),u=JSON.parse(l);return{load:{loadType:7,macroId:s,template:u},bytesRead:t-n}}};J(bv,"MacroLoadDecoder");var AI=bv,Sv=class{decode(e,t=0){let n=ie.from(e);if(t>=n.length)throw new Error("Buffer too short to decode load type");let i=n.readUInt8(t);switch(i){case 1:return this.decodeColorPalette(n,t);case 2:return this.decodeSprite(n,t);case 3:return this.decodeMulticolorSprite(n,t);case 5:return this.decodeSound(n,t);case 7:return this.decodeMacro(n,t);case 8:return this.decodeImageFont(n,t);case 9:return this.decodeImageFontBlock(n,t);default:throw new Error(`Unknown load type: 0x${i.toString(16)}`)}}decodeColorPalette(e,t){let n=t;this.checkSize(e,t,3,"ColorPalette header"),e.readUInt8(t++);let i=e.readUInt8(t++)===255,s;i&&(this.checkSize(e,t,1,"ColorPalette slotId"),s=e.readUInt8(t++));let o=e.readUInt8(t++);this.checkSize(e,t,o*6,`ColorPalette ${o} colors`);let a=[];for(let l=0;l<o;l++)a.push({colorId:e.readUInt8(t++),r:e.readUInt8(t++),g:e.readUInt8(t++),b:e.readUInt8(t++),a:e.readUInt8(t++),e:e.readUInt8(t++)});return{load:{loadType:1,...s!==void 0&&{slotId:s},colors:a},bytesRead:t-n}}decodeSprite(e,t){let n=t;this.checkSize(e,t,2,"Sprite header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=[];for(let o=0;o<i;o++){this.checkSize(e,t,3,`Sprite ${o} header`);let a=e.readUInt8(t++),l=e.readUInt8(t++),u=e.readUInt8(t++),c=l*u;this.checkSize(e,t,c,`Sprite ${o} data`);let d=[];for(let h=0;h<c;h++)d.push(e.readUInt8(t++));s.push({spriteId:a,sizeX:l,sizeY:u,data:d})}return{load:{loadType:2,sprites:s},bytesRead:t-n}}decodeMulticolorSprite(e,t){let n=t;this.checkSize(e,t,2,"MulticolorSprite header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=[];for(let o=0;o<i;o++){this.checkSize(e,t,3,`MulticolorSprite ${o} header`);let a=e.readUInt8(t++),l=e.readUInt8(t++),u=e.readUInt8(t++),c=l*u;this.checkSize(e,t,c*3,`MulticolorSprite ${o} data`);let d=[];for(let h=0;h<c;h++)d.push({charCode:e.readUInt8(t++),fgColorId:e.readUInt8(t++),bgColorId:e.readUInt8(t++)});s.push({spriteId:a,sizeX:l,sizeY:u,data:d})}return{load:{loadType:3,sprites:s},bytesRead:t-n}}decodeSound(e,t){let n=t;this.checkSize(e,t,2,"Sound header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=[];for(let o=0;o<i;o++){this.checkSize(e,t,3,`Sound ${o} header`);let a=e.readUInt8(t++),l=e.readUInt16BE(t);t+=2,this.checkSize(e,t,l,`Sound ${o} MIDI data`);let u=new Uint8Array(l);for(let c=0;c<l;c++)u[c]=e.readUInt8(t++);s.push({soundId:a,midiData:u})}return{load:{loadType:5,sounds:s},bytesRead:t-n}}checkSize(e,t,n,i){if(t+n>e.length)throw new Error(`Buffer too short for ${i}: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes remaining`)}decodeMacro(e,t){return new AI().decode(e,t)}decodeImageFont(e,t){let n=t;this.checkSize(e,t,6,"ImageFont header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt8(t++),a=e.readUInt8(t++),l=e.readUInt8(t++);if(![1,4,16].includes(l))throw new Error(`Invalid atlasBlocks value: ${l}. Must be 1, 4, or 16.`);return{load:{loadType:8,glyphWidth:i,glyphHeight:s,cellWidth:o,cellHeight:a,atlasBlocks:l},bytesRead:t-n}}decodeImageFontBlock(e,t){let n=t;this.checkSize(e,t,2,"ImageFontBlock header"),e.readUInt8(t++);let i=e.readUInt8(t++);this.checkSize(e,t,4,"ImageFontBlock data size");let s=e.readUInt32LE(t);t+=4,this.checkSize(e,t,s,"ImageFontBlock data");let o=new Uint8Array(s);for(let a=0;a<s;a++)o[a]=e.readUInt8(t++);return{load:{loadType:9,blockIndex:i,imageData:o},bytesRead:t-n}}};J(Sv,"LoadDecoder");var TI=Sv,RI=4,Kg=4,Zg=8,xv=class{decode(e,t=0){this.checkSize(e,t,Zg);let n=t,i=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let o=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++)+1,l=e.readUInt8(n++)+1,u=e.readUInt8(n++);if(u>Kg)throw new Error(`Invalid renderPass count: ${u} (max ${Kg})`);let c=u*RI;this.checkSize(e,n,c);let d=[];for(let h=0;h<u;h++){let f=e.readUInt8(n++),p=e.readUInt8(n++),m=e.readUInt8(n++),S=e.readUInt8(n++);d.push({id:f,zMin:p,zMax:m,enabled:(S&1)!==0})}return{display:{id:i,originX:s,originY:o,sizeX:a,sizeY:l,renderPasses:d.length>0?d:void 0},bytesRead:Zg+c}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for display: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(xv,"DisplayDecoder");var PI=xv,Iv=class{constructor(){O(this,"charCodeSize",_1)}decode(e,t=0,n=!1,i){if(t>=e.length)throw new Error("Buffer too short to decode order type");let s=e.readUInt8(t);switch(s){case 1:return this.decodeCharOrder(e,t,n);case 2:return this.decodeTextOrder(e,t);case 23:return this.decodeTextMultilineOrder(e,t);case 3:return this.decodeSubFrameOrder(e,t,n);case 4:return this.decodeSubFrameMultiColorOrder(e,t,n);case 5:return this.decodeFullFrameOrder(e,t,n,i);case 6:return this.decodeFullFrameMultiColorOrder(e,t,n,i);case 7:return this.decodeSpriteOrder(e,t);case 8:return this.decodeSpriteMultiColorOrder(e,t);case 9:return this.decodeColorMapOrder(e,t);case 10:return this.decodeShapeOrder(e,t,n);case 11:return this.decodeDotCloudOrder(e,t,n);case 12:return this.decodeDotCloudMultiColorOrder(e,t,n);case 17:return this.decodeBitmaskOrder(e,t,n);case 18:return this.decodeBitmask4Order(e,t,n);case 24:return this.decodeBitmask16Order(e,t,n);case 25:return this.decodePolylineOrder(e,t,n);case 13:return this.decodeSpriteCloudOrder(e,t);case 14:return this.decodeSpriteCloudMultiColorOrder(e,t);case 15:return this.decodeSpriteCloudVariedOrder(e,t);case 16:return this.decodeSpriteCloudVariedMultiColorOrder(e,t);case 19:return this.decodeFillOrder(e,t,n);case 20:return this.decodeFillCharOrder(e,t,n);case 21:return this.decodeFillSpriteOrder(e,t);case 22:return this.decodeFillSpriteMultiColorOrder(e,t);default:throw new Error(`Unknown order type: 0x${s.toString(16)}`)}}readCharCode(e,t,n){return n?[e.readUInt16LE(t),t+2]:[e.readUInt8(t),t+1]}decodeCharOrder(e,t,n){let i=5+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),[l,u]=this.readCharCode(e,s,n);s=u;let c=e.readUInt8(s++),d=e.readUInt8(s++);return{order:{type:1,posX:o,posY:a,charCode:l,bgColorCode:c,fgColorCode:d},bytesRead:i}}decodeTextOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n+3);this.checkSize(e,t,5+i);let s=e.subarray(n+4,n+4+i),o=new TextDecoder().decode(s.toUint8Array());return{order:{type:2,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),text:o,bgColorCode:e.readUInt8(n+4+i),fgColorCode:e.readUInt8(n+5+i)},bytesRead:6+i}}decodeTextMultilineOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n+3);this.checkSize(e,t,5+i);let s=e.subarray(n+4,n+4+i),o=new TextDecoder().decode(s.toUint8Array());return{order:{type:23,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),text:o,bgColorCode:e.readUInt8(n+4+i),fgColorCode:e.readUInt8(n+5+i)},bytesRead:6+i}}decodeSubFrameOrder(e,t,n){this.checkSize(e,t,7);let i=t,s=this.charCodeSize(n),o=e.readUInt8(i+3)+1,a=e.readUInt8(i+4)+1,l=o*a;this.checkSize(e,t,7+l*s);let u=[],c=i+7;for(let d=0;d<l;d++){let[h,f]=this.readCharCode(e,c,n);u.push(h),c=f}return{order:{type:3,posX:e.readUInt8(i+1),posY:e.readUInt8(i+2),sizeX:o,sizeY:a,bgColorCode:e.readUInt8(i+5),fgColorCode:e.readUInt8(i+6),frame:u},bytesRead:7+l*s}}decodeSubFrameMultiColorOrder(e,t,n){this.checkSize(e,t,5);let i=t,s=this.charCodeSize(n),o=e.readUInt8(i+3)+1,a=e.readUInt8(i+4)+1,l=o*a,u=s+2;this.checkSize(e,t,5+l*u);let c=[],d=i+5;for(let h=0;h<l;h++){let[f,p]=this.readCharCode(e,d,n);d=p,c.push({charCode:f,bgColorCode:e.readUInt8(d++),fgColorCode:e.readUInt8(d++)})}return{order:{type:4,posX:e.readUInt8(i+1),posY:e.readUInt8(i+2),sizeX:o,sizeY:a,frame:c},bytesRead:5+l*u}}decodeFullFrameOrder(e,t,n,i){this.checkSize(e,t,3);let s=t,o=this.charCodeSize(n),a=i||Math.floor((e.length-t-3)/o);this.checkSize(e,t,3+a*o);let l=[],u=s+3;for(let c=0;c<a;c++){let[d,h]=this.readCharCode(e,u,n);l.push(d),u=h}return{order:{type:5,bgColorCode:e.readUInt8(s+1),fgColorCode:e.readUInt8(s+2),frame:l},bytesRead:3+a*o}}decodeFullFrameMultiColorOrder(e,t,n,i){this.checkSize(e,t,1);let s=t,o=this.charCodeSize(n)+2,a=i||Math.floor((e.length-t-1)/o);this.checkSize(e,t,1+a*o);let l=[],u=s+1;for(let c=0;c<a;c++){let[d,h]=this.readCharCode(e,u,n);u=h,l.push({charCode:d,bgColorCode:e.readUInt8(u++),fgColorCode:e.readUInt8(u++)})}return{order:{type:6,frame:l},bytesRead:1+a*o}}decodeSpriteOrder(e,t){this.checkSize(e,t,6);let n=t;return{order:{type:7,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),spriteIndex:e.readUInt8(n+3),bgColorCode:e.readUInt8(n+4),fgColorCode:e.readUInt8(n+5)},bytesRead:6}}decodeSpriteMultiColorOrder(e,t){this.checkSize(e,t,4);let n=t;return{order:{type:8,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),spriteIndex:e.readUInt8(n+3)},bytesRead:4}}decodeColorMapOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n+3)+1,s=e.readUInt8(n+4)+1,o=i*s;this.checkSize(e,t,5+o*2);let a=[];for(let l=0;l<o;l++){let u=n+5+l*2;a.push({bgColorCode:e.readUInt8(u),fgColorCode:e.readUInt8(u+1)})}return{order:{type:9,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:s,colorData:a},bytesRead:5+o*2}}decodeShapeOrder(e,t,n){this.checkSize(e,t,2);let i=t,s=e.readUInt8(i+1),{shapeData:o,bytesRead:a}=this.decodeShapeData(e,i+2,s,n);return{order:{type:10,shapeType:s,shapeData:o},bytesRead:2+a}}decodeShapeData(e,t,n,i){let s=t,o=this.charCodeSize(i);switch(n){case 1:{let a=7+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++)+1,d=e.readUInt8(s++)+1,h=e.readUInt8(s++)===1,[f,p]=this.readCharCode(e,s,i);s=p;let m=e.readUInt8(s++),S=e.readUInt8(s++);return{shapeData:{posX:l,posY:u,width:c,height:d,filled:h,charCode:f,bgColorCode:m,fgColorCode:S},bytesRead:a}}case 2:{let a=6+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++)+1,d=e.readUInt8(s++)===1,[h,f]=this.readCharCode(e,s,i);s=f;let p=e.readUInt8(s++),m=e.readUInt8(s++);return{shapeData:{centerX:l,centerY:u,radius:c,filled:d,charCode:h,bgColorCode:p,fgColorCode:m},bytesRead:a}}case 3:{let a=6+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++),d=e.readUInt8(s++),[h,f]=this.readCharCode(e,s,i);s=f;let p=e.readUInt8(s++),m=e.readUInt8(s++);return{shapeData:{x1:l,y1:u,x2:c,y2:d,charCode:h,bgColorCode:p,fgColorCode:m},bytesRead:a}}case 4:{let a=7+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++)+1,d=e.readUInt8(s++)+1,h=e.readUInt8(s++)===1,[f,p]=this.readCharCode(e,s,i);s=p;let m=e.readUInt8(s++),S=e.readUInt8(s++);return{shapeData:{centerX:l,centerY:u,radiusX:c,radiusY:d,filled:h,charCode:f,bgColorCode:m,fgColorCode:S},bytesRead:a}}case 5:{let a=9+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++),d=e.readUInt8(s++),h=e.readUInt8(s++),f=e.readUInt8(s++),p=e.readUInt8(s++)===1,[m,S]=this.readCharCode(e,s,i);s=S;let w=e.readUInt8(s++),g=e.readUInt8(s++);return{shapeData:{x1:l,y1:u,x2:c,y2:d,x3:h,y3:f,filled:p,charCode:m,bgColorCode:w,fgColorCode:g},bytesRead:a}}default:throw new Error(`Unknown shape type: ${n}`)}}decodeDotCloudOrder(e,t,n){let i=1+this.charCodeSize(n)+2+2;this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let[o,a]=this.readCharCode(e,s,n);s=a;let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt16BE(s);s+=2,this.checkSize(e,t,i+c*2);let d=[];for(let h=0;h<c;h++)d.push({posX:e.readUInt8(s++),posY:e.readUInt8(s++)});return{order:{type:11,charCode:o,bgColorCode:l,fgColorCode:u,positions:d},bytesRead:i+c*2}}decodeDotCloudMultiColorOrder(e,t,n){this.checkSize(e,t,3);let i=this.charCodeSize(n),s=t,o=e.readUInt16BE(s+1),a=i+4;this.checkSize(e,t,3+o*a);let l=[],u=s+3;for(let c=0;c<o;c++){let[d,h]=this.readCharCode(e,u,n);u=h,l.push({charCode:d,bgColorCode:e.readUInt8(u++),fgColorCode:e.readUInt8(u++),posX:e.readUInt8(u++),posY:e.readUInt8(u++)})}return{order:{type:12,dots:l},bytesRead:3+o*a}}decodeBitmaskOrder(e,t,n){let i=8+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),l=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,[c,d]=this.readCharCode(e,s,n);s=d;let h=e.readUInt8(s++),f=e.readUInt8(s++),p=e.readUInt8(s++)===1,m=Math.ceil(l*u/8);this.checkSize(e,t,i+m);let S=new Uint8Array(m);for(let w=0;w<m;w++)S[w]=e.readUInt8(s+w);return{order:{type:17,posX:o,posY:a,sizeX:l,sizeY:u,charCode:c,bgColorCode:h,fgColorCode:f,override:p,mask:S},bytesRead:i+m}}decodeBitmask4Order(e,t,n){let i=6+3*(this.charCodeSize(n)+2);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),l=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,c=e.readUInt8(s++)===1,d=Math.ceil(l*u/4);this.checkSize(e,t,i+d);let h=[];for(let p=0;p<3;p++){let[m,S]=this.readCharCode(e,s,n);s=S,h.push({charCode:m,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let f=new Uint8Array(d);for(let p=0;p<d;p++)f[p]=e.readUInt8(s+p);return{order:{type:18,posX:o,posY:a,sizeX:l,sizeY:u,override:c,variants:h,mask:f},bytesRead:i+d}}decodeBitmask16Order(e,t,n){let i=6+15*(this.charCodeSize(n)+2);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),l=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,c=e.readUInt8(s++)===1,d=Math.ceil(l*u/2);this.checkSize(e,t,i+d);let h=[];for(let p=0;p<15;p++){let[m,S]=this.readCharCode(e,s,n);s=S,h.push({charCode:m,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let f=new Uint8Array(d);for(let p=0;p<d;p++)f[p]=e.readUInt8(s+p);return{order:{type:24,posX:o,posY:a,sizeX:l,sizeY:u,override:c,variants:h,mask:f},bytesRead:i+d}}decodePolylineOrder(e,t,n){let i=4+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let[o,a]=this.readCharCode(e,s,n);s=a;let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++);this.checkSize(e,t,i+c*2);let d=[];for(let h=0;h<c;h++)d.push({x:e.readUInt8(s++),y:e.readUInt8(s++)});return{order:{type:25,charCode:o,fgColorCode:l,bgColorCode:u,points:d},bytesRead:i+c*2}}decodeSpriteCloudOrder(e,t){this.checkSize(e,t,6);let n=t,i=e.readUInt16BE(n+4);this.checkSize(e,t,6+i*2);let s=[];for(let o=0;o<i;o++){let a=n+6+o*2;s.push({posX:e.readUInt8(a),posY:e.readUInt8(a+1)})}return{order:{type:13,spriteIndex:e.readUInt8(n+1),bgColorCode:e.readUInt8(n+2),fgColorCode:e.readUInt8(n+3),positions:s},bytesRead:6+i*2}}decodeSpriteCloudMultiColorOrder(e,t){this.checkSize(e,t,4);let n=t,i=e.readUInt16BE(n+2);this.checkSize(e,t,4+i*2);let s=[];for(let o=0;o<i;o++){let a=n+4+o*2;s.push({posX:e.readUInt8(a),posY:e.readUInt8(a+1)})}return{order:{type:14,spriteIndex:e.readUInt8(n+1),positions:s},bytesRead:4+i*2}}decodeSpriteCloudVariedOrder(e,t){this.checkSize(e,t,3);let n=t,i=e.readUInt16BE(n+1);this.checkSize(e,t,3+i*5);let s=[];for(let o=0;o<i;o++){let a=n+3+o*5;s.push({spriteIndex:e.readUInt8(a),bgColorCode:e.readUInt8(a+1),fgColorCode:e.readUInt8(a+2),posX:e.readUInt8(a+3),posY:e.readUInt8(a+4)})}return{order:{type:15,sprites:s},bytesRead:3+i*5}}decodeSpriteCloudVariedMultiColorOrder(e,t){this.checkSize(e,t,3);let n=t,i=e.readUInt16BE(n+1);this.checkSize(e,t,3+i*3);let s=[];for(let o=0;o<i;o++){let a=n+3+o*3;s.push({spriteIndex:e.readUInt8(a),posX:e.readUInt8(a+1),posY:e.readUInt8(a+2)})}return{order:{type:16,sprites:s},bytesRead:3+i*3}}decodeFillOrder(e,t,n){let i=3+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let[o,a]=this.readCharCode(e,s,n);s=a;let l=e.readUInt8(s++),u=e.readUInt8(s++);return{order:{type:19,charCode:o,bgColorCode:l,fgColorCode:u},bytesRead:i}}decodeFillCharOrder(e,t,n){this.checkSize(e,t,5);let i=this.charCodeSize(n),s=t,o=e.readUInt8(s+1)+1,a=e.readUInt8(s+2)+1,l=o*a,u=5+l*i;this.checkSize(e,t,u);let c=[],d=s+5;for(let h=0;h<l;h++){let[f,p]=this.readCharCode(e,d,n);c.push(f),d=p}return{order:{type:20,patternWidth:o,patternHeight:a,bgColorCode:e.readUInt8(s+3),fgColorCode:e.readUInt8(s+4),pattern:c},bytesRead:u}}decodeFillSpriteOrder(e,t){this.checkSize(e,t,4);let n=t;return{order:{type:21,spriteIndex:e.readUInt8(n+1),bgColorCode:e.readUInt8(n+2),fgColorCode:e.readUInt8(n+3)},bytesRead:4}}decodeFillSpriteMultiColorOrder(e,t){this.checkSize(e,t,2);let n=t;return{order:{type:22,spriteIndex:e.readUInt8(n+1)},bytesRead:2}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(Iv,"OrderDecoder");var BI=Iv,zI=32,OI=64,kv=class{constructor(){O(this,"orderDecoder"),this.orderDecoder=new BI}decode(e,t=0){this.checkSize(e,t,13);let n=t,i=e.readUInt16BE(n);n+=2;let s=e.readUInt8(n++),o=e.readUInt8(n++),a=e.readUInt16BE(n);n+=2;let l=e.readUInt16BE(n);n+=2;let u=e.readUInt16BE(n);n+=2;let c=e.readUInt16BE(n);n+=2;let d=e.readUInt8(n++),h=(s&zI)!==0,f=(s&OI)!==0,p=[],m=n,S=u*c;for(let w=0;w<d;w++){let g=this.orderDecoder.decode(e,m,f,S);p.push(g.order),m+=g.bytesRead}return{layer:{id:i,updateFlags:s,zIndex:o,originX:a,originY:l,width:u,height:c,orderCount:d,orders:p,isMacroLayer:h,is16bit:f},bytesRead:m-t}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for layer: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(kv,"LayerDecoder");var DI=kv,Ev=class{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode audio order type");let n=e.readUInt8(t);switch(n){case 1:return this.decodePlaySoundOrder(e,t);case 2:return this.decodePlayGlobalSoundOrder(e,t);case 3:return this.decodeStopSoundOrder(e,t);case 4:return this.decodeFadeOutSoundOrder(e,t);case 5:return this.decodePauseSoundOrder(e,t);case 6:return this.decodeResumeSoundOrder(e,t);case 7:return this.decodeSetListenerPositionOrder(e,t);case 8:return this.decodeConfigureSpatialOrder(e,t);case 9:return this.decodeSetSoundEffectsOrder(e,t);default:throw new Error(`Unknown audio order type: 0x${n.toString(16)}`)}}decodePlaySoundOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++),l={type:i,soundId:s,instanceId:o,flags:a};return a&2&&(this.checkSize(e,n,1),l.volume=e.readUInt8(n++)),a&4&&(this.checkSize(e,n,1),l.pitch=e.readUInt8(n++)),a&8&&(this.checkSize(e,n,1),l.fadeIn=e.readUInt8(n++)),a&16&&(this.checkSize(e,n,4),l.posX=e.readUInt16BE(n),n+=2,l.posY=e.readUInt16BE(n),n+=2),a&32&&(this.checkSize(e,n,1),l.lowpass=e.readUInt8(n++)),a&64&&(this.checkSize(e,n,1),l.highpass=e.readUInt8(n++)),a&128&&(this.checkSize(e,n,1),l.reverb=e.readUInt8(n++)),{order:l,bytesRead:n-t}}decodePlayGlobalSoundOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++),l={type:i,soundId:s,instanceId:o,flags:a};return a&2&&(this.checkSize(e,n,1),l.volume=e.readUInt8(n++)),a&4&&(this.checkSize(e,n,1),l.pitch=e.readUInt8(n++)),a&8&&(this.checkSize(e,n,1),l.fadeIn=e.readUInt8(n++)),a&32&&(this.checkSize(e,n,1),l.lowpass=e.readUInt8(n++)),a&64&&(this.checkSize(e,n,1),l.highpass=e.readUInt8(n++)),a&128&&(this.checkSize(e,n,1),l.reverb=e.readUInt8(n++)),{order:l,bytesRead:n-t}}decodeStopSoundOrder(e,t){this.checkSize(e,t,2);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o={type:i,targetType:s};return s===0?(this.checkSize(e,n,2),o.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),o.target=e.readUInt8(n++)),{order:o,bytesRead:n-t}}decodeFadeOutSoundOrder(e,t){this.checkSize(e,t,3);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++),a={type:i,targetType:s,duration:o};return s===0?(this.checkSize(e,n,2),a.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),a.target=e.readUInt8(n++)),{order:a,bytesRead:n-t}}decodePauseSoundOrder(e,t){this.checkSize(e,t,2);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o={type:i,targetType:s};return s===0?(this.checkSize(e,n,2),o.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),o.target=e.readUInt8(n++)),{order:o,bytesRead:n-t}}decodeResumeSoundOrder(e,t){this.checkSize(e,t,2);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o={type:i,targetType:s};return s===0?(this.checkSize(e,n,2),o.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),o.target=e.readUInt8(n++)),{order:o,bytesRead:n-t}}decodeSetListenerPositionOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let o=e.readUInt16BE(n);return n+=2,{order:{type:i,x:s,y:o},bytesRead:5}}decodeConfigureSpatialOrder(e,t){this.checkSize(e,t,5);let n=t;return{order:{type:e.readUInt8(n),maxDistance:e.readUInt8(n+1),referenceDistance:e.readUInt8(n+2),rolloffFactor:e.readUInt8(n+3),panSpread:e.readUInt8(n+4)},bytesRead:5}}decodeSetSoundEffectsOrder(e,t){this.checkSize(e,t,4);let n=t,i=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let o=e.readUInt8(n++),a={type:i,instanceId:s,flags:o};return o&1&&(this.checkSize(e,n,1),a.lowpass=e.readUInt8(n++)),o&2&&(this.checkSize(e,n,1),a.highpass=e.readUInt8(n++)),o&4&&(this.checkSize(e,n,1),a.reverb=e.readUInt8(n++)),{order:a,bytesRead:n-t}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for audio order: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(Ev,"AudioOrderDecoder");var FI=Ev,Mv=class{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode vibration order type");let n=e.readUInt8(t);switch(n){case 1:return this.decodeMobileVibrateOrder(e,t);case 2:return this.decodeMobileCancelOrder(e,t);case 16:return this.decodeGamepadVibrateOrder(e,t);case 17:return this.decodeGamepadCancelOrder(e,t);default:throw new Error(`Unknown vibration order type: 0x${n.toString(16)}`)}}decodeMobileVibrateOrder(e,t){let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++),a=[];for(let u=0;u<o;u++)a.push(e.readUInt16BE(n)),n+=2;let l={type:i,flags:s,pattern:a};return s&1&&(l.intensity=e.readUInt8(n++)/255),{order:l,bytesRead:n-t}}decodeMobileCancelOrder(e,t){return{order:{type:2},bytesRead:1}}decodeGamepadVibrateOrder(e,t){let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++),a=e.readUInt16BE(n);n+=2;let l=e.readUInt8(n++),u=e.readUInt8(n++),c={type:i,flags:s,gamepadIndex:o,duration:a,strongMagnitude:l,weakMagnitude:u};return s&1&&(c.startDelay=e.readUInt16BE(n),n+=2),{order:c,bytesRead:n-t}}decodeGamepadCancelOrder(e,t){let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++);return{order:{type:i,flags:s,gamepadIndex:o},bytesRead:n-t}}};J(Mv,"VibrationOrderDecoder");var LI=Mv,Uv=class{decode(e,t=0){let n=e.readUInt8(t);switch(n){case 1:return this.decodeCreateInstance(e,t);case 2:return this.decodeUpdateInstance(e,t);case 3:return this.decodeRemoveInstance(e,t);default:throw new Error(`Unknown macro order type: 0x${n.toString(16)}`)}}decodeAll(e,t,n){let i=[],s=0;for(let o=0;o<n;o++){let{order:a,bytesRead:l}=this.decode(e,t+s);i.push(a),s+=l}return{orders:i,bytesRead:s}}decodeCreateInstance(e,t){let n=t,i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt8(t++),a=e.readUInt8(t++),l=e.readInt16BE(t);t+=2;let u=e.readInt16BE(t);t+=2;let c=e.readUInt8(t++),d=e.readUInt16BE(t);t+=2;let h=e.toUint8Array().subarray(t,t+d);t+=d;let f=new TextDecoder().decode(h),p=JSON.parse(f);return{order:{type:i,instanceId:s,macroId:o,layerId:a,x:l,y:u,tabIndex:c,params:p},bytesRead:t-n}}decodeUpdateInstance(e,t){let n=t,i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+o);t+=o;let l=new TextDecoder().decode(a),u=JSON.parse(l);return{order:{type:i,instanceId:s,params:u},bytesRead:t-n}}decodeRemoveInstance(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1);return{order:{type:n,instanceId:i},bytesRead:2}}};J(Uv,"MacroOrderDecoder");var _I=Uv,Av=class{decode(e,t){let n=e[t];switch(n){case 1:return this.decodeSetConfigOrder(e,t);case 2:return this.decodeSetScanlinesOrder(e,t);case 3:return this.decodeSetAmbientEffectOrder(e,t);case 4:return this.decodeSetScalingModeOrder(e,t);case 5:return this.decodeSetGridOrder(e,t);case 6:return this.decodeSwitchPaletteOrder(e,t);case 7:return this.decodeSetCellSizeOrder(e,t);default:throw new Error(`Unknown post-process order type: ${n}`)}}decodeSetConfigOrder(e,t){let n=t,i=e[n++],s=e[n++],o=e[n++],a={type:i,displayId:s,flags:o};return o&1&&(a.scanlines={enabled:e[n++]===1,opacity:e[n++]/255,pattern:e[n++],colorR:e[n++],colorG:e[n++],colorB:e[n++]}),o&2&&(a.ambientEffect={enabled:e[n++]===1,blur:e[n++],scale:e[n++]/100,opacity:e[n++]/255}),{order:a,bytesRead:n-t}}decodeSetScanlinesOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],enabled:e[n++]===1,opacity:e[n++]/255,pattern:e[n++],colorR:e[n++],colorG:e[n++],colorB:e[n++]},bytesRead:n-t}}decodeSetAmbientEffectOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],enabled:e[n++]===1,blur:e[n++],scale:e[n++]/100,opacity:e[n++]/255},bytesRead:n-t}}decodeSetScalingModeOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],mode:e[n++]},bytesRead:n-t}}decodeSetGridOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],enabled:e[n++]===1,colorR:e[n++],colorG:e[n++],colorB:e[n++],colorA:e[n++],lineWidth:e[n++]},bytesRead:n-t}}decodeSwitchPaletteOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],slotId:e[n++]},bytesRead:n-t}}decodeSetCellSizeOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],cellWidth:e[n++],cellHeight:e[n++]},bytesRead:n-t}}};J(Av,"PostProcessOrderDecoder");var $I=Av,Tv=class{constructor(){O(this,"displayDecoder"),O(this,"layerDecoder"),O(this,"audioOrderDecoder"),O(this,"vibrationOrderDecoder"),O(this,"macroOrderDecoder"),O(this,"postProcessOrderDecoder"),this.displayDecoder=new PI,this.layerDecoder=new DI,this.audioOrderDecoder=new FI,this.vibrationOrderDecoder=new LI,this.macroOrderDecoder=new _I,this.postProcessOrderDecoder=new $I}decode(e,t=0){let n=ie.from(e);this.checkSize(n,t,15);let i=t,s=Number(n.readBigUInt64BE(i));i+=8;let o=n.readUInt8(i);i+=1;let a=[],l=0;for(let A=0;A<o;A++){let R=this.displayDecoder.decode(n,i);a.push(R.display),i+=R.bytesRead,l+=R.bytesRead}this.checkSize(n,i,2);let u=n.readUInt16BE(i);i+=2;let c=[],d=0;for(let A=0;A<u;A++){let R=this.layerDecoder.decode(n,i);c.push({...R.layer,byteSize:R.bytesRead}),i+=R.bytesRead,d+=R.bytesRead}this.checkSize(n,i,1);let h=n.readUInt8(i);i+=1;let f=[],p=0;for(let A=0;A<h;A++){let R=this.audioOrderDecoder.decode(n,i);f.push(R.order),i+=R.bytesRead,p+=R.bytesRead}this.checkSize(n,i,1);let m=n.readUInt8(i);i+=1;let S=[],w=0;for(let A=0;A<m;A++){let R=this.vibrationOrderDecoder.decode(n,i);S.push(R.order),i+=R.bytesRead,w+=R.bytesRead}this.checkSize(n,i,1);let g=n.readUInt8(i);i+=1;let y=[],C=0;for(let A=0;A<g;A++){let R=this.macroOrderDecoder.decode(n,i);y.push(R.order),i+=R.bytesRead,C+=R.bytesRead}this.checkSize(n,i,1);let x=n.readUInt8(i);i+=1;let I=[],E=0;for(let A=0;A<x;A++){let R=this.postProcessOrderDecoder.decode(n.toUint8Array(),i);I.push(R.order),i+=R.bytesRead,E+=R.bytesRead}return{tick:s,displayCount:o,displays:a,layerCount:u,layers:c,audioOrderCount:h,audioOrders:f,vibrationOrderCount:m,vibrationOrders:S,macroOrderCount:g,macroOrders:y,postProcessOrderCount:x,postProcessOrders:I,__byteSizes:{displays:l,layers:d,audioOrders:p,vibrationOrders:w,macroOrders:C,postProcessOrders:E}}}isValid(e,t=0){let n=ie.from(e);try{return this.checkSize(n,t,15),!0}catch{return!1}}decodeHeader(e,t=0){let n=ie.from(e);this.checkSize(n,t,13);let i=t,s=Number(n.readBigUInt64BE(i));i+=8;let o=n.readUInt8(i);i+=1;for(let l=0;l<o;l++){let u=this.displayDecoder.decode(n,i);i+=u.bytesRead}this.checkSize(n,i,2);let a=n.readUInt16BE(i);return{tick:s,displayCount:o,layerCount:a}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for update packet: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(Tv,"UpdatePacketDecoder");var NI=Tv,nh=class Ts{constructor(e){this.engine=e,O(this,"colorCache",new Array(256)),O(this,"cellsBuffer",[]),O(this,"opacityBuffer",new Uint8Array(0)),O(this,"visibleLayersBuffer",[]),O(this,"visibleLayerIdsBuffer",[]),O(this,"passCellsBuffers",[]),O(this,"passOpacityBuffers",[]),this.rebuildColorCache()}static getChar(e){let t=Ts.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),Ts.charCache.set(e,t)),t}getLastVisibleLayerIds(){return this.visibleLayerIdsBuffer}rebuildColorCache(){for(let e=0;e<256;e++){let t=this.engine.getColor(e);t?this.colorCache[e]={r:t.r,g:t.g,b:t.b,a:t.a}:this.colorCache[e]={r:0,g:0,b:0,a:0}}}getColorRGB(e){return this.colorCache[e]??this.colorCache[255]}getColorEmission(e){let t=this.engine.getColor(e);return t?t.e:0}isLayerVisible(e,t){let n=e.x,i=e.x+e.width,s=e.y,o=e.y+e.height,a=t.x,l=t.x+256,u=t.y,c=t.y+256;return!(i<=a||n>=l||o<=u||s>=c)}rasterize(e,t,n){let i=this.normalizePasses(n);return this.rasterizeMultiPass(e,t,i)}rasterizeSinglePass(e,t){let n=e.width*e.height,i=this.cellsBuffer;i.length=n;for(let u=0;u<n;u++)i[u]?(i[u].char=" ",i[u].fgColorIndex=255,i[u].bgColorIndex=255,i[u].fgEmission=0,i[u].bgEmission=0):i[u]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<n?this.opacityBuffer=new Uint8Array(n):this.opacityBuffer.fill(0,0,n);let s=this.opacityBuffer,o=this.visibleLayersBuffer;o.length=0;for(let u=0;u<t.length;u++){let c=t[u];c.isEnabled()&&this.isLayerVisible(e,c.getOrigin())&&o.push(c)}o.sort((u,c)=>c.getZOrder()-u.getZOrder());let a=this.visibleLayerIdsBuffer;a.length=o.length;for(let u=0;u<o.length;u++)a[u]=o[u].getId();for(let u=0;u<e.height;u++)for(let c=0;c<e.width;c++){let d=u*e.width+c;if(s[d])continue;let h=e.x+c,f=e.y+u;for(let p=0;p<o.length;p++){let m=o[p],S=h-m.getOrigin().x,w=f-m.getOrigin().y,g=m.getWidth(),y=m.getHeight();if(S<0||S>=g||w<0||w>=y)continue;let C=w*g+S,x=m.getData(),I=x.getCharCode(C),E=x.getFgColorCode(C),A=x.getBgColorCode(C),R=i[d];if(I!==0&&R.char===" "&&(R.char=Ts.getChar(I)),E!==255&&R.fgColorIndex===255&&(R.fgColorIndex=E,R.fgEmission=this.getColorEmission(E)),A!==255){R.bgColorIndex===255&&(R.bgColorIndex=A,R.bgEmission=this.getColorEmission(A)),s[d]=1;break}}}let l=new Array(n);for(let u=0;u<n;u++)l[u]={char:i[u].char,fgColorIndex:i[u].fgColorIndex,bgColorIndex:i[u].bgColorIndex,fgEmission:i[u].fgEmission,bgEmission:i[u].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:l,palette:this.colorCache}}rasterizeMultiPass(e,t,n){let i=e.width*e.height;this.ensurePassBuffers(n.length,i),this.visibleLayerIdsBuffer.length=0;let s=this.visibleLayersBuffer;s.length=0;for(let c=0;c<t.length;c++){let d=t[c];d.isEnabled()&&this.isLayerVisible(e,d.getOrigin())&&s.push(d)}s.sort((c,d)=>d.getZOrder()-c.getZOrder());for(let c=0;c<n.length;c++){let d=n[c],h=this.passCellsBuffers[c],f=this.preparePassBuffers(h,this.passOpacityBuffers[c],i);this.passOpacityBuffers[c]=f;let p=[];for(let S=0;S<s.length;S++){let w=s[S],g=w.getZOrder();g<d.zMin||g>d.zMax||p.push(w)}let m=this.visibleLayerIdsBuffer.length;for(let S=0;S<p.length;S++)this.visibleLayerIdsBuffer[m+S]=p[S].getId();this.composePass(e,p,h,f)}let o=this.cellsBuffer,a=this.preparePassBuffers(o,this.opacityBuffer,i);this.opacityBuffer=a;let l=new Array(i),u=[];for(let c=0;c<n.length;c++){let d=this.passCellsBuffers[c],h=new Array(i);for(let f=0;f<i;f++){let p=d[f];h[f]={char:p.char,fgColorIndex:p.fgColorIndex,bgColorIndex:p.bgColorIndex,fgEmission:p.fgEmission,bgEmission:p.bgEmission}}u.push({id:n[c].id,zMin:n[c].zMin,zMax:n[c].zMax,cells:h})}for(let c=0;c<i;c++){let d=o[c];for(let h=n.length-1;h>=0;h--){let f=this.passCellsBuffers[h][c];if(d.char===" "&&f.char!==" "&&(d.char=f.char),d.fgColorIndex===255&&f.fgColorIndex!==255&&(d.fgColorIndex=f.fgColorIndex,d.fgEmission=f.fgEmission),f.bgColorIndex!==255){d.bgColorIndex===255&&(d.bgColorIndex=f.bgColorIndex,d.bgEmission=f.bgEmission);break}}l[c]={char:d.char,fgColorIndex:d.fgColorIndex,bgColorIndex:d.bgColorIndex,fgEmission:d.fgEmission,bgEmission:d.bgEmission}}return{id:e.id,width:e.width,height:e.height,cells:l,palette:this.colorCache,passes:u}}composePass(e,t,n,i){let s=e.width,o=e.height;for(let a=0;a<o;a++)for(let l=0;l<s;l++){let u=a*s+l;if(i[u])continue;let c=e.x+l,d=e.y+a;for(let h=0;h<t.length;h++){let f=t[h],p=c-f.getOrigin().x,m=d-f.getOrigin().y,S=f.getWidth(),w=f.getHeight();if(p<0||p>=S||m<0||m>=w)continue;let g=m*S+p,y=f.getData(),C=y.getCharCode(g),x=y.getFgColorCode(g),I=y.getBgColorCode(g),E=n[u];if(C!==0&&E.char===" "&&(E.char=Ts.getChar(C)),x!==255&&E.fgColorIndex===255&&(E.fgColorIndex=x,E.fgEmission=this.getColorEmission(x)),I!==255){E.bgColorIndex===255&&(E.bgColorIndex=I,E.bgEmission=this.getColorEmission(I)),i[u]=1;break}}}}preparePassBuffers(e,t,n){e.length=n;for(let i=0;i<n;i++)e[i]?(e[i].char=" ",e[i].fgColorIndex=255,e[i].bgColorIndex=255,e[i].fgEmission=0,e[i].bgEmission=0):e[i]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};return t.length<n?t=new Uint8Array(n):t.fill(0,0,n),t}ensurePassBuffers(e,t){for(;this.passCellsBuffers.length<e;)this.passCellsBuffers.push([]);for(;this.passOpacityBuffers.length<e;)this.passOpacityBuffers.push(new Uint8Array(t));this.passCellsBuffers.length>e&&(this.passCellsBuffers.length=e),this.passOpacityBuffers.length>e&&(this.passOpacityBuffers.length=e);for(let n=0;n<e;n++)this.passOpacityBuffers[n].length<t?this.passOpacityBuffers[n]=new Uint8Array(t):this.passOpacityBuffers[n].fill(0,0,t)}normalizePasses(e){let t={id:0,zMin:0,zMax:255,enabled:!0};if(!e||e.length===0)return[t];let n=e.filter(i=>i.enabled!==!1);return n.length===0?[t]:n.slice(0,4)}rasterizeWithSortedLayers(e,t){let n=e.width*e.height,i=this.cellsBuffer;i.length=n;for(let l=0;l<n;l++)i[l]?(i[l].char=" ",i[l].fgColorIndex=255,i[l].bgColorIndex=255,i[l].fgEmission=0,i[l].bgEmission=0):i[l]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<n?this.opacityBuffer=new Uint8Array(n):this.opacityBuffer.fill(0,0,n);let s=this.opacityBuffer,o=this.visibleLayersBuffer;o.length=0;for(let l=0;l<t.length;l++){let u=t[l];this.isLayerVisible(e,u.getOrigin())&&o.push(u)}for(let l=0;l<e.height;l++)for(let u=0;u<e.width;u++){let c=l*e.width+u;if(s[c])continue;let d=e.x+u,h=e.y+l;for(let f=0;f<o.length;f++){let p=o[f],m=d-p.getOrigin().x,S=h-p.getOrigin().y,w=p.getWidth(),g=p.getHeight();if(m<0||m>=w||S<0||S>=g)continue;let y=S*w+m,C=p.getData(),x=C.getCharCode(y),I=C.getFgColorCode(y),E=C.getBgColorCode(y),A=i[c];if(x!==0&&A.char===" "&&(A.char=Ts.getChar(x)),I!==255&&A.fgColorIndex===255&&(A.fgColorIndex=I,A.fgEmission=this.getColorEmission(I)),E!==255){A.bgColorIndex===255&&(A.bgColorIndex=E,A.bgEmission=this.getColorEmission(E)),s[c]=1;break}}}let a=new Array(n);for(let l=0;l<n;l++)a[l]={char:i[l].char,fgColorIndex:i[l].fgColorIndex,bgColorIndex:i[l].bgColorIndex,fgEmission:i[l].fgEmission,bgEmission:i[l].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:a,palette:this.colorCache}}calculateIntersection(e,t){let n=e.x,i=e.x+e.width,s=e.y,o=e.y+e.height,a=t.x,l=t.x+256,u=t.y,c=t.y+256,d=Math.max(n,a),h=Math.min(i,l),f=Math.max(s,u),p=Math.min(o,c);return{visible:d<h&&f<p,originStart:{x:d-e.x,y:f-e.y},originEnd:{x:h-e.x,y:p-e.y},layerStart:{x:d-t.x,y:f-t.y},layerEnd:{x:h-t.x,y:p-t.y}}}};J(nh,"DisplayRasterizer"),O(nh,"charCache",(()=>{let r=new Map;for(let e=0;e<256;e++)r.set(e,String.fromCharCode(e));return r})());var VI=nh,Rv=class{constructor(){O(this,"enabled",!1),O(this,"currentStats",null)}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get tick(){var e;return((e=this.currentStats)==null?void 0:e.tick)??0}get timestamp(){var e;return((e=this.currentStats)==null?void 0:e.timestamp)??0}get totalOrders(){var e;return((e=this.currentStats)==null?void 0:e.totalOrders)??0}get ordersByLayer(){var e;return((e=this.currentStats)==null?void 0:e.ordersByLayer)??new Map}get ordersByType(){var e;return((e=this.currentStats)==null?void 0:e.ordersByType)??new Map}get totalLayers(){var e;return((e=this.currentStats)==null?void 0:e.totalLayers)??0}get visibleLayers(){var e;return((e=this.currentStats)==null?void 0:e.visibleLayers)??0}get layersPerDisplay(){var e;return((e=this.currentStats)==null?void 0:e.layersPerDisplay)??new Map}get displayCompositeLayerIds(){var e;return((e=this.currentStats)==null?void 0:e.displayCompositeLayerIds)??new Map}get updatePacketSize(){var e;return((e=this.currentStats)==null?void 0:e.updatePacketSize)??0}get displayHeaderSize(){var e;return((e=this.currentStats)==null?void 0:e.displayHeaderSize)??0}get layerHeaderSize(){var e;return((e=this.currentStats)==null?void 0:e.layerHeaderSize)??0}get orderDataSize(){var e;return((e=this.currentStats)==null?void 0:e.orderDataSize)??0}get compressionRatio(){var e;return((e=this.currentStats)==null?void 0:e.compressionRatio)??0}get compressedPacketSize(){return Math.round(this.updatePacketSize*this.compressionRatio)}get totalCells(){var e;return((e=this.currentStats)==null?void 0:e.totalCells)??0}get nonEmptyCells(){var e;return((e=this.currentStats)==null?void 0:e.nonEmptyCells)??0}get cellsWithBackground(){var e;return((e=this.currentStats)==null?void 0:e.cellsWithBackground)??0}get rasterizationTimeMs(){var e;return((e=this.currentStats)==null?void 0:e.rasterizationTimeMs)??0}get encodingTimeMs(){var e;return((e=this.currentStats)==null?void 0:e.encodingTimeMs)??0}get packetSplit(){var e;return(e=this.currentStats)==null?void 0:e.packetSplit}get layerDetails(){var e;return(e=this.currentStats)==null?void 0:e.layerDetails}startTick(e){this.enabled&&(this.currentStats={tick:e,timestamp:Date.now(),totalOrders:0,ordersByLayer:new Map,ordersByType:new Map,totalLayers:0,visibleLayers:0,layersPerDisplay:new Map,updatePacketSize:0,displayHeaderSize:0,layerHeaderSize:0,orderDataSize:0,compressionRatio:0,totalCells:0,nonEmptyCells:0,cellsWithBackground:0,rasterizationTimeMs:0,encodingTimeMs:0,displayCompositeLayerIds:new Map})}recordDisplayComposite(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCompositeLayerIds||(this.currentStats.displayCompositeLayerIds=new Map),this.currentStats.displayCompositeLayerIds.set(e,[...t]))}recordLayerOrders(e,t){if(!(!this.enabled||!this.currentStats)){this.currentStats.totalOrders+=t.length,this.currentStats.ordersByLayer.set(e,t.length);for(let n of t){let i=this.currentStats.ordersByType.get(n.type)||0;this.currentStats.ordersByType.set(n.type,i+1)}}}recordLayers(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t)}recordDisplayLayers(e,t){!this.enabled||!this.currentStats||this.currentStats.layersPerDisplay.set(e,t)}recordUpdatePacketSize(e,t,n,i){!this.enabled||!this.currentStats||(this.currentStats.updatePacketSize=e,this.currentStats.displayHeaderSize=t,this.currentStats.layerHeaderSize=n,this.currentStats.orderDataSize=i,this.currentStats.compressionRatio=.25)}recordPacketSplit(e,t,n,i){!this.enabled||!this.currentStats||(this.currentStats.packetSplit={userId:e,displayCount:t,staticLayerCount:n,dynamicLayerCount:i})}recordLayerInfo(e,t,n,i){!this.enabled||!this.currentStats||(this.currentStats.layerDetails||(this.currentStats.layerDetails=[]),this.currentStats.layerDetails.push({layerId:e,mustBeReliable:t,orderCount:n,updateFlags:i}))}recordRenderStats(e,t,n){!this.enabled||!this.currentStats||(this.currentStats.totalCells=e,this.currentStats.nonEmptyCells=t,this.currentStats.cellsWithBackground=n)}recordRasterizationTime(e){!this.enabled||!this.currentStats||(this.currentStats.rasterizationTimeMs=e)}recordEncodingTime(e){!this.enabled||!this.currentStats||(this.currentStats.encodingTimeMs=e)}endTick(){}reset(){this.currentStats=null}};J(Rv,"CoreStats");var HI=Rv,Pv=[[0,0],[9786,1],[9787,2],[9829,3],[9830,4],[9827,5],[9824,6],[8226,7],[9688,8],[9675,9],[9689,10],[9794,11],[9792,12],[9834,13],[9835,14],[9788,15],[9658,16],[9668,17],[8597,18],[8252,19],[182,20],[167,21],[9644,22],[8616,23],[8593,24],[8595,25],[8594,26],[8592,27],[8735,28],[8596,29],[9650,30],[9660,31],[8962,127],[199,128],[252,129],[233,130],[226,131],[228,132],[224,133],[229,134],[231,135],[234,136],[235,137],[232,138],[239,139],[238,140],[236,141],[196,142],[197,143],[201,144],[230,145],[198,146],[244,147],[246,148],[242,149],[251,150],[249,151],[255,152],[214,153],[220,154],[162,155],[163,156],[165,157],[8359,158],[402,159],[225,160],[237,161],[243,162],[250,163],[241,164],[209,165],[170,166],[186,167],[191,168],[8976,169],[172,170],[189,171],[188,172],[161,173],[171,174],[187,175],[9617,176],[9618,177],[9619,178],[9474,179],[9508,180],[9569,181],[9570,182],[9558,183],[9557,184],[9571,185],[9553,186],[9559,187],[9565,188],[9564,189],[9563,190],[9488,191],[9492,192],[9524,193],[9516,194],[9500,195],[9472,196],[9532,197],[9566,198],[9567,199],[9562,200],[9556,201],[9577,202],[9574,203],[9568,204],[9552,205],[9580,206],[9575,207],[9576,208],[9572,209],[9573,210],[9561,211],[9560,212],[9554,213],[9555,214],[9579,215],[9578,216],[9496,217],[9484,218],[9608,219],[9604,220],[9612,221],[9616,222],[9600,223],[945,224],[223,225],[915,226],[960,227],[931,228],[963,229],[181,230],[964,231],[934,232],[920,233],[937,234],[948,235],[8734,236],[966,237],[949,238],[8745,239],[8801,240],[177,241],[8805,242],[8804,243],[8992,244],[8993,245],[247,246],[8776,247],[176,248],[8729,249],[183,250],[8730,251],[8319,252],[178,253],[9632,254],[160,255]],jI=new Map(Pv);new Map(Pv.map(([r,e])=>[e,r]));function Qs(r){if(r<128)return r;let e=jI.get(r);return e!==void 0?e:r&255}J(Qs,"unicodeToCp437");var Bv=class{constructor(){O(this,"unicolorSprites",new Map),O(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){if("loadType"in e){this.loadUnicolorSpritesFromPacket(e);return}for(let t of e){let{spriteId:n,sizeX:i,sizeY:s,data:o}=t,a=new Vg(i*s);if(typeof o=="string"){let u=o.replace(/\n/g,"");for(let c=0;c<Math.min(u.length,i*s);c++)a.set(c,Qs(u.charCodeAt(c)))}else if(Array.isArray(o)&&o.length>0&&typeof o[0]=="string"){let u=o;for(let c=0;c<Math.min(u.length,s);c++){let d=u[c];if(d)for(let h=0;h<Math.min(d.length,i);h++)a.set(c*i+h,Qs(d.charCodeAt(h)))}}else{let u=o;for(let c=0;c<Math.min(u.length,i*s);c++)a.set(c,u[c])}let l={id:n,sizeX:i,sizeY:s,data:a};this.unicolorSprites.set(l.id,l)}}loadUnicolorSpritesFromPacket(e){for(let t of e.sprites){let n=new Vg(t.sizeX*t.sizeY);for(let s=0;s<t.data.length;s++)n.set(s,t.data[s]);let i={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:n};this.unicolorSprites.set(i.id,i)}}loadMulticolorSprites(e){if("loadType"in e){this.loadMulticolorSpritesFromPacket(e);return}for(let t of e){let{spriteId:n,sizeX:i,sizeY:s,data:o}=t,a=new th(i*s);for(let u=0;u<Math.min(o.length,i*s);u++){let c=o[u],d=typeof c.charCode=="string"?Qs(c.charCode.charCodeAt(0)):c.charCode;a.set(u,d,c.fgColorId,c.bgColorId)}let l={id:n,sizeX:i,sizeY:s,data:a};this.multicolorSprites.set(l.id,l)}}loadMulticolorSpritesFromPacket(e){for(let t of e.sprites){let n=new th(t.sizeX*t.sizeY);for(let s=0;s<t.data.length;s++){let o=t.data[s];n.set(s,o.charCode,o.fgColorId,o.bgColorId)}let i={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:n};this.multicolorSprites.set(i.id,i)}}getUnicolorSprite(e){return this.unicolorSprites.get(e)}getMulticolorSprite(e){return this.multicolorSprites.get(e)}hasUnicolorSprite(e){return this.unicolorSprites.has(e)}hasMulticolorSprite(e){return this.multicolorSprites.has(e)}unloadUnicolorSprite(e){return this.unicolorSprites.delete(e)}unloadMulticolorSprite(e){return this.multicolorSprites.delete(e)}clearUnicolorSprites(){this.unicolorSprites.clear()}clearMulticolorSprites(){this.multicolorSprites.clear()}clearAll(){this.unicolorSprites.clear(),this.multicolorSprites.clear()}getUnicolorSpriteCount(){return this.unicolorSprites.size}getMulticolorSpriteCount(){return this.multicolorSprites.size}getTotalSpriteCount(){return this.unicolorSprites.size+this.multicolorSprites.size}};J(Bv,"SpriteRegistry");var YI=Bv,WI=(r=>(r.Bitmap="bitmap",r.Image="image",r))(WI||{});function Ef(r){return Math.sqrt(r)*16}J(Ef,"getAtlasColumns");function zv(r){return r*256-1}J(zv,"getMaxCharCode");function GI(r,e){let t=Ef(r)*e;return{width:t,height:t}}J(GI,"getAtlasDimensions");var Ov=class{constructor(e,t){this.fontId=e,this.config=t,O(this,"atlasColumns"),O(this,"maxCharCode"),O(this,"blocks",new Map),this.atlasColumns=Ef(t.atlasBlocks),this.maxCharCode=zv(t.atlasBlocks)}addBlock(e,t){if(e<0||e>=this.config.atlasBlocks)throw new Error(`Invalid block index ${e} for font with ${this.config.atlasBlocks} blocks`);this.blocks.set(e,t)}getBlock(e){return this.blocks.get(e)}getFontId(){return this.fontId}getConfig(){return{glyphWidth:this.config.glyphWidth,glyphHeight:this.config.glyphHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,atlasBlocks:this.config.atlasBlocks}}getGlyphWidth(){return this.config.glyphWidth}getGlyphHeight(){return this.config.glyphHeight}getCellWidth(){return this.config.cellWidth??this.config.glyphWidth}getCellHeight(){return this.config.cellHeight??this.config.glyphHeight}getAtlasBlocks(){return this.config.atlasBlocks}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}getAtlasDimensions(){return{width:this.atlasColumns*this.config.glyphWidth,height:this.atlasColumns*this.config.glyphHeight}}getCharUV(e){if(e<0||e>this.maxCharCode)return null;let t=e%this.atlasColumns,n=Math.floor(e/this.atlasColumns),i=t/this.atlasColumns,s=n/this.atlasColumns,o=(t+1)/this.atlasColumns,a=(n+1)/this.atlasColumns;return{u1:i,v1:s,u2:o,v2:a}}isValidCharCode(e){return e>=0&&e<=this.maxCharCode}};J(Ov,"ImageFont");var qg=Ov,Dv=class{constructor(){O(this,"fonts",new Map),O(this,"nameToId",new Map),O(this,"nextId",0)}allocateId(e){if(this.nextId>255)throw new Error(`Cannot register font "${e}": maximum 256 fonts reached`);return this.nextId++}registerFont(e,t){if(this.nameToId.has(e))throw new Error(`ImageFont with name "${e}" already exists`);let n=this.allocateId(e),i={glyphWidth:t.glyphWidth,glyphHeight:t.glyphHeight,cellWidth:t.cellWidth,cellHeight:t.cellHeight,atlasBlocks:t.atlasBlocks??1},s=new qg(n,i);return this.fonts.set(n,s),this.nameToId.set(e,n),n}addBlock(e,t,n){let i=this.fonts.get(e);if(!i)throw new Error(`ImageFont with ID ${e} not found`);i.addBlock(t,n)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`ImageFont with ID ${e} already exists`);let n=new qg(e,t);this.fonts.set(e,n),e>=this.nextId&&(this.nextId=e+1)}getFont(e){return this.fonts.get(e)}getFontByName(e){let t=this.nameToId.get(e);if(t!==void 0)return this.fonts.get(t)}getFontId(e){return this.nameToId.get(e)}getFontName(e){for(let[t,n]of this.nameToId.entries())if(n===e)return t}hasFont(e){return this.fonts.has(e)}hasFontByName(e){return this.nameToId.has(e)}unloadFont(e){if(!this.fonts.get(e))return!1;for(let[t,n]of this.nameToId.entries())if(n===e){this.nameToId.delete(t);break}return this.fonts.delete(e)}unloadFontByName(e){let t=this.nameToId.get(e);return t===void 0?!1:(this.nameToId.delete(e),this.fonts.delete(t))}clearFonts(){this.fonts.clear(),this.nameToId.clear(),this.nextId=0}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getFontNames(){return Array.from(this.nameToId.keys())}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};J(Dv,"ImageFontRegistry");var XI=Dv,Fv=class{constructor(){O(this,"sounds",new Map),O(this,"nameToId",new Map),O(this,"nextId",0)}registerFile(e,t,n){let i=this.allocateId(e),s={soundId:i,name:e,loadType:"file",format:t,data:n};return this.sounds.set(i,s),this.nameToId.set(e,i),i}registerFileWithId(e,t,n,i){this.validateId(e),this.checkIdAvailable(e,t);let s={soundId:e,name:t,loadType:"file",format:n,data:i};this.sounds.set(e,s),this.nameToId.set(t,e)}registerExternal(e,t,n,i,s){let o=this.allocateId(e),a={soundId:o,name:e,loadType:"external",format:t,url:n,size:i,checksum:s};return this.sounds.set(o,a),this.nameToId.set(e,o),o}registerExternalWithId(e,t,n,i,s,o){this.validateId(e),this.checkIdAvailable(e,t);let a={soundId:e,name:t,loadType:"external",format:n,url:i,size:s,checksum:o};this.sounds.set(e,a),this.nameToId.set(t,e)}get(e){if(typeof e=="number")return this.sounds.get(e);let t=this.nameToId.get(e);return t!==void 0?this.sounds.get(t):void 0}has(e){return this.get(e)!==void 0}getAll(){return Array.from(this.sounds.values())}getFileSounds(){return this.getAll().filter(e=>e.loadType==="file")}getExternalSounds(){return this.getAll().filter(e=>e.loadType==="external")}getNames(){return Array.from(this.nameToId.keys())}getId(e){return this.nameToId.get(e)}toLoadPackets(){let e=[],t=this.sounds.size,n=this.getFileSounds();if(n.length>0){let s=n.map(o=>({soundId:o.soundId,name:o.name,format:o.format,data:o.data}));e.push({type:"sound",mode:"file",sounds:s,totalSounds:t})}let i=this.getExternalSounds();if(i.length>0){let s=i.map(o=>({soundId:o.soundId,name:o.name,format:o.format,url:o.url,size:o.size,checksum:o.checksum}));e.push({type:"sound",mode:"external",sounds:s,totalSounds:t})}return e}toLoadPacket(e){let t=this.get(e);return t?t.loadType==="file"?{type:"sound",mode:"file",sounds:[{soundId:t.soundId,name:t.name,format:t.format,data:t.data}]}:{type:"sound",mode:"external",sounds:[{soundId:t.soundId,name:t.name,format:t.format,url:t.url,size:t.size,checksum:t.checksum}]}:null}unregister(e){let t=this.get(e);return t?(this.sounds.delete(t.soundId),this.nameToId.delete(t.name),!0):!1}clear(){this.sounds.clear(),this.nameToId.clear(),this.nextId=0}get size(){return this.sounds.size}getStats(){let e=this.getAll(),t=e.filter(i=>i.loadType==="file"),n=t.reduce((i,s)=>{var o;return i+(((o=s.data)==null?void 0:o.length)??0)},0);return{total:e.length,file:t.length,external:e.length-t.length,totalFileSize:n}}allocateId(e){if(this.nameToId.has(e))throw new Error(`Sound with name "${e}" already exists`);for(;this.sounds.has(this.nextId);)if(this.nextId++,this.nextId>255)throw new Error("Maximum number of sounds (256) reached");return this.nextId++}validateId(e){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`Invalid sound ID: ${e}. Must be an integer between 0 and 255.`)}checkIdAvailable(e,t){if(this.sounds.has(e)){let n=this.sounds.get(e);throw new Error(`Sound ID ${e} is already used by "${n.name}". Cannot register "${t}".`)}if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" already exists`)}};J(Fv,"SoundRegistry");var KI=Fv,Lv=class{constructor(e){this.soundRegistry=e}collectFromUser(e){let t=[],n=e.flushSoundCommands();for(let s of n){let o=this.convertSoundCommand(s);o&&t.push(o)}let i=e.flushAudioConfigCommands();for(let s of i){let o=this.convertConfigCommand(s);o&&t.push(o)}return t}convertSoundCommand(e){return"setEffects"in e&&e.setEffects===!0?this.convertSetEffectsCommand(e):"fadeOut"in e&&e.fadeOut===!0?this.convertFadeOutCommand(e):"pause"in e&&e.pause===!0?this.convertPauseCommand(e):"resume"in e&&e.resume===!0?this.convertResumeCommand(e):"instanceId"in e||"volume"in e||"pitch"in e||"loop"in e||"fadeIn"in e||"x"in e||"y"in e||"lowpass"in e||"highpass"in e||"reverb"in e?this.convertPlayCommand(e):this.convertStopCommand(e)}convertPlayCommand(e){let t=this.resolveSoundId(e.sound);if(t===null)return console.warn(`[AudioOrderCollector] Unknown sound: ${e.sound}`),null;let n=0;e.loop&&(n|=1),e.volume!==void 0&&(n|=2),e.pitch!==void 0&&(n|=4),e.fadeIn!==void 0&&(n|=8),e.lowpass!==void 0&&e.lowpass>0&&(n|=32),e.highpass!==void 0&&e.highpass>0&&(n|=64),e.reverb!==void 0&&e.reverb>0&&(n|=128);let i=e.x!==void 0&&e.y!==void 0;return i&&(n|=16),i?{type:1,soundId:t,instanceId:e.instanceId??0,flags:n,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,posX:this.encodePosition(e.x),posY:this.encodePosition(e.y),lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}:{type:2,soundId:t,instanceId:e.instanceId??0,flags:n&-17,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}}convertStopCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:3,targetType:t,target:n}}convertFadeOutCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:4,targetType:t,duration:this.encodeFadeTime(e.duration),target:n}}convertPauseCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:5,targetType:t,target:n}}convertResumeCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:6,targetType:t,target:n}}convertSetEffectsCommand(e){let t=0;return e.lowpass!==void 0&&(t|=1),e.highpass!==void 0&&(t|=2),e.reverb!==void 0&&(t|=4),{type:9,instanceId:e.instanceId,flags:t,lowpass:e.lowpass!==void 0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0?this.encodeReverb(e.reverb):void 0}}convertConfigCommand(e){return e.type==="set-listener-position"?{type:7,x:this.encodePosition(e.x),y:this.encodePosition(e.y)}:e.type==="configure-spatial"?{type:8,maxDistance:this.encodeDistance(e.maxDistance??1e3),referenceDistance:this.encodeDistance(e.referenceDistance??100),rolloffFactor:this.encodeRolloff(e.rolloffFactor??1),panSpread:this.encodePanSpread(e.panSpread??.5)}:null}resolveSoundId(e){if(typeof e=="number")return e>=0&&e<=255?e:null;let t=this.soundRegistry.getId(e);return t!==void 0?t:null}resolveTarget(e){if(e==="all")return{targetType:2,target:void 0};if(typeof e=="number")return{targetType:0,target:e};let t=this.soundRegistry.getId(e);return t!==void 0?{targetType:1,target:t}:(console.warn(`[AudioOrderCollector] Unknown sound name: ${e}, treating as 'all'`),{targetType:2,target:void 0})}encodeVolume(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePitch(e){let t=Math.max(.25,Math.min(4,e)),n=64*Math.log2(t/.25);return Math.round(Math.max(0,Math.min(255,n)))}encodeFadeTime(e){return Math.round(Math.max(0,Math.min(25.5,e))*10)}encodeDistance(e){return Math.round(Math.max(0,Math.min(25500,e))/100)}encodeRolloff(e){return Math.round(Math.max(0,Math.min(2.55,e))*100)}encodePanSpread(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePosition(e){return Math.round(Math.max(0,Math.min(65535,e)))}encodeFilterFreq(e){return e<=0?0:Math.round(Math.max(1,Math.min(255,e/100)))}encodeReverb(e){return Math.round(Math.max(0,Math.min(1,e))*255)}};J(Lv,"AudioOrderCollector");var ZI=Lv,_v=class{collectFromUser(e){let t=[];if(e.hasMobileVibrationCommands()){let n=e.flushMobileVibrationCommands();for(let i of n){let s=this.convertMobileCommand(i);s&&t.push(s)}}if(e.hasGamepadVibrationCommands()){let n=e.flushGamepadVibrationCommands();for(let i of n){let s=this.convertGamepadCommand(i);s&&t.push(s)}}return t}convertMobileCommand(e){return"cancel"in e&&e.cancel===!0?this.convertMobileCancelCommand():"pattern"in e?this.convertMobileVibrateCommand(e):null}convertMobileVibrateCommand(e){let t=0;e.intensity!==void 0&&e.intensity!==1&&(t|=1);let n=e.pattern,i=Array.isArray(n)?[...n]:[n],s={type:1,flags:t,pattern:i.map(o=>Math.round(o))};return t&1&&(s.intensity=Math.round(Math.min(1,Math.max(0,e.intensity))*255)/255),s}convertMobileCancelCommand(){return{type:2}}convertGamepadCommand(e){if("cancel"in e&&e.cancel===!0){let t=e.gamepadIndex??"all";return this.convertGamepadCancelCommand({gamepadIndex:t})}if("options"in e&&e.options){let t=e.gamepadIndex??0;return this.convertGamepadVibrateCommand({gamepadIndex:t,options:e.options})}return null}convertGamepadVibrateCommand(e){let{gamepadIndex:t,options:n}=e,i=0;n.startDelay!==void 0&&n.startDelay>0&&(i|=1);let s=t==="all"?255:t;t==="all"&&(i|=2);let o={type:16,flags:i,gamepadIndex:s,duration:Math.round(n.duration),strongMagnitude:Math.round(Math.min(1,Math.max(0,n.strongMagnitude??1))*255),weakMagnitude:Math.round(Math.min(1,Math.max(0,n.weakMagnitude??.5))*255)};return n.startDelay!==void 0&&n.startDelay>0&&(o.startDelay=Math.round(n.startDelay)),o}convertGamepadCancelCommand(e){let{gamepadIndex:t}=e,n=0,i=t==="all"?255:t;return t==="all"&&(n|=2),{type:17,flags:n,gamepadIndex:i}}};J(_v,"VibrationOrderCollector");var qI=_v,$v=class{collectFromUser(e){let t=e.flushPostProcessCommands();return this.convertCommands(t)}convertCommands(e){let t=[];for(let n of e){let i=this.convertCommand(n);i&&t.push(i)}return t}convertCommand(e){let t=e.displayId;switch(e.type){case"set-config":return this.convertSetConfig(e);case"set-scanlines-enabled":return this.createSetScanlinesOrder(t,e.enabled??!1,e.opacity);case"set-scanlines-opacity":return this.createSetScanlinesOrder(t,!0,e.opacity??Ge.scanlines.opacity);case"set-ambient-effect-enabled":return this.createSetAmbientEffectOrder(t,e.enabled??!1);case"set-ambient-effect-blur":return this.createSetAmbientEffectOrder(t,!0,e.blur);case"set-ambient-effect-scale":return this.createSetAmbientEffectOrder(t,!0,void 0,e.scale);case"set-scaling-mode":return this.createSetScalingModeOrder(t,e.scalingMode);case"set-grid":return this.createSetGridOrder(t,e.gridConfig);case"switch-palette":return this.createSwitchPaletteOrder(t,e.paletteSlotId);case"set-cell-size":return this.createSetCellSizeOrder(t,e.cellWidth,e.cellHeight);default:return console.warn(`[PostProcessOrderCollector] Unknown command type: ${e.type}`),null}}convertSetConfig(e){var s,o,a;let t=e.displayId;if(!e.config)return{type:1,displayId:t,flags:3,scanlines:{enabled:!1,opacity:0,pattern:0,colorR:0,colorG:0,colorB:0},ambientEffect:{enabled:!1,blur:0,scale:1,opacity:0}};let n=0,i={type:1,displayId:t,flags:0};if(e.config.scanlines){n|=1;let l=e.config.scanlines;i.scanlines={enabled:l.enabled,opacity:l.opacity??Ge.scanlines.opacity,pattern:this.patternToType(l.pattern??"horizontal"),colorR:((s=l.color)==null?void 0:s.r)??0,colorG:((o=l.color)==null?void 0:o.g)??0,colorB:((a=l.color)==null?void 0:a.b)??0}}if(e.config.ambientEffect){n|=2;let l=e.config.ambientEffect;i.ambientEffect={enabled:l.enabled,blur:l.blur??Ge.ambientEffect.blur,scale:l.scale??Ge.ambientEffect.scale,opacity:l.opacity??Ge.ambientEffect.opacity}}return i.flags=n,i}createSetScanlinesOrder(e,t,n){return{type:2,displayId:e,enabled:t,opacity:n??Ge.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,n,i){return{type:3,displayId:e,enabled:t,blur:n??Ge.ambientEffect.blur,scale:i??Ge.ambientEffect.scale,opacity:Ge.ambientEffect.opacity}}patternToType(e){switch(e){case"horizontal":return 0;case"vertical":return 1;case"grid":return 2;default:return 0}}createSetScalingModeOrder(e,t){return{type:4,displayId:e,mode:E1(t)}}createSetGridOrder(e,t){let{r:n,g:i,b:s,a:o}=this.parseColor(t.color??js.color);return{type:5,displayId:e,enabled:t.enabled,colorR:n,colorG:i,colorB:s,colorA:o,lineWidth:t.lineWidth??js.lineWidth}}createSwitchPaletteOrder(e,t){return{type:6,displayId:e,slotId:t}}createSetCellSizeOrder(e,t,n){return{type:7,displayId:e,cellWidth:t,cellHeight:n}}parseColor(e){let t=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?Math.round(parseFloat(t[4])*255):255};let n=e.match(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/);if(n){let i=n[1];return i.length===3?{r:parseInt(i[0]+i[0],16),g:parseInt(i[1]+i[1],16),b:parseInt(i[2]+i[2],16),a:255}:{r:parseInt(i.slice(0,2),16),g:parseInt(i.slice(2,4),16),b:parseInt(i.slice(4,6),16),a:255}}return{r:144,g:24,b:24,a:255}}};J($v,"PostProcessOrderCollector");var Mf=$v,ih=class sh{constructor(e={}){O(this,"mode"),O(this,"maxUsers"),O(this,"strictMode",!1),O(this,"currentTick",0),O(this,"stats",new HI),O(this,"spriteRegistry",new YI),O(this,"imageFontRegistry",new XI),O(this,"soundRegistry",new KI),O(this,"audioOrderCollector",new ZI(this.soundRegistry)),O(this,"vibrationOrderCollector",new qI),O(this,"postProcessOrderCollector",new Mf),O(this,"encoder",new EI),O(this,"users",new Map),O(this,"colorPalette",new Map),O(this,"paletteSlots",new Map),O(this,"displayRasterizer",new VI(this)),O(this,"updatePacketDecoder",new NI),O(this,"loadDecoder",new TI),O(this,"cachedLoadPackets",null),O(this,"_renderCallCount",0),O(this,"onPaletteChangedCallback"),O(this,"onFontAllocatedCallback"),O(this,"onFontBlockAddedCallback"),O(this,"onImageFontChangedCallback"),this.mode=e.mode??"standalone",this.maxUsers=e.maxUsers??(this.mode==="client"?1:100),this.initializeDefaultPalette(),this.loadFont(8,8,1,8,8)}initializeDefaultPalette(){[{r:0,g:0,b:0},{r:170,g:0,b:0},{r:0,g:170,b:0},{r:170,g:85,b:0},{r:0,g:0,b:170},{r:170,g:0,b:170},{r:0,g:170,b:170},{r:170,g:170,b:170},{r:85,g:85,b:85},{r:255,g:85,b:85},{r:85,g:255,b:85},{r:255,g:255,b:85},{r:85,g:85,b:255},{r:255,g:85,b:255},{r:85,g:255,b:255},{r:255,g:255,b:255}].forEach((e,t)=>this.colorPalette.set(t,{...e,a:255,e:0})),sh.ANSI_VGA_COLORS.forEach(e=>this.colorPalette.set(e.colorId,e)),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0})}isServer(){return this.mode==="server"}isClient(){return this.mode==="client"}isStandalone(){return this.mode==="standalone"}createUser(e,t){if(this.users.has(e))throw new Error(`User with ID ${e} already exists`);if(this.mode==="server"&&this.users.size>=this.maxUsers)throw new Error(`Maximum number of users reached (${this.maxUsers}). Cannot create user ${e}`);if(this.mode==="client"&&this.users.size>=1)throw new Error(`Client mode only allows one user. Cannot create user ${e}`);let n=new vI(e,t,this.mode);return n.setSpriteRegistry(this.spriteRegistry),this.users.set(e,n),n}getUser(e){return this.users.get(e)??null}getUsers(){return Array.from(this.users.values())}hasUser(e){return this.users.has(e)}removeUser(e){return this.users.delete(e)}getUserCount(){return this.users.size}clearAllUsers(){this.users.clear()}setColor(e,t,n,i,s=255,o=0){if(e<0||e>255)throw new Error(`Color ID must be between 0 and 255, got ${e}`);if(e>=240)throw new Error("Color IDs 240-255 are reserved (240-254: UI palette, 255: skip color). Use IDs 0-239 for custom colors.");if(t<0||t>255||n<0||n>255||i<0||i>255||s<0||s>255||o<0||o>255)throw new Error("Color components must be between 0 and 255");this.colorPalette.set(e,{r:t,g:n,b:i,a:s,e:o}),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}onPaletteChanged(e){this.onPaletteChangedCallback=e}getColor(e){return this.colorPalette.get(e)??null}getPalette(){return new Map(this.colorPalette)}resetPalette(){this.colorPalette.clear(),this.initializeDefaultPalette(),this.cachedLoadPackets=null,this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}loadPaletteToSlot(e,t){if(e<0||e>255)throw new Error(`Palette slot ID must be between 0 and 255, got ${e}`);let n=new Map;for(let i of t)i.colorId<0||i.colorId>255||n.set(i.colorId,{r:i.r,g:i.g,b:i.b,a:i.a??255,e:i.e??0});sh.ANSI_VGA_COLORS.forEach(i=>{n.set(i.colorId,{r:i.r,g:i.g,b:i.b,a:i.a,e:i.e})}),n.set(255,{r:0,g:0,b:0,a:0,e:0}),this.paletteSlots.set(e,n)}getPaletteFromSlot(e){return this.paletteSlots.get(e)??null}hasPaletteSlot(e){return this.paletteSlots.has(e)}clearPaletteSlot(e){this.paletteSlots.delete(e)}clearAllPaletteSlots(){this.paletteSlots.clear()}getColorCSS(e){let t=this.getColor(e);if(!t)return null;let n=t.a/255;return`rgba(${t.r}, ${t.g}, ${t.b}, ${n})`}getUserIds(){return Array.from(this.users.keys())}forEachUser(e){this.users.forEach(e)}filterUsers(e){return this.getUsers().filter(e)}findUser(e){return this.getUsers().find(e)}getCurrentTick(){return this.currentTick}getStats(){return this.stats}endTick(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,n=0;return this.users.forEach((i,s)=>{let o=i.getLayers(),a=i.getDisplays();t+=o.length,i.getStats().isEnabled()&&i.getStats().startTick(this.currentTick);let l=a.map(w=>{let g=w.getOrigin(),y=w.getSize();return{id:w.getId(),originX:g.x,originY:g.y,sizeX:y.x,sizeY:y.y,renderPasses:w.getRenderPasses()}});a.forEach(w=>w.resetChangeTracking());let u=[],c=[];o.forEach((w,g)=>{if(!w.getNeedsCommit())return;let y=w.getOrigin(),C=w.getOrders(),x=w.getMustBeReliable(),I=w.calculateUpdateFlags();w.resetChangeTracking(),w.resetCommit(),w.getId()===0&&Aa(w,g);let E={id:w.getId(),updateFlags:I,zIndex:w.getZOrder(),originX:y.x,originY:y.y,width:w.getWidth(),height:w.getHeight(),isMacroLayer:w.getIsMacroLayer(),is16bit:w.getCharCodeMode()==="16bit",orderCount:C.length,orders:C};C.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(w.getId(),x,C.length,I),x?u.push(E):c.push(E)}),n+=u.length+c.length;let d=this.audioOrderCollector.collectFromUser(i),h=this.vibrationOrderCollector.collectFromUser(i),f=this.postProcessOrderCollector.collectFromUser(i),p=i.flushMacroOrders(),m=null,S=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(s,l.length,u.length,c.length),(u.length>0||d.length>0||p.length>0)&&(m=this.encoder.encode({tick:this.currentTick,displayCount:l.length,displays:l,layerCount:u.length,layers:u,audioOrderCount:d.length,audioOrders:d,vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:p.length,macroOrders:p,postProcessOrderCount:0,postProcessOrders:[]})),S=this.encoder.encode({tick:this.currentTick,displayCount:l.length,displays:l,layerCount:c.length,layers:c,audioOrderCount:0,audioOrders:[],vibrationOrderCount:h.length,vibrationOrders:h,macroOrderCount:0,macroOrders:[],postProcessOrderCount:f.length,postProcessOrders:f}),e.set(s,{static:m,dynamic:S}),i.getStats().isEnabled()){let w=a.reduce((x,I)=>{let E=I.getSize();return x+E.x*E.y},0);i.getStats().recordDisplays(a.length,w),i.getStats().recordLayers(o.length,u.length+c.length,u.length,c.length),[...u,...c].forEach(x=>{i.getStats().recordLayerOrders(x.id,x.orders.length)});let g=(m==null?void 0:m.length)||0,y=(S==null?void 0:S.length)||0;i.getStats().recordPacketSizes(g,y);let C=i.getInputBindingRegistry();i.getStats().recordInput(!1,C.getAxisCount(),C.getButtonCount()),i.getStats().endTick()}if(i.endTickBytes(),this.stats.isEnabled()){let w=[...u,...c];w.forEach((I,E)=>{this.stats.recordLayerOrders(E,I.orders)}),a.forEach((I,E)=>{this.stats.recordDisplayLayers(E,w.length)});let g=((m==null?void 0:m.length)||0)+((S==null?void 0:S.length)||0),y=l.reduce((I,E)=>{var R;let A=Math.min(((R=E.renderPasses)==null?void 0:R.length)??0,4);return I+8+A*4},0),C=w.length*20,x=g-y-C;this.stats.recordUpdatePacketSize(g,y,C,x>0?x:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,n),this.stats.endTick()),this.currentTick++,e}getSnapshot(e){let t=this.getUser(e);if(!t)return null;let n=t.getDisplays(),i=t.getLayers(),s=n.map((a,l)=>{let u=a.getOrigin(),c=a.getSize();return{id:l,originX:u.x,originY:u.y,sizeX:c.x,sizeY:c.y,renderPasses:a.getRenderPasses()}}),o=i.map((a,l)=>{let u=a.getOrigin(),c=a.getOrders();return a.getId()===0&&Aa(a,l),{id:a.getId(),updateFlags:7,zIndex:a.getZOrder(),originX:u.x,originY:u.y,width:a.getWidth(),height:a.getHeight(),isMacroLayer:a.getIsMacroLayer(),is16bit:a.getCharCodeMode()==="16bit",orderCount:c.length,orders:c}});return this.encoder.encode({tick:this.currentTick,displayCount:s.length,displays:s,layerCount:o.length,layers:o,audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})}resetTick(){this.currentTick=0}applyUpdatePacket(e,t){let n=this.getUser(e);if(!n){if(this.strictMode)throw new Error(`Cannot apply update packet: user ${e} does not exist`);return!1}return n.applyUpdate(t),t.audioOrders&&t.audioOrders.length>0&&n.applyAudioOrders(t.audioOrders),t.vibrationOrders&&t.vibrationOrders.length>0&&n.applyVibrationOrders(t.vibrationOrders),!0}applyUpdatePacketBuffer(e,t){let n=this.updatePacketDecoder.decode(t);return this.applyUpdatePacket(e,n)?n:null}applyLoadPacket(e){try{let t=this.loadDecoder.decode(e).load;switch(t.loadType){case 1:t.slotId!==void 0?this.loadPaletteToSlot(t.slotId,t.colors):(console.warn("[Core] ColorPalette load without slotId is deprecated. Loading into slot 0."),this.loadPaletteToSlot(0,t.colors));break;case 2:this.spriteRegistry.loadUnicolorSprites(t);break;case 3:this.spriteRegistry.loadMulticolorSprites(t);break;case 5:console.warn("[Core] Sound loading not yet implemented");break;case 8:this.loadFont(t.glyphWidth,t.glyphHeight,t.atlasBlocks,t.cellWidth,t.cellHeight);break;case 9:this.loadFontBlock(t.blockIndex,t.imageData);break;case 7:{for(let n of this.users.values())n.loadMacroTemplate(t.macroId,t.template);break}default:return console.error(`[Core] Unknown LoadType: ${t.loadType}`),!1}return!0}catch(t){return console.error("[Core] Failed to apply LoadPacket:",t),!1}}generatePaletteSlotLoadPacket(e){let t=this.getPaletteFromSlot(e);if(!t||t.size===0)return null;let n=new Lc,i=[];return t.forEach((s,o)=>{o!==255&&i.push({colorId:o,r:s.r,g:s.g,b:s.b,a:s.a,e:s.e})}),n.encode({loadType:1,slotId:e,colors:i})}generateAllPaletteSlotLoadPackets(){let e=[];return this.paletteSlots.forEach((t,n)=>{let i=this.generatePaletteSlotLoadPacket(n);i&&e.push(i)}),e}generateUnicolorSpritesLoadPacket(){if(this.spriteRegistry.getUnicolorSpriteCount()===0)return null;let e=[];for(let t=0;t<=255;t++){let n=this.spriteRegistry.getUnicolorSprite(t);if(n){let i=[];for(let s=0;s<n.sizeX*n.sizeY;s++)i.push(n.data.get(s));e.push({spriteId:n.id,sizeX:n.sizeX,sizeY:n.sizeY,data:i})}}return e.length===0?null:new Lc().encode({loadType:2,sprites:e})}generateMulticolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let i=e.getMulticolorSprite(n);if(i){let s=[];for(let o=0;o<i.sizeX*i.sizeY;o++){let a=i.data.get(o);s.push({charCode:a.charCode,fgColorId:a.fgColorCode,bgColorId:a.bgColorCode})}t.push({spriteId:i.id,sizeX:i.sizeX,sizeY:i.sizeY,data:s})}}return t.length===0?null:new Lc().encode({loadType:3,sprites:t})}generateAllLoadPackets(){if(this.cachedLoadPackets)return this.cachedLoadPackets;let e=[],t=this.generateAllPaletteSlotLoadPackets();e.push(...t);let n=this.generateUnicolorSpritesLoadPacket();n&&e.push(n);let i=this.generateMulticolorSpritesLoadPacket();return i&&e.push(i),this.cachedLoadPackets=e,e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let n=t.getMacroLoads();if(n.length===0)return[];let i=new UI;return n.map(s=>i.encode(s))}generateInitialUpdatePacket(e){let t=this.getUser(e);if(!t||!t.hasPostProcessCommands())return null;let n=this.postProcessOrderCollector.collectFromUser(t);if(n.length===0)return null;let i=t.getDisplays().map(s=>{let o=s.getSize();return{id:s.getId(),originX:0,originY:0,sizeX:o.x,sizeY:o.y}});return this.encoder.encode({tick:0,displayCount:i.length,displays:i,layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:n.length,postProcessOrders:n})}applyInputBindingsLoadPacket(e,t){let n=this.getUser(e);if(!n){if(this.strictMode)throw new Error(`Cannot apply input bindings: user ${e} does not exist`);return!1}try{return n.applyInputBindingsLoadPacket(t),!0}catch(i){return console.error(`[Core] Failed to apply input bindings for user ${e}:`,i),!1}}getRenderState(e,t){let n=this.getUser(e);if(!n)return null;let i=n.getDisplays(),s=t?n.getLayers().filter(t):n.getLayers(),o=performance.now(),a=[];for(let l of i){if(!l)continue;let u=l.getOrigin(),c=l.getSize();if(a.push(this.displayRasterizer.rasterize({id:l.getId(),x:u.x,y:u.y,width:c.x,height:c.y},s,l.getRenderPasses())),this.stats.isEnabled()){let d=l.getId();this.stats.recordDisplayComposite(d,this.displayRasterizer.getLastVisibleLayerIds())}}return performance.now()-o,this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:n.id,userName:n.name,tick:this.currentTick,displays:a}}getAllRenderStates(){let e=new Map;return this.users.forEach((t,n)=>{let i=this.getRenderState(n);i&&e.set(n,i)}),e}enableStats(e){this.stats.setEnabled(e)}getStatsInstance(){return this.stats}resetStats(){this.stats.reset()}loadUnicolorSprites(e){this.spriteRegistry.loadUnicolorSprites(e)}loadMulticolorSprites(e){this.spriteRegistry.loadMulticolorSprites(e)}loadFont(e,t,n,i,s){let o={glyphWidth:e,glyphHeight:t,cellWidth:i,cellHeight:s,atlasBlocks:n};this.imageFontRegistry.hasFont(0)&&this.imageFontRegistry.unloadFont(0),this.imageFontRegistry.loadFont(0,o),this.onFontAllocatedCallback&&this.onFontAllocatedCallback()}loadFontBlock(e,t){if(typeof t=="string")return this.readResource(t).then(n=>{this.imageFontRegistry.addBlock(0,e,n),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(e),e===0&&this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0)});this.imageFontRegistry.addBlock(0,e,t),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(e),e===0&&this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0)}unloadUnicolorSprite(e){return this.spriteRegistry.unloadUnicolorSprite(e)}unloadMulticolorSprite(e){return this.spriteRegistry.unloadMulticolorSprite(e)}clearUnicolorSprites(){this.spriteRegistry.clearUnicolorSprites()}clearMulticolorSprites(){this.spriteRegistry.clearMulticolorSprites()}clearAllSprites(){this.spriteRegistry.clearAll()}getUnicolorSpriteCount(){return this.spriteRegistry.getUnicolorSpriteCount()}getMulticolorSpriteCount(){return this.spriteRegistry.getMulticolorSpriteCount()}getTotalSpriteCount(){return this.spriteRegistry.getTotalSpriteCount()}hasUnicolorSprite(e){return this.spriteRegistry.hasUnicolorSprite(e)}hasMulticolorSprite(e){return this.spriteRegistry.hasMulticolorSprite(e)}getSpriteRegistry(){return this.spriteRegistry}getSoundRegistry(){return this.soundRegistry}async loadSound(e,t){let n=this.detectSoundFormat(t),i=await this.readResource(t);return this.soundRegistry.registerFile(e,n,i)}async loadSounds(e){let t={},n=Object.entries(e).map(async([i,s])=>{let o=await this.loadSound(i,s);t[i]=o});return await Promise.all(n),t}detectSoundFormat(e){var s;let t=((s=e.split(".").pop())==null?void 0:s.toLowerCase())??"",n={mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"},i=n[t];if(!i)throw new Error(`Unsupported audio format: .${t}. Supported: ${Object.keys(n).join(", ")}`);return i}async readResource(e){let t=globalThis,n=typeof t.window<"u"||typeof t.document<"u",i=typeof t.fetch=="function",s=/^https?:\/\//i.test(e),o=e.startsWith("file:");if(n)try{let f=await fetch(e);if(!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);let p=await f.arrayBuffer();return new Uint8Array(p)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Error(`Failed to load resource "${e}": ${p}`)}if((s||o)&&i)try{let f=await fetch(e);if(!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);let p=await f.arrayBuffer();return new Uint8Array(p)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Error(`Failed to load resource "${e}": ${p}`)}let a=typeof ll<"u"?ll:null;if(!a)throw new Error("Node.js require is not available");let l="fs",u=a("path"),c=a(l),d=u.resolve(e),h=c.readFileSync(d);return new Uint8Array(h)}registerSound(e,t,n){return this.soundRegistry.registerFile(e,t,n)}registerExternalSound(e,t,n,i){return this.soundRegistry.registerExternal(e,t,n,i)}hasSound(e){return this.soundRegistry.has(e)}generateSoundLoadPackets(){return this.soundRegistry.toLoadPackets()}async loadImageFont(e,t,n){let i=await this.loadImageData(t),s=this.imageFontRegistry.registerFont(e,n);return this.imageFontRegistry.addBlock(0,0,i),this.onFontAllocatedCallback&&this.onFontAllocatedCallback(),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(0),this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0),s}async loadImageFonts(e){let t={},n=Object.entries(e).map(async([i,{path:s,options:o}])=>{let a=await this.loadImageFont(i,s,o);t[i]=a});return await Promise.all(n),t}async loadImageData(e){let t=globalThis;if(typeof t.document<"u"||typeof t.window<"u"||typeof t.fetch=="function")try{let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let i=await n.arrayBuffer();return new Uint8Array(i)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`Failed to load image font "${e}": ${i}`)}else{let n=typeof ll<"u"?ll:null;if(!n)throw new Error("Node.js require is not available");let i=n("fs").readFileSync(e);return new Uint8Array(i)}}getImageFontId(e){return this.imageFontRegistry.getFontId(e)}getImageFontByName(e){return this.imageFontRegistry.getFontByName(e)??null}onFontAllocated(e){this.onFontAllocatedCallback=e}onFontBlockAdded(e){this.onFontBlockAddedCallback=e}onImageFontChanged(e){this.onImageFontChangedCallback=e}getImageFontRegistry(){return this.imageFontRegistry}loadImageFontById(e,t){this.imageFontRegistry.loadFont(e,t),this.onImageFontChangedCallback&&this.onImageFontChangedCallback(e)}getImageFont(e){return this.imageFontRegistry.getFont(e)??null}hasImageFont(e){return this.imageFontRegistry.hasFont(e)}hasImageFontByName(e){return this.imageFontRegistry.hasFontByName(e)}unloadImageFont(e){return this.imageFontRegistry.unloadFont(e)}unloadImageFontByName(e){return this.imageFontRegistry.unloadFontByName(e)}clearImageFonts(){this.imageFontRegistry.clearFonts()}getImageFontCount(){return this.imageFontRegistry.getFontCount()}getImageFontIds(){return this.imageFontRegistry.getFontIds()}getImageFontNames(){return this.imageFontRegistry.getFontNames()}};J(ih,"Core"),O(ih,"ANSI_VGA_COLORS",[{colorId:240,r:0,g:0,b:0,a:255,e:0},{colorId:241,r:60,g:60,b:75,a:255,e:0},{colorId:242,r:160,g:160,b:180,a:255,e:0},{colorId:243,r:255,g:255,b:255,a:255,e:0},{colorId:244,r:230,g:50,b:80,a:255,e:0},{colorId:245,r:255,g:120,b:50,a:255,e:0},{colorId:246,r:255,g:210,b:60,a:255,e:0},{colorId:247,r:130,g:220,b:50,a:255,e:0},{colorId:248,r:35,g:100,b:55,a:255,e:0},{colorId:249,r:40,g:200,b:220,a:255,e:0},{colorId:250,r:60,g:120,b:240,a:255,e:0},{colorId:251,r:35,g:55,b:125,a:255,e:0},{colorId:252,r:150,g:70,b:210,a:255,e:0},{colorId:253,r:130,g:80,b:50,a:255,e:0},{colorId:254,r:240,g:210,b:170,a:255,e:0}]);var Nv=ih,Ru=new Map([[0,new Uint8Array([0,0,0,0,0,0,0,0])],[1,new Uint8Array([0,60,102,102,102,60,0,0])],[2,new Uint8Array([0,60,126,126,126,60,0,0])],[3,new Uint8Array([0,108,254,254,124,56,16,0])],[4,new Uint8Array([0,16,56,124,56,16,0,0])],[5,new Uint8Array([0,56,124,56,108,16,56,0])],[6,new Uint8Array([0,16,56,124,124,16,56,0])],[7,new Uint8Array([0,0,24,60,60,24,0,0])],[8,new Uint8Array([255,255,231,195,195,231,255,255])],[9,new Uint8Array([0,60,66,66,66,60,0,0])],[10,new Uint8Array([255,195,189,189,189,195,255,255])],[11,new Uint8Array([0,30,14,26,120,204,120,0])],[12,new Uint8Array([0,60,102,102,60,24,126,24])],[13,new Uint8Array([0,6,14,14,14,124,120,0])],[14,new Uint8Array([0,102,118,126,126,60,24,0])],[15,new Uint8Array([0,153,90,60,60,90,153,0])],[16,new Uint8Array([0,16,48,112,48,16,0,0])],[17,new Uint8Array([0,8,12,14,12,8,0,0])],[18,new Uint8Array([0,24,60,126,24,126,60,24])],[19,new Uint8Array([0,102,102,102,102,0,102,0])],[20,new Uint8Array([0,127,219,219,123,27,27,0])],[21,new Uint8Array([62,99,56,108,108,56,204,120])],[22,new Uint8Array([0,0,0,0,126,126,126,0])],[23,new Uint8Array([0,24,60,126,24,126,60,24])],[24,new Uint8Array([0,24,60,126,255,255,0,0])],[25,new Uint8Array([0,0,255,255,126,60,24,0])],[26,new Uint8Array([0,48,120,252,252,120,48,0])],[27,new Uint8Array([0,12,30,63,63,30,12,0])],[28,new Uint8Array([0,0,24,24,24,126,0,0])],[29,new Uint8Array([0,16,48,127,48,16,0,0])],[30,new Uint8Array([0,0,24,60,126,24,24,0])],[31,new Uint8Array([0,0,24,24,126,60,24,0])],[32,new Uint8Array([0,0,0,0,0,0,0,0])],[33,new Uint8Array([24,24,24,24,24,0,24,0])],[34,new Uint8Array([108,108,108,0,0,0,0,0])],[35,new Uint8Array([54,54,127,54,127,54,54,0])],[36,new Uint8Array([12,63,104,62,11,126,24,0])],[37,new Uint8Array([96,102,12,24,48,102,6,0])],[38,new Uint8Array([56,108,108,56,109,102,59,0])],[39,new Uint8Array([24,24,24,0,0,0,0,0])],[40,new Uint8Array([12,24,48,48,48,24,12,0])],[41,new Uint8Array([48,24,12,12,12,24,48,0])],[42,new Uint8Array([0,102,60,255,60,102,0,0])],[43,new Uint8Array([0,24,24,126,24,24,0,0])],[44,new Uint8Array([0,0,0,0,0,24,24,48])],[45,new Uint8Array([0,0,0,126,0,0,0,0])],[46,new Uint8Array([0,0,0,0,0,24,24,0])],[47,new Uint8Array([0,6,12,24,48,96,0,0])],[48,new Uint8Array([60,102,110,126,118,102,60,0])],[49,new Uint8Array([24,56,24,24,24,24,126,0])],[50,new Uint8Array([60,102,6,12,24,48,126,0])],[51,new Uint8Array([60,102,6,28,6,102,60,0])],[52,new Uint8Array([12,28,60,108,126,12,12,0])],[53,new Uint8Array([126,96,124,6,6,102,60,0])],[54,new Uint8Array([28,48,96,124,102,102,60,0])],[55,new Uint8Array([126,6,12,24,48,48,48,0])],[56,new Uint8Array([60,102,102,60,102,102,60,0])],[57,new Uint8Array([60,102,102,62,6,12,56,0])],[58,new Uint8Array([0,0,24,24,0,24,24,0])],[59,new Uint8Array([0,0,24,24,0,24,24,48])],[60,new Uint8Array([12,24,48,96,48,24,12,0])],[61,new Uint8Array([0,0,126,0,126,0,0,0])],[62,new Uint8Array([48,24,12,6,12,24,48,0])],[63,new Uint8Array([60,102,12,24,24,0,24,0])],[64,new Uint8Array([60,102,110,106,110,96,60,0])],[65,new Uint8Array([60,102,102,126,102,102,102,0])],[66,new Uint8Array([124,102,102,124,102,102,124,0])],[67,new Uint8Array([60,102,96,96,96,102,60,0])],[68,new Uint8Array([120,108,102,102,102,108,120,0])],[69,new Uint8Array([126,96,96,124,96,96,126,0])],[70,new Uint8Array([126,96,96,124,96,96,96,0])],[71,new Uint8Array([60,102,96,110,102,102,60,0])],[72,new Uint8Array([102,102,102,126,102,102,102,0])],[73,new Uint8Array([126,24,24,24,24,24,126,0])],[74,new Uint8Array([62,12,12,12,12,108,56,0])],[75,new Uint8Array([102,108,120,112,120,108,102,0])],[76,new Uint8Array([96,96,96,96,96,96,126,0])],[77,new Uint8Array([99,119,127,107,99,99,99,0])],[78,new Uint8Array([102,102,118,126,110,102,102,0])],[79,new Uint8Array([60,102,102,102,102,102,60,0])],[80,new Uint8Array([124,102,102,124,96,96,96,0])],[81,new Uint8Array([60,102,102,102,106,108,54,0])],[82,new Uint8Array([124,102,102,124,108,102,102,0])],[83,new Uint8Array([60,102,96,60,6,102,60,0])],[84,new Uint8Array([126,24,24,24,24,24,24,0])],[85,new Uint8Array([102,102,102,102,102,102,60,0])],[86,new Uint8Array([102,102,102,102,102,60,24,0])],[87,new Uint8Array([99,99,99,107,127,119,99,0])],[88,new Uint8Array([102,102,60,24,60,102,102,0])],[89,new Uint8Array([102,102,102,60,24,24,24,0])],[90,new Uint8Array([126,6,12,24,48,96,126,0])],[91,new Uint8Array([60,48,48,48,48,48,60,0])],[92,new Uint8Array([0,96,48,24,12,6,0,0])],[93,new Uint8Array([60,12,12,12,12,12,60,0])],[94,new Uint8Array([24,60,102,0,0,0,0,0])],[95,new Uint8Array([0,0,0,0,0,0,255,0])],[96,new Uint8Array([48,24,12,0,0,0,0,0])],[97,new Uint8Array([0,0,60,6,62,102,62,0])],[98,new Uint8Array([96,96,124,102,102,102,124,0])],[99,new Uint8Array([0,0,60,102,96,102,60,0])],[100,new Uint8Array([6,6,62,102,102,102,62,0])],[101,new Uint8Array([0,0,60,102,126,96,60,0])],[102,new Uint8Array([28,54,48,124,48,48,48,0])],[103,new Uint8Array([0,0,62,102,102,62,6,60])],[104,new Uint8Array([96,96,124,102,102,102,102,0])],[105,new Uint8Array([24,0,56,24,24,24,60,0])],[106,new Uint8Array([12,0,28,12,12,12,108,56])],[107,new Uint8Array([96,96,102,108,120,108,102,0])],[108,new Uint8Array([56,24,24,24,24,24,60,0])],[109,new Uint8Array([0,0,102,127,107,107,99,0])],[110,new Uint8Array([0,0,124,102,102,102,102,0])],[111,new Uint8Array([0,0,60,102,102,102,60,0])],[112,new Uint8Array([0,0,124,102,102,124,96,96])],[113,new Uint8Array([0,0,62,102,102,62,6,6])],[114,new Uint8Array([0,0,108,118,96,96,96,0])],[115,new Uint8Array([0,0,62,96,60,6,124,0])],[116,new Uint8Array([48,48,124,48,48,54,28,0])],[117,new Uint8Array([0,0,102,102,102,102,62,0])],[118,new Uint8Array([0,0,102,102,102,60,24,0])],[119,new Uint8Array([0,0,99,107,107,127,54,0])],[120,new Uint8Array([0,0,102,60,24,60,102,0])],[121,new Uint8Array([0,0,102,102,102,62,6,60])],[122,new Uint8Array([0,0,126,12,24,48,126,0])],[123,new Uint8Array([14,24,24,112,24,24,14,0])],[124,new Uint8Array([24,24,24,24,24,24,24,0])],[125,new Uint8Array([112,24,24,14,24,24,112,0])],[126,new Uint8Array([49,107,70,0,0,0,0,0])],[127,new Uint8Array([0,24,60,126,126,24,60,0])],[128,new Uint8Array([60,102,96,96,102,60,24,48])],[129,new Uint8Array([102,0,102,102,102,102,62,0])],[130,new Uint8Array([12,24,60,102,126,96,60,0])],[131,new Uint8Array([24,102,60,6,62,102,62,0])],[132,new Uint8Array([102,0,60,6,62,102,62,0])],[133,new Uint8Array([48,24,60,6,62,102,62,0])],[134,new Uint8Array([24,36,60,6,62,102,62,0])],[135,new Uint8Array([0,0,60,96,96,60,24,48])],[136,new Uint8Array([24,102,60,102,126,96,60,0])],[137,new Uint8Array([102,0,60,102,126,96,60,0])],[138,new Uint8Array([48,24,60,102,126,96,60,0])],[139,new Uint8Array([102,0,24,24,24,24,24,0])],[140,new Uint8Array([24,102,0,24,24,24,24,0])],[141,new Uint8Array([48,24,0,24,24,24,24,0])],[142,new Uint8Array([102,0,60,102,126,102,102,0])],[143,new Uint8Array([24,36,60,102,126,102,102,0])],[144,new Uint8Array([12,24,126,96,124,96,126,0])],[145,new Uint8Array([0,0,110,27,127,216,119,0])],[146,new Uint8Array([63,108,108,127,108,108,111,0])],[147,new Uint8Array([24,102,60,102,102,102,60,0])],[148,new Uint8Array([102,0,60,102,102,102,60,0])],[149,new Uint8Array([48,24,60,102,102,102,60,0])],[150,new Uint8Array([24,102,0,102,102,102,62,0])],[151,new Uint8Array([48,24,0,102,102,102,62,0])],[152,new Uint8Array([102,0,102,102,62,6,60,0])],[153,new Uint8Array([102,0,60,102,102,102,60,0])],[154,new Uint8Array([102,0,102,102,102,102,60,0])],[155,new Uint8Array([0,24,62,96,96,62,24,0])],[156,new Uint8Array([28,54,48,124,48,48,126,0])],[157,new Uint8Array([102,102,60,126,24,126,24,0])],[158,new Uint8Array([124,102,124,98,102,111,102,3])],[159,new Uint8Array([14,27,24,60,24,24,216,112])],[160,new Uint8Array([12,24,60,6,62,102,62,0])],[161,new Uint8Array([12,24,0,24,24,24,24,0])],[162,new Uint8Array([12,24,60,102,102,102,60,0])],[163,new Uint8Array([12,24,0,102,102,102,62,0])],[164,new Uint8Array([54,108,0,124,102,102,102,0])],[165,new Uint8Array([54,108,102,118,126,110,102,0])],[166,new Uint8Array([28,6,30,54,30,0,62,0])],[167,new Uint8Array([28,54,54,54,28,0,62,0])],[168,new Uint8Array([24,0,24,48,96,102,60,0])],[169,new Uint8Array([0,0,0,254,192,192,0,0])],[170,new Uint8Array([0,0,0,254,6,6,0,0])],[171,new Uint8Array([96,224,98,102,108,24,48,110])],[172,new Uint8Array([96,224,98,102,108,24,62,6])],[173,new Uint8Array([24,0,24,24,60,60,24,0])],[174,new Uint8Array([0,0,54,108,216,108,54,0])],[175,new Uint8Array([0,0,216,108,54,108,216,0])],[176,new Uint8Array([34,136,34,136,34,136,34,136])],[177,new Uint8Array([136,34,136,34,136,34,136,34])],[178,new Uint8Array([170,85,170,85,170,85,170,85])],[179,new Uint8Array([24,24,24,24,24,24,24,24])],[180,new Uint8Array([24,24,24,248,24,24,24,24])],[181,new Uint8Array([24,24,24,252,28,24,24,24])],[182,new Uint8Array([54,54,54,246,54,54,54,54])],[183,new Uint8Array([0,0,0,254,54,54,54,54])],[184,new Uint8Array([0,0,0,252,28,24,24,24])],[185,new Uint8Array([54,54,54,252,54,54,54,54])],[186,new Uint8Array([54,54,54,54,54,54,54,54])],[187,new Uint8Array([0,0,0,252,54,54,54,54])],[188,new Uint8Array([54,54,54,252,0,0,0,0])],[189,new Uint8Array([54,54,54,247,0,0,0,0])],[190,new Uint8Array([24,24,24,252,0,0,0,0])],[191,new Uint8Array([0,0,0,248,24,24,24,24])],[192,new Uint8Array([24,24,24,31,0,0,0,0])],[193,new Uint8Array([24,24,24,255,0,0,0,0])],[194,new Uint8Array([0,0,0,255,24,24,24,24])],[195,new Uint8Array([24,24,24,31,24,24,24,24])],[196,new Uint8Array([0,0,0,255,0,0,0,0])],[197,new Uint8Array([24,24,24,255,24,24,24,24])],[198,new Uint8Array([24,24,31,31,24,24,24,24])],[199,new Uint8Array([54,54,55,55,54,54,54,54])],[200,new Uint8Array([54,54,54,63,0,0,0,0])],[201,new Uint8Array([0,0,0,63,54,54,54,54])],[202,new Uint8Array([54,54,54,255,0,0,0,0])],[203,new Uint8Array([0,0,0,255,54,54,54,54])],[204,new Uint8Array([54,54,54,63,54,54,54,54])],[205,new Uint8Array([0,0,0,255,0,255,0,0])],[206,new Uint8Array([54,54,54,255,54,54,54,54])],[207,new Uint8Array([24,24,24,255,0,255,0,0])],[208,new Uint8Array([54,54,54,255,0,0,0,0])],[209,new Uint8Array([0,0,0,255,0,255,24,24])],[210,new Uint8Array([0,0,0,255,54,54,54,54])],[211,new Uint8Array([24,24,24,31,0,31,0,0])],[212,new Uint8Array([54,54,54,62,0,0,0,0])],[213,new Uint8Array([0,0,0,31,0,31,24,24])],[214,new Uint8Array([0,0,0,62,54,54,54,54])],[215,new Uint8Array([24,24,24,255,24,255,24,24])],[216,new Uint8Array([54,54,54,255,54,54,54,54])],[217,new Uint8Array([24,24,24,248,0,0,0,0])],[218,new Uint8Array([0,0,0,31,24,24,24,24])],[219,new Uint8Array([255,255,255,255,255,255,255,255])],[220,new Uint8Array([0,0,0,0,255,255,255,255])],[221,new Uint8Array([240,240,240,240,240,240,240,240])],[222,new Uint8Array([15,15,15,15,15,15,15,15])],[223,new Uint8Array([255,255,255,255,0,0,0,0])],[224,new Uint8Array([0,0,123,207,207,123,0,0])],[225,new Uint8Array([124,102,102,124,102,102,108,96])],[226,new Uint8Array([126,102,96,96,96,96,96,0])],[227,new Uint8Array([0,0,127,54,54,54,54,0])],[228,new Uint8Array([126,96,48,24,48,96,126,0])],[229,new Uint8Array([0,0,63,102,102,102,60,0])],[230,new Uint8Array([0,0,102,102,102,124,96,96])],[231,new Uint8Array([0,0,126,24,24,24,24,0])],[232,new Uint8Array([24,126,219,219,219,126,24,0])],[233,new Uint8Array([60,102,102,126,102,102,60,0])],[234,new Uint8Array([60,102,102,102,60,102,102,0])],[235,new Uint8Array([28,48,24,60,102,102,60,0])],[236,new Uint8Array([0,0,110,219,219,118,0,0])],[237,new Uint8Array([6,12,126,219,219,126,96,192])],[238,new Uint8Array([30,48,96,126,96,48,30,0])],[239,new Uint8Array([60,102,102,102,102,102,0,0])],[240,new Uint8Array([0,126,0,126,0,126,0,0])],[241,new Uint8Array([24,24,126,24,24,0,126,0])],[242,new Uint8Array([48,24,12,24,48,0,126,0])],[243,new Uint8Array([12,24,48,24,12,0,126,0])],[244,new Uint8Array([14,27,27,24,24,24,24,24])],[245,new Uint8Array([24,24,24,24,24,216,216,112])],[246,new Uint8Array([0,24,0,126,0,24,0,0])],[247,new Uint8Array([0,118,220,0,118,220,0,0])],[248,new Uint8Array([56,108,108,56,0,0,0,0])],[249,new Uint8Array([0,0,0,24,24,0,0,0])],[250,new Uint8Array([0,0,0,0,24,0,0,0])],[251,new Uint8Array([15,12,12,12,236,108,60,28])],[252,new Uint8Array([108,54,54,54,54,0,0,0])],[253,new Uint8Array([120,12,24,48,124,0,0,0])],[254,new Uint8Array([0,0,60,60,60,60,0,0])],[255,new Uint8Array([0,0,0,0,0,0,0,0])]]);function QI(r){return Ru.get(r)}J(QI,"getCharBitmap");function JI(r){return Ru.has(r)}J(JI,"hasChar");function ek(){return Array.from(Ru.keys()).sort((r,e)=>r-e)}J(ek,"getAllCharCodes");function tk(){return{charWidth:8,charHeight:8,glyphs:new Map(Ru)}}J(tk,"getASCII8x8FontConfig");var Vv=class{encode(e){switch(e.type){case 1:return this.encodeClick(e);case 2:return this.encodeChange(e);case 3:return this.encodeSubmit(e);case 4:return this.encodeSelect(e);default:throw new Error(`Unknown macro event type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return 2;case 2:return this.calculateChangeSize(e);case 3:return this.calculateSubmitSize(e);case 4:return 4;default:throw new Error(`Unknown macro event type: ${e.type}`)}}encodeClick(e){let t=ie.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let t=ie.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt8(1,2),t.writeUInt8(e.value?1:0,3),t.toUint8Array()}else{let t=ie.allocUnsafe(7);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt8(0,2),t.writeFloatBE(e.value,3),t.toUint8Array()}}calculateChangeSize(e){return typeof e.value=="boolean"?4:7}encodeSubmit(e){let t=new TextEncoder().encode(e.text);if(t.length>65535)throw new Error(`Submit text too large: ${t.length} bytes (max 65535)`);let n=4+t.length,i=ie.allocUnsafe(n),s=0;return i.writeUInt8(e.type,s++),i.writeUInt8(e.instanceId,s++),i.writeUInt16BE(t.length,s),s+=2,i.toUint8Array().set(t,s),i.toUint8Array()}calculateSubmitSize(e){return 4+new TextEncoder().encode(e.text).length}encodeSelect(e){let t=ie.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};J(Vv,"MacroEventEncoder");var rk=Vv;function Hv(r,e,t,n,i,s,o,a=[],l=[],u=[],c=[],d=!1){let h=Array.from(e.entries()).sort((T,_)=>T[0]-_[0]),f=Array.from(t.entries()).sort((T,_)=>T[0]-_[0]),p=h.length,m=f.length,S=sv(p,m),w=new TextEncoder,g=a.map(T=>w.encode(T)),y=1+g.reduce((T,_)=>T+1+_.length,0),C=new rk,x=l.map(T=>C.encode(T)),I=1+x.reduce((T,_)=>T+_.length,0),E=Math.min(u.length,255),A=1+E*5,R=Math.min(c.length,10),F=1+R*4,z=S+y+I+A+F,P=new Uint8Array(z),D=new DataView(P.buffer),L=0;D.setBigUint64(L,r,!0),L+=8;for(let[,T]of h){let _=nv(T);P[L]=_+256&255,L+=1}let V=Tu(m);for(let T=0;T<V;T++){let _=0;for(let j=0;j<8;j++){let G=T*8+j;if(G<m){let[,ee]=f[G];ee&&(_|=1<<j)}}P[L]=_,L+=1}P[L]=n&255,L+=1,P[L]=i&255,L+=1,P[L]=s&255,L+=1;let X=0;o&&(X|=1),d&&(X|=2),P[L]=X,L+=1,P[L]=Math.min(a.length,255),L+=1;for(let T of g)P[L]=Math.min(T.length,255),L+=1,P.set(T.slice(0,255),L),L+=T.length;P[L]=Math.min(l.length,255),L+=1;for(let T of x)P.set(T,L),L+=T.length;P[L]=E,L+=1;for(let T=0;T<E;T++){let _=u[T];P[L]=_.displayId&255,L+=1,D.setUint16(L,Math.min(_.pixelWidth,65535),!1),L+=2,D.setUint16(L,Math.min(_.pixelHeight,65535),!1),L+=2}P[L]=R,L+=1;for(let T=0;T<R;T++){let _=c[T];P[L]=_.id&15,L+=1,P[L]=_.x&255,L+=1,P[L]=_.y&255,L+=1,P[L]=_.over?1:0,L+=1}return P}J(Hv,"encodeCompressedInput");var nk=class mt{static toCharCode(e){if(typeof e=="number")return e&65535;if(e.length===0)return 0;let t=e.charCodeAt(0);return Qs(t)}static dedent(e){let t=e.split(`
|
|
53
53
|
`);if(t.length>0&&t[0].trim()===""&&t.shift(),t.length>0&&t[t.length-1].trim()===""&&t.pop(),t.length===0)return"";let n=t.filter(s=>s.trim().length>0);if(n.length===0)return"";let i=Math.min(...n.map(s=>{let o=s.match(/^(\s*)/);return o?o[1].length:0}));return t.map(s=>s.slice(i)).join(`
|
|
54
|
-
`)}static encodeString(e){let t="";for(let n=0;n<e.length;n++){let i=e.charCodeAt(n),s=Qs(i);t+=String.fromCharCode(s)}return t}static char(e,t,n,i=15,s=0){return{type:1,posX:e,posY:t,charCode:
|
|
54
|
+
`)}static encodeString(e){let t="";for(let n=0;n<e.length;n++){let i=e.charCodeAt(n),s=Qs(i);t+=String.fromCharCode(s)}return t}static char(e,t,n,i=15,s=0){return{type:1,posX:e,posY:t,charCode:mt.toCharCode(n),bgColorCode:s,fgColorCode:i}}static text(e,t,n,i=15,s=0){return{type:2,posX:e,posY:t,text:mt.encodeString(n),bgColorCode:s,fgColorCode:i}}static textMultiline(e,t,n,i=15,s=0){return{type:23,posX:e,posY:t,text:mt.encodeString(mt.dedent(n)),bgColorCode:s,fgColorCode:i}}static subFrame(e,t,n,i,s,o=15,a=0){return{type:3,posX:e,posY:t,sizeX:n,sizeY:i,frame:s.map(l=>mt.toCharCode(l)),bgColorCode:a,fgColorCode:o}}static subFrameMultiColor(e,t,n,i,s){return{type:4,posX:e,posY:t,sizeX:n,sizeY:i,frame:s.map(o=>({charCode:mt.toCharCode(o.charCode),bgColorCode:o.bgColorCode,fgColorCode:o.fgColorCode}))}}static fullFrame(e,t=15,n=0){return{type:5,frame:e.map(i=>mt.toCharCode(i)),bgColorCode:n,fgColorCode:t}}static fullFrameMultiColor(e){return{type:6,frame:e.map(t=>({charCode:mt.toCharCode(t.charCode),bgColorCode:t.bgColorCode,fgColorCode:t.fgColorCode}))}}static sprite(e,t,n,i=15,s=0){return{type:7,posX:e,posY:t,spriteIndex:n,bgColorCode:s,fgColorCode:i}}static spriteMultiColor(e,t,n){return{type:8,posX:e,posY:t,spriteIndex:n}}static colorMap(e,t,n,i,s){return{type:9,posX:e,posY:t,sizeX:n,sizeY:i,colorData:s}}static rectangle(e,t,n,i,s={}){return{type:10,shapeType:1,shapeData:{posX:e,posY:t,width:n,height:i,filled:s.filled??!0,charCode:mt.toCharCode(s.charCode??219),bgColorCode:s.bgColor??0,fgColorCode:s.fgColor??15}}}static circle(e,t,n,i={}){return{type:10,shapeType:2,shapeData:{centerX:e,centerY:t,radius:n,filled:i.filled??!0,charCode:mt.toCharCode(i.charCode??219),bgColorCode:i.bgColor??0,fgColorCode:i.fgColor??15}}}static line(e,t,n,i,s={}){return{type:10,shapeType:3,shapeData:{x1:e,y1:t,x2:n,y2:i,charCode:mt.toCharCode(s.charCode??219),bgColorCode:s.bgColor??0,fgColorCode:s.fgColor??15}}}static ellipse(e,t,n,i,s={}){return{type:10,shapeType:4,shapeData:{centerX:e,centerY:t,radiusX:n,radiusY:i,filled:s.filled??!0,charCode:mt.toCharCode(s.charCode??219),bgColorCode:s.bgColor??0,fgColorCode:s.fgColor??15}}}static triangle(e,t,n,i,s,o,a={}){return{type:10,shapeType:5,shapeData:{x1:e,y1:t,x2:n,y2:i,x3:s,y3:o,filled:a.filled??!0,charCode:mt.toCharCode(a.charCode??219),bgColorCode:a.bgColor??0,fgColorCode:a.fgColor??15}}}static dotCloud(e,t,n=15,i=0){return{type:11,charCode:mt.toCharCode(t),bgColorCode:i,fgColorCode:n,positions:e}}static dotCloudMultiColor(e){return{type:12,dots:e.map(t=>({...t,charCode:mt.toCharCode(t.charCode)}))}}static bitmask(e,t,n,i,s,o,a=15,l=0,u=!1){let c=n*i,d=Math.ceil(c/8),h=new Uint8Array(d);for(let f=0;f<c;f++)if(s[f]){let p=Math.floor(f/8),m=f%8;h[p]|=1<<m}return{type:17,posX:e,posY:t,sizeX:n,sizeY:i,charCode:mt.toCharCode(o),bgColorCode:l,fgColorCode:a,override:u,mask:h}}static bitmask4(e,t,n,i,s,o,a=!1){let l={char:"?",fgColor:15,bgColor:0},u=[o[0]??l,o[1]??l,o[2]??l],c=n*i,d=Math.ceil(c/4),h=new Uint8Array(d);for(let f=0;f<c;f++){let p=s[f]&3,m=Math.floor(f/4),S=f%4*2;h[m]|=p<<S}return{type:18,posX:e,posY:t,sizeX:n,sizeY:i,override:a,variants:[{charCode:mt.toCharCode(u[0].char),fgColorCode:u[0].fgColor,bgColorCode:u[0].bgColor},{charCode:mt.toCharCode(u[1].char),fgColorCode:u[1].fgColor,bgColorCode:u[1].bgColor},{charCode:mt.toCharCode(u[2].char),fgColorCode:u[2].fgColor,bgColorCode:u[2].bgColor}],mask:h}}static bitmask16(e,t,n,i,s,o,a=!1){let l={char:"?",fgColor:15,bgColor:0},u=[];for(let f=0;f<15;f++)u.push(o[f]??l);let c=n*i,d=Math.ceil(c/2),h=new Uint8Array(d);for(let f=0;f<c;f++){let p=s[f]&15,m=Math.floor(f/2),S=f%2*4;h[m]|=p<<S}return{type:24,posX:e,posY:t,sizeX:n,sizeY:i,override:a,variants:u.map(f=>({charCode:mt.toCharCode(f.char),fgColorCode:f.fgColor,bgColorCode:f.bgColor})),mask:h}}static spriteCloud(e,t,n=15,i=0){return{type:13,spriteIndex:e,bgColorCode:i,fgColorCode:n,positions:t}}static spriteCloudMultiColor(e,t){return{type:14,spriteIndex:e,positions:t}}static spriteCloudVaried(e){return{type:15,sprites:e}}static spriteCloudVariedMultiColor(e){return{type:16,sprites:e}}static fill(e=32,t=15,n=0){return{type:19,charCode:mt.toCharCode(e),bgColorCode:n,fgColorCode:t}}static fillChar(e,t,n,i=15,s=0){return{type:20,patternWidth:e,patternHeight:t,pattern:n.map(o=>mt.toCharCode(o)),bgColorCode:s,fgColorCode:i}}static fillSprite(e,t=15,n=0){return{type:21,spriteIndex:e,bgColorCode:n,fgColorCode:t}}static fillSpriteMultiColor(e){return{type:22,spriteIndex:e}}static boxWithBorder(e,t,n,i,s,o){return[this.rectangle(e+1,t+1,n-2,i-2,{charCode:o.charCode??219,bgColor:o.bgColor??0,fgColor:o.fgColor??8,filled:!0}),this.rectangle(e,t,n,i,{charCode:s.charCode??219,bgColor:s.bgColor??0,fgColor:s.fgColor??15,filled:!1})]}static grid(e,t,n,i,s,o,a={}){let l=[];for(let u=0;u<=s;u++)for(let c=0;c<=o;c++)l.push({posX:e+c*n,posY:t+u*i});return this.dotCloud(l,a.charCode??"+",a.fgColor??15,a.bgColor??0)}static polyline(e,t="*",n=15,i=0){return{type:25,charCode:mt.toCharCode(t),fgColorCode:n,bgColorCode:i,points:e.map(s=>({x:s.x&255,y:s.y&255}))}}static polylineFromCoords(e,t="*",n=15,i=0){let s=[];for(let o=0;o<e.length-1;o+=2)s.push({x:e[o],y:e[o+1]});return this.polyline(s,t,n,i)}static polygon(e,t="*",n=15,i=0){if(e.length<2)return this.polyline(e,t,n,i);let s=[...e,e[0]];return this.polyline(s,t,n,i)}};J(nk,"OrderBuilder");O1();var ik=(r=>(r[r.LayerEnabled=1]="LayerEnabled",r[r.SetMode=2]="SetMode",r[r.UpdatePosition=4]="UpdatePosition",r[r.UpdateZOrder=8]="UpdateZOrder",r[r.IsMacroLayer=32]="IsMacroLayer",r[r.CharCode16Bit=64]="CharCode16Bit",r[r.Disabled=0]="Disabled",r[r.EnabledAddMode=1]="EnabledAddMode",r[r.EnabledSetMode=3]="EnabledSetMode",r[r.EnabledAddMoveOnly=5]="EnabledAddMoveOnly",r[r.EnabledSetMoveOnly=7]="EnabledSetMoveOnly",r[r.EnabledAddReorderOnly=9]="EnabledAddReorderOnly",r[r.EnabledSetReorderOnly=11]="EnabledSetReorderOnly",r[r.FullUpdate=15]="FullUpdate",r))(ik||{}),Qg;(r=>{function e(d,h){return(d&h)!==0}r.hasFlag=e,J(e,"hasFlag");function t(d,h){return d|h}r.addFlag=t,J(t,"addFlag");function n(d,h){return d&~h}r.removeFlag=n,J(n,"removeFlag");function i(...d){return d.reduce((h,f)=>h|f,0)}r.combine=i,J(i,"combine");function s(d){return(d&144)===0}r.isValid=s,J(s,"isValid");function o(d){return e(d,1)}r.isEnabled=o,J(o,"isEnabled");function a(d){return e(d,2)}r.isSetMode=a,J(a,"isSetMode");function l(d){return e(d,4)}r.hasPositionChanged=l,J(l,"hasPositionChanged");function u(d){return e(d,8)}r.hasZOrderChanged=u,J(u,"hasZOrderChanged");function c(d){if(d===0)return"Disabled";let h=[];return e(d,1)?h.push("Enabled"):h.push("Disabled"),e(d,2)?h.push("SET"):h.push("ADD"),e(d,4)&&h.push("Position"),e(d,8)&&h.push("ZOrder"),e(d,32)&&h.push("Macro"),e(d,64)&&h.push("16bit"),h.join(" | ")}r.describe=c,J(c,"describe")})(Qg||(Qg={}));F1();A1();R1();var jv=Object.defineProperty,sk=(r,e,t)=>e in r?jv(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Pr=(r,e)=>jv(r,"name",{value:e,configurable:!0}),H=(r,e,t)=>(sk(r,typeof e!="symbol"?e+"":e,t),t),Yv=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff","#080808","#121212","#1c1c1c","#262626","#303030","#3a3a3a","#444444","#4e4e4e","#585858","#626262","#6c6c6c","#767676","#808080","#8a8a8a","#949494","#9e9e9e","#a80000","#00a800","#a8a800","#0000a8","#a800a8","#00a8a8","#a8a8a8","#545454","#fc5454","#54fc54","#fcfc54","#5454fc","#fc54fc","#54fcfc","#fcfcfc","#000000",...Array(192).fill("#808080")];function ok(r,e=Yv){return r<0||r>=e.length?"#ff00ff":e[r]}Pr(ok,"paletteIndexToColor");function ak(r,e=Yv){let t=e.indexOf(r.toLowerCase());return t>=0?t:0}Pr(ak,"colorToPaletteIndex");var Wv=class{constructor(e,t){H(this,"canvas"),H(this,"ctx"),H(this,"container"),H(this,"cols",0),H(this,"rows",0),H(this,"cellWidth",0),H(this,"cellHeight",0),H(this,"offsetX",0),H(this,"offsetY",0),H(this,"strokeColor","rgba(80, 80, 80, 0.4)"),H(this,"lineWidth",1),this.container=e,this.canvas=document.createElement("canvas"),this.canvas.className="grid-overlay-canvas";let n=(t==null?void 0:t.zIndex)??10;this.canvas.style.cssText=`
|
|
55
55
|
display: block !important;
|
|
56
56
|
position: absolute !important;
|
|
57
57
|
pointer-events: none !important;
|
|
@@ -252,9 +252,9 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
252
252
|
height: 100% !important;
|
|
253
253
|
pointer-events: none !important;
|
|
254
254
|
`;let n=this.canvas.getContext("2d",{alpha:!0});if(!n)throw new Error("PostProcessOverlay: Failed to get 2D context");this.ctx=n,this.containerDiv.appendChild(this.canvas),this.parentElement.appendChild(this.containerDiv),this.resizeObserver=new ResizeObserver(s=>{for(let o of s){let{width:a,height:l}=o.contentRect;a>0&&l>0&&this.handleResize(Math.floor(a),Math.floor(l))}}),this.resizeObserver.observe(this.parentElement);let i=this.parentElement.getBoundingClientRect();i.width>0&&i.height>0&&this.handleResize(Math.floor(i.width),Math.floor(i.height)),this.hide()}handleResize(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t,this.currentConfig&&this.isActive()&&this.render())}setConfig(e){let t=this.hashConfig(e);if(t!==this.configHash){if(this.currentConfig=e,this.configHash=t,!e||!this.isActiveConfig(e)){this.clear(),this.hide();return}this.show(),this.render()}}setScanlines(e){e===null?this.setConfig({scanlines:{enabled:!1}}):this.setConfig({scanlines:e})}setScanlinesEnabled(e){var t;if(e){let n=(t=this.currentConfig)==null?void 0:t.scanlines;this.setScanlines({enabled:!0,opacity:(n==null?void 0:n.opacity)??Ge.scanlines.opacity,pattern:(n==null?void 0:n.pattern)??"horizontal",spacing:(n==null?void 0:n.spacing)??2,thickness:(n==null?void 0:n.thickness)??1,color:(n==null?void 0:n.color)??{r:0,g:0,b:0}})}else this.setScanlines({enabled:!1})}setScanlinesOpacity(e){var i;let t=Math.max(0,Math.min(1,e)),n=(i=this.currentConfig)==null?void 0:i.scanlines;this.setScanlines({enabled:(n==null?void 0:n.enabled)??!0,opacity:t,pattern:(n==null?void 0:n.pattern)??"horizontal",spacing:(n==null?void 0:n.spacing)??2,thickness:(n==null?void 0:n.thickness)??1,color:(n==null?void 0:n.color)??{r:0,g:0,b:0}})}setScanlinesPattern(e){var n;let t=(n=this.currentConfig)==null?void 0:n.scanlines;this.setScanlines({enabled:(t==null?void 0:t.enabled)??!0,opacity:(t==null?void 0:t.opacity)??Ge.scanlines.opacity,pattern:e,spacing:(t==null?void 0:t.spacing)??2,thickness:(t==null?void 0:t.thickness)??1,color:(t==null?void 0:t.color)??{r:0,g:0,b:0}})}setScanlinesSpacing(e){var i;let t=Math.max(2,Math.round(e)),n=(i=this.currentConfig)==null?void 0:i.scanlines;this.setScanlines({enabled:(n==null?void 0:n.enabled)??!0,opacity:(n==null?void 0:n.opacity)??Ge.scanlines.opacity,pattern:(n==null?void 0:n.pattern)??"horizontal",spacing:t,thickness:(n==null?void 0:n.thickness)??1,color:(n==null?void 0:n.color)??{r:0,g:0,b:0}})}getConfig(){return this.currentConfig}isActive(){return this.isActiveConfig(this.currentConfig)}destroy(){this.resizeObserver.disconnect(),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}syncWithRenderer(e){}resize(e,t){}setCellDimensions(e,t){}show(){this.containerDiv.style.display="block"}hide(){this.containerDiv.style.display="none"}clear(){this.ctx.clearRect(0,0,this.width,this.height)}isActiveConfig(e){var t;return((t=e==null?void 0:e.scanlines)==null?void 0:t.enabled)??!1}render(){var e,t;this.clear(),(t=(e=this.currentConfig)==null?void 0:e.scanlines)!=null&&t.enabled&&this.renderScanlines(this.currentConfig.scanlines)}renderScanlines(e){let t=e.opacity??Ge.scanlines.opacity,n=e.pattern??"horizontal",i=e.spacing??2,s=e.thickness??1,o=e.color??{r:0,g:0,b:0},a=this.ctx;switch(a.fillStyle=`rgba(${o.r}, ${o.g}, ${o.b}, ${t})`,n){case"horizontal":for(let l=i-1;l<this.height;l+=i)a.fillRect(0,l,this.width,s);break;case"vertical":for(let l=i-1;l<this.width;l+=i)a.fillRect(l,0,s,this.height);break;case"grid":for(let l=i-1;l<this.height;l+=i)a.fillRect(0,l,this.width,s);for(let l=i-1;l<this.width;l+=i)a.fillRect(l,0,s,this.height);break}}hashConfig(e){return e?JSON.stringify(e):"null"}};Pr(Qv,"PostProcessOverlay");var Jv=Qv,_c="\x1B[0m",em="\x1B[H",dk="\x1B[2J",tm="\x1B[?25l",hk="\x1B[?25h",fk=`
|
|
255
|
-
`,pk=class{constructor(e={}){H(this,"options"),H(this,"fgCache",[]),H(this,"bgCache",[]),H(this,"lastPalette",null),this.options={optimizeColors:e.optimizeColors??!0,includeHome:e.includeHome??!0,hideCursor:e.hideCursor??!0,includeNewlines:e.includeNewlines??!0,includeReset:e.includeReset??!0}}buildColorCache(e){if(this.lastPalette!==e){this.fgCache=new Array(e.length),this.bgCache=new Array(e.length);for(let t=0;t<e.length;t++){let n=e[t];this.fgCache[t]=`\x1B[38;2;${n.r};${n.g};${n.b}m`,this.bgCache[t]=`\x1B[48;2;${n.r};${n.g};${n.b}m`}this.lastPalette=e}}render(e){let{width:t,height:n,cells:i,palette:s}=e;this.buildColorCache(s);let o="";this.options.hideCursor&&(o+=tm),this.options.includeHome&&(o+=em);let a=-1,l=-1,u=this.options.optimizeColors,c=this.options.includeNewlines;for(let d=0;d<n;d++){let h=d*t;for(let f=0;f<t;f++){let p=i[h+f],m=p.fgColorIndex,S=p.bgColorIndex;u?(S!==l&&(o+=this.bgCache[S],l=S),m!==a&&(o+=this.fgCache[m],a=m)):(o+=this.bgCache[S],o+=this.fgCache[m]),o+=p.char||" "}c&&d<n-1&&(o+=fk)}return this.options.includeReset&&(o+=_c),o}renderRow(e,t){let{width:n,cells:i,palette:s}=e;this.buildColorCache(s);let o=`\x1B[${t+1};1H`,a=-1,l=-1,u=this.options.optimizeColors,c=t*n;for(let d=0;d<n;d++){let h=i[c+d],f=h.fgColorIndex,p=h.bgColorIndex;u?(p!==l&&(o+=this.bgCache[p],l=p),f!==a&&(o+=this.fgCache[f],a=f)):(o+=this.bgCache[p],o+=this.fgCache[f]),o+=h.char||" "}return this.options.includeReset&&(o+=_c),o}clear(){return dk+em}showCursor(){return hk}hideCursor(){return tm}reset(){return _c}moveTo(e,t){return`\x1B[${e+1};${t+1}H`}};Pr(pk,"TerminalANSI");function gk(r){let e=r.startsWith("#")?r.slice(1):r,t=e.length===3?e[0]+e[0]+e[1]+e[1]+e[2]+e[2]:e,n=parseInt(t,16);return{r:n>>16&255,g:n>>8&255,b:n&255,a:255}}Pr(gk,"hexToRGB");function mk(r){let e=r.r.toString(16).padStart(2,"0"),t=r.g.toString(16).padStart(2,"0"),n=r.b.toString(16).padStart(2,"0");return`#${e}${t}${n}`}Pr(mk,"rgbToHex");function yk(r,e){let t=[{r:0,g:0,b:0,a:255},{r:128,g:0,b:0,a:255},{r:0,g:128,b:0,a:255},{r:128,g:128,b:0,a:255},{r:0,g:0,b:128,a:255},{r:128,g:0,b:128,a:255},{r:0,g:128,b:128,a:255},{r:192,g:192,b:192,a:255},{r:128,g:128,b:128,a:255},{r:255,g:0,b:0,a:255},{r:0,g:255,b:0,a:255},{r:255,g:255,b:0,a:255},{r:0,g:0,b:255,a:255},{r:255,g:0,b:255,a:255},{r:0,g:255,b:255,a:255},{r:255,g:255,b:255,a:255}];for(;t.length<256;)t.push({r:128,g:128,b:128,a:255});let n=[];for(let i=0;i<e;i++)for(let s=0;s<r;s++)n.push({char:String.fromCharCode(65+(s+i)%26),fgColorIndex:15,bgColorIndex:(s+i)%16,fgEmission:0,bgEmission:0});return{id:0,width:r,height:e,cells:n,palette:t}}Pr(yk,"createTestRenderState");var ew=Object.defineProperty,vk=(r,e,t)=>e in r?ew(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wr=(r,e)=>ew(r,"name",{value:e,configurable:!0}),ke=(r,e,t)=>(vk(r,typeof e!="symbol"?e+"":e,t),t),wk=(r=>(r.KeyDown="keydown",r.KeyUp="keyup",r.MouseDown="mousedown",r.MouseUp="mouseup",r.MouseMove="mousemove",r.MouseWheel="mousewheel",r.TouchStart="touchstart",r.TouchEnd="touchend",r.TouchMove="touchmove",r.GamepadConnected="gamepadconnected",r.GamepadDisconnected="gamepaddisconnected",r.GamepadButton="gamepadbutton",r.GamepadAxis="gamepadaxis",r))(wk||{}),tw=class{constructor(e=window,t={}){ke(this,"isActive",!1),ke(this,"targetElement"),ke(this,"config"),ke(this,"callbacks",{}),this.targetElement=e,this.config={enabled:!0,preventDefault:!1,stopPropagation:!1,debug:!1,...t}}isListening(){return this.isActive}destroy(){this.stop(),this.clearCallbacks()}setCallbacks(e){typeof e=="object"&&e!==null&&Object.assign(this.callbacks,e)}clearCallbacks(){this.callbacks={}}getTargetElement(){return this.targetElement}enable(){this.config.enabled=!0,this.isActive||this.start()}disable(){this.config.enabled=!1,this.isActive&&this.stop()}isEnabled(){return this.config.enabled??!0}emit(e,...t){this.callbacks[e]&&this.callbacks[e].forEach(n=>{try{n(...t)}catch(i){this.config.debug&&console.error(`Error in ${e} callback:`,i)}})}log(...e){}};wr(tw,"BaseInputs");var Fa=tw;function Ck(r){return typeof r=="object"&&r!==null&&"start"in r&&"stop"in r&&"reset"in r&&"isListening"in r&&"destroy"in r}wr(Ck,"isInputs");var rw=class extends Fa{constructor(e=window,t={}){super(e,t),ke(this,"keys",{}),ke(this,"keyboardCallbacks",{}),ke(this,"textInputsThisFrame",[]),ke(this,"boundHandlers"),this.boundHandlers={keyDown:this.handleKeyDown.bind(this),keyUp:this.handleKeyUp.bind(this)}}start(){this.isActive||(this.targetElement.addEventListener("keydown",this.boundHandlers.keyDown),this.targetElement.addEventListener("keyup",this.boundHandlers.keyUp),this.isActive=!0)}stop(){this.isActive&&(this.targetElement.removeEventListener("keydown",this.boundHandlers.keyDown),this.targetElement.removeEventListener("keyup",this.boundHandlers.keyUp),this.isActive=!1)}reset(){this.keys={}}resetDelta(){}poll(){for(let e in this.keys)this.keys[e].justPressed=!1,this.keys[e].justReleased=!1;this.textInputsThisFrame=[]}getTextInputs(){return this.textInputsThisFrame}isKeyPressed(e){var t;return((t=this.keys[e])==null?void 0:t.pressed)||!1}isKeyJustPressed(e){var t;return((t=this.keys[e])==null?void 0:t.justPressed)||!1}isKeyJustReleased(e){var t;return((t=this.keys[e])==null?void 0:t.justReleased)||!1}getKeysPressed(){return Object.keys(this.keys).filter(e=>this.keys[e].pressed)}getKeysJustPressed(){return Object.keys(this.keys).filter(e=>this.keys[e].justPressed)}getKeysJustReleased(){return Object.keys(this.keys).filter(e=>this.keys[e].justReleased)}isAnyKeyPressed(){return Object.values(this.keys).some(e=>e.pressed)}setKeyboardCallbacks(e){this.keyboardCallbacks={...this.keyboardCallbacks,...e}}clearKeyboardCallbacks(){this.keyboardCallbacks={}}setCallbacks(e){this.isKeyboardCallbacks(e)&&this.setKeyboardCallbacks(e)}isKeyboardCallbacks(e){return typeof e=="object"&&e!==null&&("onKeyDown"in e||"onKeyUp"in e)}shouldAllowDefault(e,t){let n=/^F([1-9]|1[0-2])$/.test(e),i=(t.ctrlKey||t.metaKey)&&(e==="KeyT"||e==="KeyW"||e==="KeyR"||e==="KeyN"||e==="Tab");return n||i}handleKeyDown(e){var t,n;try{let i=e.code,s=this.shouldAllowDefault(i,e);this.config.preventDefault&&!s&&e.preventDefault(),this.config.stopPropagation&&!s&&e.stopPropagation(),this.keys[i]||(this.keys[i]={pressed:!1,justPressed:!1,justReleased:!1}),this.keys[i].pressed||(this.keys[i].justPressed=!0,(n=(t=this.keyboardCallbacks).onKeyDown)==null||n.call(t,i,e)),this.keys[i].pressed=!0,this.keys[i].justReleased=!1;let o=e.key;o.length===1&&!e.ctrlKey&&!e.metaKey&&this.textInputsThisFrame.push(o)}catch(i){console.error("Error in keyboard keydown handler:",i)}}handleKeyUp(e){var t,n;try{let i=e.code,s=this.shouldAllowDefault(i,e);this.config.preventDefault&&!s&&e.preventDefault(),this.config.stopPropagation&&!s&&e.stopPropagation(),this.keys[i]||(this.keys[i]={pressed:!1,justPressed:!1,justReleased:!1}),this.keys[i].pressed&&(this.keys[i].justReleased=!0,(n=(t=this.keyboardCallbacks).onKeyUp)==null||n.call(t,i,e)),this.keys[i].pressed=!1,this.keys[i].justPressed=!1}catch(i){console.error("Error in keyboard keyup handler:",i)}}};wr(rw,"KeyboardInputs");var nw=rw;function bk(r,e){let t=new nw(r);return e&&t.setCallbacks(e),t.start(),t}wr(bk,"useKeyboardInputs");var oh=class iw extends Fa{constructor(e=window,t={}){super(e,t),ke(this,"mouseButtons",{left:{pressed:!1,justPressed:!1,justReleased:!1},middle:{pressed:!1,justPressed:!1,justReleased:!1},right:{pressed:!1,justPressed:!1,justReleased:!1}}),ke(this,"mousePosition",Yt.zero()),ke(this,"mouseDelta",Yt.zero()),ke(this,"wheelDelta",0),ke(this,"mouseCallbacks",{}),ke(this,"boundHandlers"),this.boundHandlers={mouseDown:this.handleMouseDown.bind(this),mouseUp:this.handleMouseUp.bind(this),mouseMove:this.handleMouseMove.bind(this),wheel:this.handleWheel.bind(this),mouseEnter:this.handleMouseEnter.bind(this),mouseLeave:this.handleMouseLeave.bind(this),contextMenu:this.handleContextMenu.bind(this)}}start(){this.isActive||(this.targetElement.addEventListener("mousedown",this.boundHandlers.mouseDown),this.targetElement.addEventListener("mouseup",this.boundHandlers.mouseUp),this.targetElement.addEventListener("mousemove",this.boundHandlers.mouseMove),this.targetElement.addEventListener("wheel",this.boundHandlers.wheel),this.targetElement.addEventListener("mouseenter",this.boundHandlers.mouseEnter),this.targetElement.addEventListener("mouseleave",this.boundHandlers.mouseLeave),this.targetElement.addEventListener("contextmenu",this.boundHandlers.contextMenu),this.isActive=!0)}stop(){this.isActive&&(this.targetElement.removeEventListener("mousedown",this.boundHandlers.mouseDown),this.targetElement.removeEventListener("mouseup",this.boundHandlers.mouseUp),this.targetElement.removeEventListener("mousemove",this.boundHandlers.mouseMove),this.targetElement.removeEventListener("wheel",this.boundHandlers.wheel),this.targetElement.removeEventListener("mouseenter",this.boundHandlers.mouseEnter),this.targetElement.removeEventListener("mouseleave",this.boundHandlers.mouseLeave),this.targetElement.removeEventListener("contextmenu",this.boundHandlers.contextMenu),this.isActive=!1)}reset(){this.mouseButtons={left:{pressed:!1,justPressed:!1,justReleased:!1},middle:{pressed:!1,justPressed:!1,justReleased:!1},right:{pressed:!1,justPressed:!1,justReleased:!1}},this.mousePosition=Yt.zero(),this.mouseDelta=Yt.zero(),this.wheelDelta=0}poll(){this.mouseButtons.left.justPressed=!1,this.mouseButtons.left.justReleased=!1,this.mouseButtons.middle.justPressed=!1,this.mouseButtons.middle.justReleased=!1,this.mouseButtons.right.justPressed=!1,this.mouseButtons.right.justReleased=!1,this.resetDelta()}resetDelta(){this.mouseDelta=Yt.zero(),this.wheelDelta=0}isLeftMousePressed(){return this.mouseButtons.left.pressed}isLeftMouseJustPressed(){return this.mouseButtons.left.justPressed}isLeftMouseJustReleased(){return this.mouseButtons.left.justReleased}isRightMousePressed(){return this.mouseButtons.right.pressed}isRightMouseJustPressed(){return this.mouseButtons.right.justPressed}isRightMouseJustReleased(){return this.mouseButtons.right.justReleased}isMiddleMousePressed(){return this.mouseButtons.middle.pressed}isMiddleMouseJustPressed(){return this.mouseButtons.middle.justPressed}isMiddleMouseJustReleased(){return this.mouseButtons.middle.justReleased}getMousePosition(){return this.mousePosition.clone()}getMouseDelta(){return this.mouseDelta.clone()}getWheelDelta(){return this.wheelDelta}setMouseCallbacks(e){this.mouseCallbacks={...this.mouseCallbacks,...e}}clearMouseCallbacks(){this.mouseCallbacks={}}setCallbacks(e){this.isMouseCallbacks(e)&&this.setMouseCallbacks(e)}isMouseCallbacks(e){return typeof e=="object"&&e!==null&&("onMouseDown"in e||"onMouseUp"in e||"onMouseMove"in e||"onMouseWheel"in e||"onMouseEnter"in e||"onMouseLeave"in e)}getButtonByIndex(e){let t=iw.BUTTON_NAMES[e];return t?{state:this.mouseButtons[t],name:t}:null}handleMouseDown(e){var t,n;try{this.shouldPreventDefault(e)&&this.config.preventDefault&&e.preventDefault(),this.config.stopPropagation&&e.stopPropagation();let i=this.getButtonByIndex(e.button);i&&(i.state.pressed||(i.state.justPressed=!0),i.state.pressed=!0,i.state.justReleased=!1,(n=(t=this.mouseCallbacks).onMouseDown)==null||n.call(t,i.name,this.mousePosition,e))}catch(i){console.error("Error in mouse down handler:",i)}}handleMouseUp(e){var t,n;try{this.shouldPreventDefault(e)&&this.config.preventDefault&&e.preventDefault(),this.config.stopPropagation&&e.stopPropagation();let i=this.getButtonByIndex(e.button);i&&(i.state.pressed&&(i.state.justReleased=!0),i.state.pressed=!1,i.state.justPressed=!1,(n=(t=this.mouseCallbacks).onMouseUp)==null||n.call(t,i.name,this.mousePosition,e))}catch(i){console.error("Error in mouse up handler:",i)}}handleMouseMove(e){var t,n;try{this.shouldPreventDefault(e)&&this.config.preventDefault&&e.preventDefault(),this.config.stopPropagation&&e.stopPropagation();let i=new Yt(e.clientX,e.clientY);this.mouseDelta=i.subtract(this.mousePosition),this.mousePosition=i,(n=(t=this.mouseCallbacks).onMouseMove)==null||n.call(t,this.mousePosition,this.mouseDelta,e)}catch(i){console.error("Error in mouse move handler:",i)}}handleWheel(e){var t,n;try{this.shouldPreventDefault(e)&&this.config.preventDefault&&e.preventDefault(),this.config.stopPropagation&&e.stopPropagation(),this.wheelDelta=e.deltaY,(n=(t=this.mouseCallbacks).onMouseWheel)==null||n.call(t,this.wheelDelta,e)}catch(i){console.error("Error in mouse wheel handler:",i)}}handleMouseEnter(e){var t,n;try{(n=(t=this.mouseCallbacks).onMouseEnter)==null||n.call(t,e)}catch(i){console.error("Error in mouse enter handler:",i)}}handleMouseLeave(e){var t,n;try{(n=(t=this.mouseCallbacks).onMouseLeave)==null||n.call(t,e)}catch(i){console.error("Error in mouse leave handler:",i)}}handleContextMenu(e){try{this.isInteractiveSurfaceEvent(e)&&e.preventDefault(),this.config.stopPropagation&&e.stopPropagation()}catch(t){console.error("Error in context menu handler:",t)}}shouldPreventDefault(e){return this.isInteractiveSurfaceEvent(e)}isInteractiveSurfaceEvent(e){var n,i;let t=e.target;return t?(t.tagName??"").toLowerCase()==="canvas"||(((n=t.getAttribute)==null?void 0:n.call(t,"data-utsp-input-surface"))??"").toLowerCase()==="true"?!0:!!((i=t.closest)!=null&&i.call(t,'canvas,[data-utsp-input-surface="true"]')):!1}};wr(oh,"MouseInputs"),ke(oh,"BUTTON_NAMES",["left","middle","right"]);var sw=oh;function Sk(r,e){let t=new sw(r);return e&&t.setCallbacks(e),t.start(),t}wr(Sk,"useMouseInputs");var ow=class extends Fa{constructor(e=window,t={}){super(e,t),ke(this,"touches",new Map),ke(this,"nativeToInternal",new Map),ke(this,"mobileCallbacks",{}),ke(this,"mobileConfig"),ke(this,"maxTouches",10),ke(this,"lastLogTime",0),ke(this,"boundHandlers"),this.mobileConfig={targetElement:e,preventDefault:t.preventDefault??!1,passive:t.passive??!0,maxTouches:t.maxTouches??10,enabled:t.enabled??!0,debug:t.debug??!1,stopPropagation:t.stopPropagation??!1},this.maxTouches=this.mobileConfig.maxTouches,this.mobileConfig.preventDefault&&this.mobileConfig.passive&&(console.warn("[MobileInputs] passive=true prevents preventDefault() from working! Setting passive=false."),this.mobileConfig.passive=!1),this.boundHandlers={touchStart:this.handleTouchStart.bind(this),touchEnd:this.handleTouchEnd.bind(this),touchMove:this.handleTouchMove.bind(this),touchCancel:this.handleTouchCancel.bind(this),orientationChange:this.handleOrientationChange.bind(this)}}start(){if(this.isActive)return;let e={passive:!this.mobileConfig.preventDefault&&this.mobileConfig.passive};this.targetElement.addEventListener("touchstart",this.boundHandlers.touchStart,e),this.targetElement.addEventListener("touchend",this.boundHandlers.touchEnd,e),this.targetElement.addEventListener("touchmove",this.boundHandlers.touchMove,e),this.targetElement.addEventListener("touchcancel",this.boundHandlers.touchCancel,e),window.addEventListener("orientationchange",this.boundHandlers.orientationChange),this.isActive=!0}stop(){this.isActive&&(this.targetElement.removeEventListener("touchstart",this.boundHandlers.touchStart),this.targetElement.removeEventListener("touchend",this.boundHandlers.touchEnd),this.targetElement.removeEventListener("touchmove",this.boundHandlers.touchMove),this.targetElement.removeEventListener("touchcancel",this.boundHandlers.touchCancel),window.removeEventListener("orientationchange",this.boundHandlers.orientationChange),this.isActive=!1)}reset(){this.touches.clear(),this.nativeToInternal.clear()}resetDelta(){}poll(){let e=[];for(let[t,n]of this.touches.entries())n.justReleased&&(e.push(t),this.nativeToInternal.delete(n.nativeId)),n.justTouched=!1,n.justReleased=!1;for(let t of e)this.touches.delete(t)}isTouchActive(e){if(e<0||e>=this.maxTouches)return!1;let t=this.touches.get(e);return t?t.active:!1}getTouchPosition(e){if(e<0||e>=this.maxTouches)return null;let t=this.touches.get(e);return t?t.position.clone():null}getTouchStartPosition(e){if(e<0||e>=this.maxTouches)return null;let t=this.touches.get(e);return t?t.startPosition.clone():null}getTouchDelta(e){if(e<0||e>=this.maxTouches)return null;let t=this.touches.get(e);return t?t.position.subtract(t.startPosition):null}getTouchCount(){let e=0;for(let t of this.touches.values())t.active&&e++;return e}isTouchJustStarted(e){if(e<0||e>=this.maxTouches)return!1;let t=this.touches.get(e);return t?t.justTouched:!1}isTouchJustReleased(e){if(e<0||e>=this.maxTouches)return!1;let t=this.touches.get(e);return t?t.justReleased:!1}isAnyTouchJustStarted(){for(let e of this.touches.values())if(e.justTouched)return!0;return!1}isAnyTouchJustReleased(){for(let e of this.touches.values())if(e.justReleased)return!0;return!1}getJustReleasedTouches(){return Array.from(this.touches.values()).filter(e=>e.justReleased)}getAllTouches(){return Array.from(this.touches.values()).filter(e=>e.active)}setMobileCallbacks(e){this.mobileCallbacks={...this.mobileCallbacks,...e}}clearMobileCallbacks(){this.mobileCallbacks={}}setCallbacks(e){this.isMobileCallbacks(e)&&this.setMobileCallbacks(e)}isMobileCallbacks(e){return typeof e=="object"&&e!==null&&("onTouchStart"in e||"onTouchEnd"in e||"onTouchMove"in e||"onTouchCancel"in e||"onOrientationChange"in e)}handleTouchStart(e){var t,n;try{this.mobileConfig.preventDefault&&e.preventDefault();let i=Array.from(e.changedTouches),s=[];for(let o of i){if(this.touches.size>=this.maxTouches)break;let a=this.nativeToInternal.get(o.identifier);if(a!==void 0){let d=this.touches.get(a);if(d){let h=new Yt(o.clientX,o.clientY);d.position=h.clone(),d.startPosition=h.clone(),d.active=!0,d.justTouched=!0,d.justReleased=!1,s.push({...d})}continue}let l=-1;for(let d=0;d<this.maxTouches;d++)if(!this.touches.has(d)){l=d;break}if(l===-1)continue;let u=new Yt(o.clientX,o.clientY),c={id:l,nativeId:o.identifier,position:u.clone(),startPosition:u.clone(),active:!0,justTouched:!0,justReleased:!1};this.touches.set(l,c),this.nativeToInternal.set(o.identifier,l),s.push(c),console.warn(`👆 Touch START - ID: ${l}`)}(n=(t=this.mobileCallbacks).onTouchStart)==null||n.call(t,s,e)}catch(i){console.error("Error in touch start handler:",i)}}handleTouchEnd(e){var t,n;try{this.mobileConfig.preventDefault&&e.preventDefault();let i=Array.from(e.changedTouches),s=[];for(let o of i){let a=this.nativeToInternal.get(o.identifier);if(a!==void 0){let l=this.touches.get(a);l&&(l.justReleased=!0,l.justTouched=!1,l.active=!1,s.push({...l}),console.warn(`👇 Touch END - ID: ${a}`))}}(n=(t=this.mobileCallbacks).onTouchEnd)==null||n.call(t,s,e)}catch(i){console.error("Error in touch end handler:",i)}}handleTouchMove(e){var t,n;try{let i=Array.from(e.changedTouches);this.mobileConfig.debug&&(!this.lastLogTime||Date.now()-this.lastLogTime>200)&&(console.warn(`🔄 TouchMove event - ${i.length} touches changed`),this.lastLogTime=Date.now());for(let s of i){let o=this.nativeToInternal.get(s.identifier);if(o!==void 0){let a=this.touches.get(o);if(a){let l=a.position.clone();a.position=new Yt(s.clientX,s.clientY),this.mobileConfig.debug&&(!this.lastLogTime||Date.now()-this.lastLogTime>200)&&console.warn(`🔄 Updated touch ${a.id} (native ${s.identifier}) - ${l.x.toFixed(1)},${l.y.toFixed(1)} → ${s.clientX.toFixed(1)},${s.clientY.toFixed(1)}`)}}else this.mobileConfig.debug&&console.warn(`⚠️ Touch move for unknown native ID ${s.identifier}`)}(n=(t=this.mobileCallbacks).onTouchMove)==null||n.call(t,this.getAllTouches(),e)}catch(i){console.error("Error in touch move handler:",i)}}handleTouchCancel(e){var t,n;try{this.mobileConfig.preventDefault&&e.preventDefault();let i=[],s=Array.from(e.changedTouches);for(let o of s){let a=this.nativeToInternal.get(o.identifier);if(a!==void 0){let l=this.touches.get(a);l&&(l.justReleased=!0,l.justTouched=!1,l.active=!1,i.push({...l}),this.mobileConfig.debug&&console.warn(`❌ Touch CANCEL - ID: ${a}, nativeId: ${o.identifier}`))}}(n=(t=this.mobileCallbacks).onTouchCancel)==null||n.call(t,i,e)}catch(i){console.error("Error in touch cancel handler:",i)}}handleOrientationChange(e){var t,n;try{let i=(window.screen.orientation&&window.screen.orientation.angle)??window.orientation??0;(n=(t=this.mobileCallbacks).onOrientationChange)==null||n.call(t,i)}catch(i){console.error("Error in orientation change handler:",i)}}};wr(ow,"MobileInputs");var ah=ow;function xk(r,e,t){console.warn("[MobileInputs] useMobileInputs() is deprecated and causes memory leaks. Use useMemo + useEffect instead.");let n=new ah(r,t);return e&&n.setCallbacks(e),n.start(),n}wr(xk,"useMobileInputs");var aw=class extends Fa{constructor(e,t){super(t.targetElement,t),this.mobile=e,ke(this,"zones",[]),ke(this,"zoneState",new Map),ke(this,"gridWidth"),ke(this,"gridHeight"),ke(this,"rendererOffsets"),this.gridWidth=t.gridWidth,this.gridHeight=t.gridHeight,this.rendererOffsets=t.rendererOffsets??{offsetX:0,offsetY:0},t.zones&&this.setZones(t.zones)}start(){this.isActive=!0}stop(){this.isActive=!1}reset(){this.clearZones()}resetDelta(){}setLayout(e,t,n){this.gridWidth=e,this.gridHeight=t,n&&(this.rendererOffsets=n)}setZones(e){this.zones=e.filter(t=>t.id>=0&&t.id<=31),this.zoneState.clear();for(let t of this.zones)this.zoneState.set(t.id,{pressed:!1,justPressed:!1,justReleased:!1,lastX:t.x,lastY:t.y})}clearZones(){this.zones=[],this.zoneState.clear()}updateFromTouches(){if(this.zones.length===0)return;let e=this.targetElement,t=e.getBoundingClientRect(),{renderWidth:n,renderHeight:i,offsetX:s,offsetY:o}=this.calculateRenderMetrics(e,t),a=n/this.gridWidth,l=i/this.gridHeight,u=new Map,c=new Map,d=this.mobile.getAllTouches();for(let h of d){let f=h.position.x-t.left-s,p=h.position.y-t.top-o,m=Math.floor(f/a),S=Math.floor(p/l);for(let w of this.zones)this.isInsideZone(m,S,w)&&(u.set(w.id,(u.get(w.id)??0)+1),c.set(w.id,{x:Math.max(w.x,Math.min(w.x+w.width-1,m)),y:Math.max(w.y,Math.min(w.y+w.height-1,S))}))}for(let h of this.zones){let f=this.zoneState.get(h.id)??{pressed:!1,justPressed:!1,justReleased:!1,lastX:h.x,lastY:h.y},p=(u.get(h.id)??0)>0;p&&!f.pressed&&(f.justPressed=!0),!p&&f.pressed&&(f.justReleased=!0),f.pressed=p;let m=c.get(h.id);m&&(f.lastX=m.x,f.lastY=m.y),this.zoneState.set(h.id,f)}}poll(){for(let e of this.zoneState.values())e.justPressed=!1,e.justReleased=!1}isZonePressed(e){var t;return((t=this.zoneState.get(e))==null?void 0:t.pressed)??!1}isZoneJustPressed(e){var t;return((t=this.zoneState.get(e))==null?void 0:t.justPressed)??!1}isZoneJustReleased(e){var t;return((t=this.zoneState.get(e))==null?void 0:t.justReleased)??!1}getZoneAxis(e,t){let n=this.zoneState.get(e);if(!n||!n.pressed)return 0;let i=this.zones.find(s=>s.id===e);if(!i)return 0;if(t==="x"){let s=(i.width-1)/2,o=i.x+s;return s>0?(n.lastX-o)/s:0}else{let s=(i.height-1)/2,o=i.y+s;return s>0?(n.lastY-o)/s:0}}getZonePosition(e){let t=this.zoneState.get(e);return t?{x:t.lastX,y:t.lastY}:null}calculateRenderMetrics(e,t){let n=e.width,i=e.height,s=n/i,o=t.width/t.height,a,l,u,c;s>o?(a=t.width,l=t.width/s,u=0,c=(t.height-l)/2):(a=t.height*s,l=t.height,u=(t.width-a)/2,c=0);let d=this.rendererOffsets;return u+=d.offsetX,c+=d.offsetY,a-=d.offsetX*2,l-=d.offsetY*2,{renderWidth:a,renderHeight:l,offsetX:u,offsetY:c}}isInsideZone(e,t,n){return e>=n.x&&e<n.x+n.width&&t>=n.y&&t<n.y+n.height}};wr(aw,"TouchZoneInputs");var rm=aw,wn={tap:10,mediumTap:25,heavyTap:50,success:[30,50,30],error:[50,30,50,30,50],warning:[100],selection:5,impactLight:15,impactMedium:30,impactHeavy:50,notification:[100,100,100,100,100]},lw=class{constructor(e={}){ke(this,"config"),ke(this,"supported",!1),ke(this,"userActivated",!1),this.config={enabled:e.enabled??!0,debug:e.debug??!1,intensity:Math.max(0,Math.min(1,e.intensity??1))},this.supported=typeof navigator<"u"&&"vibrate"in navigator,this.config.debug&&console.log(`[MobileVibration] Vibration API supported: ${this.supported}`)}isSupported(){return this.supported}isEnabled(){return this.config.enabled&&this.supported}setEnabled(e){this.config.enabled=e,this.config.debug&&console.log(`[MobileVibration] Enabled: ${e}`)}setIntensity(e){this.config.intensity=Math.max(0,Math.min(1,e)),this.config.debug&&console.log(`[MobileVibration] Intensity set to: ${this.config.intensity}`)}getIntensity(){return this.config.intensity}vibrate(e){if(!this.isEnabled())return!1;try{let t=this.scalePattern(e),n=typeof t=="number"?t:[...t],i=navigator.vibrate(n);return this.config.debug&&console.log(`[MobileVibration] Vibrate: ${JSON.stringify(t)} -> ${i}`),i&&(this.userActivated=!0),i}catch(t){return this.config.debug&&console.error("[MobileVibration] Vibration failed:",t),!1}}cancel(){this.supported&&(navigator.vibrate(0),this.config.debug&&console.log("[MobileVibration] Vibration cancelled"))}hasUserActivation(){return this.userActivated}tap(){return this.vibrate(wn.tap)}mediumTap(){return this.vibrate(wn.mediumTap)}heavyTap(){return this.vibrate(wn.heavyTap)}success(){return this.vibrate(wn.success)}error(){return this.vibrate(wn.error)}warning(){return this.vibrate(wn.warning)}selection(){return this.vibrate(wn.selection)}impactLight(){return this.vibrate(wn.impactLight)}impactMedium(){return this.vibrate(wn.impactMedium)}impactHeavy(){return this.vibrate(wn.impactHeavy)}notification(){return this.vibrate(wn.notification)}scalePattern(e){return this.config.intensity===1?e:typeof e=="number"?Math.round(e*this.config.intensity):e.map((t,n)=>n%2===0?Math.round(t*this.config.intensity):t)}};wr(lw,"MobileVibration");var Uf=lw,$c=null;function Ik(){return $c||($c=new Uf),$c}wr(Ik,"getMobileVibration");var kk=.01,uw=class extends Fa{constructor(e={}){super(window,e),ke(this,"gamepads",new Map),ke(this,"previousGamepads",new Map),ke(this,"gamepadCallbacks",{}),ke(this,"gamepadConfig"),ke(this,"pollingIntervalId",null),ke(this,"rafId",null),ke(this,"boundHandlers"),ke(this,"vibrationPresets",{tap:{duration:50,strongMagnitude:.3,weakMagnitude:.5},impact:{duration:100,strongMagnitude:.7,weakMagnitude:.3},heavy:{duration:200,strongMagnitude:1,weakMagnitude:.2},success:{duration:150,strongMagnitude:.4,weakMagnitude:.6},error:{duration:300,strongMagnitude:.8,weakMagnitude:.4},explosion:{duration:400,strongMagnitude:1,weakMagnitude:.8},engine:{duration:1e3,strongMagnitude:.5,weakMagnitude:.2},heartbeat:{duration:100,strongMagnitude:.6,weakMagnitude:.1}}),this.gamepadConfig={targetElement:window,maxGamepads:e.maxGamepads??4,axisDeadzone:e.axisDeadzone??.1,pollingInterval:e.pollingInterval??16,autoPolling:e.autoPolling??!0,enabled:e.enabled??!0,debug:e.debug??!1,preventDefault:e.preventDefault??!1,stopPropagation:e.stopPropagation??!1},this.boundHandlers={connected:this.handleGamepadConnected.bind(this),disconnected:this.handleGamepadDisconnected.bind(this)}}start(){this.isActive||(window.addEventListener("gamepadconnected",this.boundHandlers.connected),window.addEventListener("gamepaddisconnected",this.boundHandlers.disconnected),this.gamepadConfig.autoPolling&&this.startPolling(),this.isActive=!0,this.log("GamepadInputs started"))}stop(){this.isActive&&(window.removeEventListener("gamepadconnected",this.boundHandlers.connected),window.removeEventListener("gamepaddisconnected",this.boundHandlers.disconnected),this.stopPolling(),this.isActive=!1,this.log("GamepadInputs stopped"))}reset(){this.gamepads.clear(),this.previousGamepads.clear()}resetDelta(){this.previousGamepads.clear(),this.gamepads.forEach((e,t)=>{this.previousGamepads.set(t,this.cloneGamepadState(e))})}startPolling(){if(this.pollingIntervalId!==null||this.rafId!==null)return;let e=wr(()=>{this.poll(),this.rafId=requestAnimationFrame(e)},"poll");this.rafId=requestAnimationFrame(e),this.log("Polling started")}stopPolling(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.pollingIntervalId!==null&&(clearInterval(this.pollingIntervalId),this.pollingIntervalId=null),this.log("Polling stopped")}poll(){let e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t<e.length&&t<this.gamepadConfig.maxGamepads;t++){let n=e[t];n&&this.updateGamepadState(n)}}getConnectedGamepadCount(){return this.gamepads.size}isGamepadConnected(e){return this.gamepads.has(e)&&this.gamepads.get(e).connected}getGamepadState(e){return this.gamepads.get(e)||null}getAllGamepads(){return Array.from(this.gamepads.values()).filter(e=>e.connected)}isButtonPressed(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid gamepadIndex: ${e}. Must be a non-negative integer.`);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid buttonIndex: ${t}. Must be a non-negative integer.`);let n=this.gamepads.get(e);return!n||!n.connected||t>=n.buttons.length?!1:n.buttons[t].pressed}isButtonJustPressed(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid gamepadIndex: ${e}. Must be a non-negative integer.`);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid buttonIndex: ${t}. Must be a non-negative integer.`);let n=this.gamepads.get(e);return!n||!n.connected||t>=n.buttons.length?!1:n.buttons[t].justPressed}isButtonJustReleased(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid gamepadIndex: ${e}. Must be a non-negative integer.`);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid buttonIndex: ${t}. Must be a non-negative integer.`);let n=this.gamepads.get(e);return!n||!n.connected||t>=n.buttons.length?!1:n.buttons[t].justReleased}getButtonValue(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid gamepadIndex: ${e}. Must be a non-negative integer.`);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid buttonIndex: ${t}. Must be a non-negative integer.`);let n=this.gamepads.get(e);return!n||!n.connected||t>=n.buttons.length?0:n.buttons[t].value}getAxis(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid gamepadIndex: ${e}. Must be a non-negative integer.`);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid axisIndex: ${t}. Must be a non-negative integer.`);let n=this.gamepads.get(e);if(!n||!n.connected||t>=n.axes.length)return 0;let i=n.axes[t];return this.applyDeadzone(i)}getAxisRaw(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid gamepadIndex: ${e}. Must be a non-negative integer.`);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid axisIndex: ${t}. Must be a non-negative integer.`);let n=this.gamepads.get(e);return!n||!n.connected||t>=n.axes.length?0:n.axes[t]}getLeftStick(e){return{x:this.getAxis(e,0),y:this.getAxis(e,1)}}getRightStick(e){return{x:this.getAxis(e,2),y:this.getAxis(e,3)}}supportsVibration(e){let t=this.getNativeGamepad(e);if(!t)return!1;let n=t.vibrationActuator;if(n&&typeof n.playEffect=="function")return!0;let i=t.hapticActuators;return!!(i&&i.length>0)}async vibrate(e,t){let n=this.getNativeGamepad(e);if(!n)return this.log(`Vibrate failed: gamepad ${e} not found`),!1;let{duration:i,strongMagnitude:s=1,weakMagnitude:o=.5,startDelay:a=0}=t;try{let l=n.vibrationActuator;if(l&&typeof l.playEffect=="function"){let c=await l.playEffect("dual-rumble",{startDelay:a,duration:i,strongMagnitude:Math.min(1,Math.max(0,s)),weakMagnitude:Math.min(1,Math.max(0,o))});return this.log(`Vibration effect result: ${c}`),c==="complete"}let u=n.hapticActuators;if(u&&u.length>0){let c=Math.max(s,o);return await u[0].pulse(c,i),!0}return this.log(`Vibrate failed: gamepad ${e} does not support vibration`),!1}catch(l){return this.log("Vibrate error:",l),!1}}async stopVibration(e){let t=this.getNativeGamepad(e);if(!t)return!1;try{let n=t.vibrationActuator;return n&&typeof n.reset=="function"?(await n.reset(),!0):n&&typeof n.playEffect=="function"?(await n.playEffect("dual-rumble",{duration:0,strongMagnitude:0,weakMagnitude:0}),!0):!1}catch(n){return this.log("Stop vibration error:",n),!1}}async stopAllVibrations(){let e=[];for(let[t]of this.gamepads)e.push(this.stopVibration(t));await Promise.all(e)}async vibrateAll(e){let t=[];for(let[n]of this.gamepads)t.push(this.vibrate(n,e));await Promise.all(t)}async vibratePreset(e,t){let n=this.vibrationPresets[t];return n?this.vibrate(e,n):(this.log(`Unknown vibration preset: ${t}`),!1)}getNativeGamepad(e){return(navigator.getGamepads?navigator.getGamepads():[])[e]||null}setGamepadCallbacks(e){this.gamepadCallbacks={...this.gamepadCallbacks,...e}}clearGamepadCallbacks(){this.gamepadCallbacks={}}setCallbacks(e){this.isGamepadCallbacks(e)&&this.setGamepadCallbacks(e)}isGamepadCallbacks(e){return typeof e=="object"&&e!==null&&("onGamepadConnected"in e||"onGamepadDisconnected"in e||"onButtonDown"in e||"onButtonUp"in e||"onAxisMove"in e)}updateGamepadState(e){let t=this.gamepads.get(e.index),n=Array.from(e.buttons).map((o,a)=>{let l=t==null?void 0:t.buttons[a],u=o.pressed,c=(l==null?void 0:l.pressed)??!1;return{pressed:u,justPressed:u&&!c,justReleased:!u&&c,value:o.value,touched:o.touched??!1}}),i=Array.from(e.axes),s={id:e.id,index:e.index,connected:e.connected,buttons:n,axes:i,timestamp:e.timestamp,mapping:e.mapping};this.gamepads.set(e.index,s),this.triggerCallbacks(s,t)}triggerCallbacks(e,t){try{e.buttons.forEach((n,i)=>{var s,o,a,l;n.justPressed&&((o=(s=this.gamepadCallbacks).onButtonDown)==null||o.call(s,e.index,i,n.value)),n.justReleased&&((l=(a=this.gamepadCallbacks).onButtonUp)==null||l.call(a,e.index,i))}),e.axes.forEach((n,i)=>{var l,u;let s=(t==null?void 0:t.axes[i])??0,o=this.applyDeadzone(n),a=this.applyDeadzone(s);Math.abs(o-a)>kk&&((u=(l=this.gamepadCallbacks).onAxisMove)==null||u.call(l,e.index,i,o))})}catch(n){this.log("Error in gamepad callbacks:",n)}}handleGamepadConnected(e){var t,n;try{this.log(`Gamepad connected: ${e.gamepad.id} at index ${e.gamepad.index}`);let i={id:e.gamepad.id,index:e.gamepad.index,connected:!0,buttons:Array.from(e.gamepad.buttons).map(s=>({pressed:s.pressed,justPressed:!1,justReleased:!1,value:s.value,touched:s.touched??!1})),axes:Array.from(e.gamepad.axes),timestamp:e.gamepad.timestamp,mapping:e.gamepad.mapping};this.gamepads.set(e.gamepad.index,i),(n=(t=this.gamepadCallbacks).onGamepadConnected)==null||n.call(t,i)}catch(i){this.log("Error handling gamepad connected:",i)}}handleGamepadDisconnected(e){var t,n;try{this.log(`Gamepad disconnected at index ${e.gamepad.index}`),this.gamepads.delete(e.gamepad.index),this.previousGamepads.delete(e.gamepad.index),(n=(t=this.gamepadCallbacks).onGamepadDisconnected)==null||n.call(t,e.gamepad.index)}catch(i){this.log("Error handling gamepad disconnected:",i)}}applyDeadzone(e){let t=this.gamepadConfig.axisDeadzone;return Math.abs(e)<t?0:(e>0?1:-1)*((Math.abs(e)-t)/(1-t))}cloneGamepadState(e){return{...e,buttons:e.buttons.map(t=>({...t})),axes:[...e.axes]}}};wr(uw,"GamepadInputs");var cw=uw;function Ek(r,e){let t=new cw(e);return r&&t.setGamepadCallbacks(r),t.start(),t}wr(Ek,"useGamepadInputs");var dw=class{constructor(e={}){ke(this,"keyboard",null),ke(this,"mouse",null),ke(this,"gamepad",null),ke(this,"mobile",null),ke(this,"touchZones",null),ke(this,"config"),this.config={enableKeyboardMouse:e.enableKeyboardMouse??!0,enableGamepad:e.enableGamepad??!0,enableMobile:e.enableMobile??!1,targetElement:e.targetElement??window,mobileTargetElement:e.mobileTargetElement??e.targetElement??window,debug:e.debug??!1,keyboardConfig:{preventDefault:!1,stopPropagation:!1,...e.keyboardConfig},mouseConfig:{preventDefault:!1,stopPropagation:!1,...e.mouseConfig},mobileConfig:{preventDefault:!0,passive:!1,maxTouches:10,...e.mobileConfig},enableTouchZones:e.enableTouchZones??!1,touchZoneConfig:e.touchZoneConfig??{gridWidth:0,gridHeight:0}},this.initialize()}initialize(){var e,t,n,i,s,o,a,l,u;if(this.config.enableKeyboardMouse&&(this.keyboard=new nw(this.config.targetElement,{preventDefault:((e=this.config.keyboardConfig)==null?void 0:e.preventDefault)??!1,stopPropagation:((t=this.config.keyboardConfig)==null?void 0:t.stopPropagation)??!1,debug:this.config.debug}),this.keyboard.start(),this.mouse=new sw(this.config.targetElement,{preventDefault:((n=this.config.mouseConfig)==null?void 0:n.preventDefault)??!1,stopPropagation:((i=this.config.mouseConfig)==null?void 0:i.stopPropagation)??!1,debug:this.config.debug}),this.mouse.start(),this.log("Keyboard/Mouse initialized")),this.config.enableGamepad&&(this.gamepad=new cw({debug:this.config.debug}),this.gamepad.start(),this.log("Gamepad initialized")),this.config.enableMobile&&(this.config.mobileTargetElement?(this.mobile=new ah(this.config.mobileTargetElement,this.config.mobileConfig),this.mobile.start(),this.log("Mobile/Touch initialized")):this.warn("Mobile input enabled but no canvas provided - mobile input will be disabled until setMobileTarget() is called")),this.config.enableTouchZones){let c=((s=this.config.touchZoneConfig)==null?void 0:s.targetElement)??this.config.mobileTargetElement;if(!c||!c.getBoundingClientRect)this.warn("Touch zones enabled but no canvas HTMLElement provided - touch zones disabled");else if(!this.mobile)this.warn("Touch zones require mobile input to be enabled - touch zones disabled");else{let d={targetElement:c,gridWidth:((o=this.config.touchZoneConfig)==null?void 0:o.gridWidth)??0,gridHeight:((a=this.config.touchZoneConfig)==null?void 0:a.gridHeight)??0,rendererOffsets:(l=this.config.touchZoneConfig)==null?void 0:l.rendererOffsets,zones:(u=this.config.touchZoneConfig)==null?void 0:u.zones,enabled:!0,debug:this.config.debug};this.disableSystemLongPressHaptics(c),this.touchZones=new rm(this.mobile,d),this.log("Touch zones initialized")}}}getButton(e,t){if(!aa({device:e,input:t}))return this.warn(`Input ${t} on device ${e} is not a button`),!1;switch(e){case ce.Keyboard:return this.getKeyboardButton(t);case ce.Mouse:return this.getMouseButton(t);case ce.Gamepad:return this.getGamepadButton(t);case ce.Touch:return this.getTouchButton(t);case ce.TouchZone:return this.getTouchZoneButton(t);default:return this.warn(`Unknown device type: ${e}`),!1}}getButtonJustPressed(e,t){if(!aa({device:e,input:t}))return this.warn(`Input ${t} on device ${e} is not a button`),!1;switch(e){case ce.Keyboard:return this.getKeyboardButtonJustPressed(t);case ce.Mouse:return this.getMouseButtonJustPressed(t);case ce.Gamepad:return this.getGamepadButtonJustPressed(t);case ce.Touch:return this.getTouchButtonJustPressed(t);case ce.TouchZone:return this.getTouchZoneButtonJustPressed(t);default:return this.warn(`Unknown device type: ${e}`),!1}}getButtonJustReleased(e,t){if(!aa({device:e,input:t}))return this.warn(`Input ${t} on device ${e} is not a button`),!1;switch(e){case ce.Keyboard:return this.getKeyboardButtonJustReleased(t);case ce.Mouse:return this.getMouseButtonJustReleased(t);case ce.Gamepad:return this.getGamepadButtonJustReleased(t);case ce.Touch:return this.getTouchButtonJustReleased(t);case ce.TouchZone:return this.getTouchZoneButtonJustReleased(t);default:return this.warn(`Unknown device type: ${e}`),!1}}getAxis(e,t){if(!I1({device:e,input:t}))return this.warn(`Input ${t} on device ${e} is not an axis`),0;switch(e){case ce.Keyboard:return this.warn("Keyboard does not have axis inputs"),0;case ce.Mouse:return this.getMouseAxis(t);case ce.Gamepad:return this.getGamepadAxis(t);case ce.Touch:return this.getTouchAxis(t);case ce.TouchZone:return this.getTouchZoneAxis(t);default:return this.warn(`Unknown device type: ${e}`),0}}isLeftMousePressed(){return this.mouse?this.mouse.isLeftMousePressed():!1}getKeyboardButton(e){if(!this.keyboard)return!1;let t=Ai[e];return this.keyboard.isKeyPressed(t)}getKeyboardButtonJustPressed(e){if(!this.keyboard)return!1;let t=Ai[e];return this.keyboard.isKeyJustPressed(t)}getKeyboardButtonJustReleased(e){if(!this.keyboard)return!1;let t=Ai[e];return this.keyboard.isKeyJustReleased(t)}getMouseButton(e){if(!this.mouse)return!1;switch(e){case Nt.LeftButton:return this.mouse.isLeftMousePressed();case Nt.RightButton:return this.mouse.isRightMousePressed();case Nt.MiddleButton:return this.mouse.isMiddleMousePressed();default:return!1}}getMouseButtonJustPressed(e){if(!this.mouse)return!1;switch(e){case Nt.LeftButton:return this.mouse.isLeftMouseJustPressed();case Nt.RightButton:return this.mouse.isRightMouseJustPressed();case Nt.MiddleButton:return this.mouse.isMiddleMouseJustPressed();default:return!1}}getMouseButtonJustReleased(e){if(!this.mouse)return!1;switch(e){case Nt.LeftButton:return this.mouse.isLeftMouseJustReleased();case Nt.RightButton:return this.mouse.isRightMouseJustReleased();case Nt.MiddleButton:return this.mouse.isMiddleMouseJustReleased();default:return!1}}getGamepadButton(e){return!this.gamepad||e>=100?!1:this.gamepad.isButtonPressed(0,e)}getGamepadButtonJustPressed(e){return!this.gamepad||e>=100?!1:this.gamepad.isButtonJustPressed(0,e)}getGamepadButtonJustReleased(e){return!this.gamepad||e>=100?!1:this.gamepad.isButtonJustReleased(0,e)}getTouchButton(e){var t,n;return this.mobile?e>=100?!1:((n=(t=this.mobile).isTouchActive)==null?void 0:n.call(t,e))??!1:(console.warn("🚫 MobileInputs not initialized!"),!1)}getTouchButtonJustPressed(e){var t,n;return!this.mobile||e>=100?!1:((n=(t=this.mobile).isTouchJustStarted)==null?void 0:n.call(t,e))??!1}getTouchButtonJustReleased(e){var t,n;return!this.mobile||e>=100?!1:((n=(t=this.mobile).isTouchJustReleased)==null?void 0:n.call(t,e))??!1}ensureTouchZonesSynced(){var e;(e=this.touchZones)==null||e.updateFromTouches()}getTouchZoneButton(e){if(!this.touchZones)return!1;this.ensureTouchZonesSynced();let t=e;return this.touchZones.isZonePressed(t)}getTouchZoneButtonJustPressed(e){if(!this.touchZones)return!1;this.ensureTouchZonesSynced();let t=e;return this.touchZones.isZoneJustPressed(t)}getTouchZoneButtonJustReleased(e){if(!this.touchZones)return!1;this.ensureTouchZonesSynced();let t=e;return this.touchZones.isZoneJustReleased(t)}getTouchZoneAxis(e){if(!this.touchZones||e<100)return 0;this.ensureTouchZonesSynced();let t=Math.floor((e-100)/2),n=(e-100)%2===0;return this.touchZones.getZoneAxis(t,n?"x":"y")}getMouseAxis(e){if(!this.mouse)return 0;switch(e){case Nt.PositionX:return this.mouse.getMousePosition().x;case Nt.PositionY:return this.mouse.getMousePosition().y;case Nt.DeltaX:return this.mouse.getMouseDelta().x;case Nt.DeltaY:return this.mouse.getMouseDelta().y;case Nt.WheelDeltaY:return this.mouse.getWheelDelta();default:return 0}}getGamepadAxis(e){if(!this.gamepad||e<100)return 0;let t=e-100;return this.gamepad.getAxis(0,t)}getTouchAxis(e){var t,n;if(!this.mobile)return 0;if(e>=100&&e<200){let i=Math.floor((e-100)/2),s=(e-100)%2===0,o=(n=(t=this.mobile).getTouchPosition)==null?void 0:n.call(t,i);return this.config.debug&&o&&console.warn(`🎯 getTouchAxis(${e}) - touchIndex: ${i}, ${s?"X":"Y"}: ${s?o.x:o.y}`),o?s?o.x:o.y:0}return 0}getMousePosition(){if(!this.mouse)return null;let e=this.mouse.getMousePosition();return{x:e.x,y:e.y}}setMobileTarget(e){if(!e){this.warn("setMobileTarget() called with null/undefined canvas - mobile input will remain disabled");return}if(this.config.mobileTargetElement=e,!this.config.enableMobile){this.warn("setMobileTarget() called but mobile input is disabled in config");return}this.mobile&&this.mobile.stop(),this.mobile=new ah(e,this.config.mobileConfig),this.mobile.start()}getTextInputs(){return this.keyboard?this.keyboard.getTextInputs():[]}start(){var e,t;(e=this.keyboard)==null||e.start(),(t=this.mouse)==null||t.start(),this.log("Input router started")}stop(){var e,t;(e=this.keyboard)==null||e.stop(),(t=this.mouse)==null||t.stop(),this.log("Input router stopped")}reset(){var e,t;(e=this.keyboard)==null||e.reset(),(t=this.mouse)==null||t.reset(),this.log("Input router reset")}poll(){var e,t,n,i,s;(e=this.keyboard)==null||e.poll(),(t=this.mouse)==null||t.poll(),(n=this.gamepad)==null||n.poll(),(i=this.mobile)==null||i.poll(),(s=this.touchZones)==null||s.poll()}isListening(){return this.keyboard!==null&&this.config.enableKeyboardMouse||this.gamepad!==null&&this.config.enableGamepad||this.mobile!==null&&this.config.enableMobile||this.touchZones!==null&&this.config.enableTouchZones}getGamepad(){return this.gamepad}getKeyboard(){return this.keyboard}getMouse(){return this.mouse}getMobile(){return this.mobile}getTouchZones(){return this.touchZones}enableTouchZonesDevice(e,t,n,i){let s=Math.max(1,t),o=Math.max(1,n);if(this.touchZones)return i&&this.touchZones.setZones(i),this.touchZones.setLayout(s,o),!0;if(!this.mobile)return this.warn("Cannot enable touch zones: mobile input not initialized"),!1;let a={targetElement:e,gridWidth:s,gridHeight:o,zones:i,enabled:!0,debug:this.config.debug};return this.disableSystemLongPressHaptics(e),this.touchZones=new rm(this.mobile,a),this.touchZones.start(),this.log(`Touch zones dynamically enabled with ${(i==null?void 0:i.length)??0} zones`),!0}updateTouchZoneLayout(e,t,n){var o;let i=Math.max(1,e),s=Math.max(1,t);(o=this.touchZones)==null||o.setLayout(i,s,n)}destroy(){var e,t;(e=this.keyboard)==null||e.destroy(),(t=this.mouse)==null||t.destroy(),this.keyboard=null,this.mouse=null,this.gamepad=null,this.mobile=null,this.touchZones=null,this.log("Input router destroyed")}log(e){}warn(e){console.warn(`[InputRouter] ${e}`)}disableSystemLongPressHaptics(e){let t="__utspTouchSurfacePatched";if(e[t])return;e[t]=!0;let n=e.tagName.toLowerCase()==="canvas"||(e.getAttribute("data-utsp-input-surface")??"").toLowerCase()==="true";n&&(e.style.setProperty("touch-action","none"),e.style.setProperty("user-select","none"),e.style.setProperty("-webkit-user-select","none"),e.style.setProperty("-webkit-touch-callout","none")),e.addEventListener("contextmenu",i=>i.preventDefault()),n&&e.addEventListener("touchstart",i=>{this.config.mobileConfig.preventDefault&&i.preventDefault()},{passive:!this.config.mobileConfig.preventDefault})}};wr(dw,"UnifiedInputRouter");var hw=dw,nm=100,im=2,fw=class lh{static calculateRenderMetrics(e,t){let n=e.getBoundingClientRect(),i=e.width/e.height,s=n.width/n.height,o,a,l,u;i>s?(o=n.width,a=n.width/i,l=0,u=(n.height-a)/2):(o=n.height*i,a=n.height,l=(n.width-o)/2,u=0);let c=(t==null?void 0:t.offsetX)||0,d=(t==null?void 0:t.offsetY)||0;return l+=c,u+=d,o-=c*2,a-=d*2,{renderWidth:o,renderHeight:a,offsetX:l,offsetY:u,rect:n}}static collectAxisSources(e,t){let n=new Map;for(let i of e)for(let s of i.sources){if(n.has(s.sourceId))continue;let o=0,a=!1;if(s.type===ce.Keyboard&&s.negativeKey!==void 0&&s.positiveKey!==void 0){let l=t.getButton(ce.Keyboard,s.negativeKey);t.getButton(ce.Keyboard,s.positiveKey)&&(o+=1),l&&(o-=1),a=!0}else if(s.type===ce.Mouse&&s.mouseAxis!==void 0)o=t.getAxis(ce.Mouse,s.mouseAxis),a=!0;else if(s.type===ce.Gamepad&&s.axis!==void 0)o=t.getAxis(ce.Gamepad,s.axis),a=!0;else if(s.type===ce.Touch&&s.touchId!==void 0&&s.touchAxis!==void 0){let l=100+s.touchId*2,u=s.touchAxis==="x"?l:l+1;o=t.getAxis(ce.Touch,u),a=!0}else if(s.type===ce.TouchZone&&s.touchZoneId!==void 0&&s.touchZoneAxis!==void 0){let l=100+s.touchZoneId*2,u=s.touchZoneAxis==="x"?l:l+1;o=t.getAxis(ce.TouchZone,u),a=!0}a&&n.set(s.sourceId,o)}return n}static collectButtonSources(e,t){let n=new Map;for(let i of e)for(let s of i.sources){if(n.has(s.sourceId))continue;let o=!1,a=!1;s.type===ce.Keyboard&&s.key!==void 0?(o=t.getButton(ce.Keyboard,s.key),a=!0):s.type===ce.Mouse&&s.mouseButton!==void 0?(o=t.getButton(ce.Mouse,s.mouseButton),a=!0):s.type===ce.Gamepad&&s.button!==void 0?(o=t.getButton(ce.Gamepad,s.button),a=!0):s.type===ce.Touch&&s.touchButton!==void 0?(o=t.getButton(ce.Touch,s.touchButton),a=!0):s.type===ce.TouchZone&&s.touchZoneId!==void 0&&(o=t.getButton(ce.TouchZone,s.touchZoneId),a=!0),a&&n.set(s.sourceId,o)}return n}static collectButtonSourcesWithTransitions(e,t){var i,s,o,a,l,u,c,d,h,f;let n=new Map;for(let p of e)for(let m of p.sources){if(n.has(m.sourceId))continue;let S=!1,w=!1,g=!1,y=!1;m.type===ce.Keyboard&&m.key!==void 0?(S=t.getButton(ce.Keyboard,m.key),w=((i=t.getButtonJustPressed)==null?void 0:i.call(t,ce.Keyboard,m.key))??!1,g=((s=t.getButtonJustReleased)==null?void 0:s.call(t,ce.Keyboard,m.key))??!1,y=!0):m.type===ce.Mouse&&m.mouseButton!==void 0?(S=t.getButton(ce.Mouse,m.mouseButton),w=((o=t.getButtonJustPressed)==null?void 0:o.call(t,ce.Mouse,m.mouseButton))??!1,g=((a=t.getButtonJustReleased)==null?void 0:a.call(t,ce.Mouse,m.mouseButton))??!1,y=!0):m.type===ce.Gamepad&&m.button!==void 0?(S=t.getButton(ce.Gamepad,m.button),w=((l=t.getButtonJustPressed)==null?void 0:l.call(t,ce.Gamepad,m.button))??!1,g=((u=t.getButtonJustReleased)==null?void 0:u.call(t,ce.Gamepad,m.button))??!1,y=!0):m.type===ce.Touch&&m.touchButton!==void 0?(S=t.getButton(ce.Touch,m.touchButton),w=((c=t.getButtonJustPressed)==null?void 0:c.call(t,ce.Touch,m.touchButton))??!1,g=((d=t.getButtonJustReleased)==null?void 0:d.call(t,ce.Touch,m.touchButton))??!1,y=!0):m.type===ce.TouchZone&&m.touchZoneId!==void 0&&(S=t.getButton(ce.TouchZone,m.touchZoneId),w=((h=t.getButtonJustPressed)==null?void 0:h.call(t,ce.TouchZone,m.touchZoneId))??!1,g=((f=t.getButtonJustReleased)==null?void 0:f.call(t,ce.TouchZone,m.touchZoneId))??!1,y=!0),y&&n.set(m.sourceId,{pressed:S,justPressed:w,justReleased:g})}return n}static collectMousePosition(e,t,n,i,s){var x;let o=e.getAxis(ce.Mouse,Nt.PositionX),a=e.getAxis(ce.Mouse,Nt.PositionY),l=((x=e.isLeftMousePressed)==null?void 0:x.call(e))??!1,{renderWidth:u,renderHeight:c,offsetX:d,offsetY:h,rect:f}=lh.calculateRenderMetrics(t,s),p=o-f.left-d,m=a-f.top-h,S=u/n,w=c/i,g=Math.floor(p/S),y=Math.floor(m/w),C=p>=0&&p<u&&m>=0&&m<c;return{x:Math.max(0,Math.min(n-1,g)),y:Math.max(0,Math.min(i-1,y)),over:C,isLeftDown:l}}static collectTouchPositions(e,t,n,i,s=10,o){let a=[],{renderWidth:l,renderHeight:u,offsetX:c,offsetY:d,rect:h}=lh.calculateRenderMetrics(t,o),f=l/n,p=u/i;for(let m=0;m<s;m++){let S=m;if(e.getButton(ce.Touch,S)){let w=nm+m*im,g=nm+m*im+1,y=e.getAxis(ce.Touch,w),C=e.getAxis(ce.Touch,g),x=y-h.left-c,I=C-h.top-d,E=Math.floor(x/f),A=Math.floor(I/p),R=x>=0&&x<l&&I>=0&&I<u;a.push({id:m,x:Math.max(0,Math.min(n-1,E)),y:Math.max(0,Math.min(i-1,A)),over:R})}}return a}static collectTextInputs(e){return typeof e.getTextInputs=="function"?e.getTextInputs():[]}};wr(fw,"InputCollector");var Er=fw;const Yn=Object.create(null);Yn.open="0";Yn.close="1";Yn.ping="2";Yn.pong="3";Yn.message="4";Yn.upgrade="5";Yn.noop="6";const Rl=Object.create(null);Object.keys(Yn).forEach(r=>{Rl[Yn[r]]=r});const uh={type:"error",data:"parser error"},pw=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",gw=typeof ArrayBuffer=="function",mw=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,Af=({type:r,data:e},t,n)=>pw&&e instanceof Blob?t?n(e):sm(e,n):gw&&(e instanceof ArrayBuffer||mw(e))?t?n(e):sm(new Blob([e]),n):n(Yn[r]+(e||"")),sm=(r,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)};function om(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Nc;function Mk(r,e){if(pw&&r.data instanceof Blob)return r.data.arrayBuffer().then(om).then(e);if(gw&&(r.data instanceof ArrayBuffer||mw(r.data)))return e(om(r.data));Af(r,!1,t=>{Nc||(Nc=new TextEncoder),e(Nc.encode(t))})}const am="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Wo=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<am.length;r++)Wo[am.charCodeAt(r)]=r;const Uk=r=>{let e=r.length*.75,t=r.length,n,i=0,s,o,a,l;r[r.length-1]==="="&&(e--,r[r.length-2]==="="&&e--);const u=new ArrayBuffer(e),c=new Uint8Array(u);for(n=0;n<t;n+=4)s=Wo[r.charCodeAt(n)],o=Wo[r.charCodeAt(n+1)],a=Wo[r.charCodeAt(n+2)],l=Wo[r.charCodeAt(n+3)],c[i++]=s<<2|o>>4,c[i++]=(o&15)<<4|a>>2,c[i++]=(a&3)<<6|l&63;return u},Ak=typeof ArrayBuffer=="function",Tf=(r,e)=>{if(typeof r!="string")return{type:"message",data:yw(r,e)};const t=r.charAt(0);return t==="b"?{type:"message",data:Tk(r.substring(1),e)}:Rl[t]?r.length>1?{type:Rl[t],data:r.substring(1)}:{type:Rl[t]}:uh},Tk=(r,e)=>{if(Ak){const t=Uk(r);return yw(t,e)}else return{base64:!0,data:r}},yw=(r,e)=>{switch(e){case"blob":return r instanceof Blob?r:new Blob([r]);case"arraybuffer":default:return r instanceof ArrayBuffer?r:r.buffer}},vw="",Rk=(r,e)=>{const t=r.length,n=new Array(t);let i=0;r.forEach((s,o)=>{Af(s,!1,a=>{n[o]=a,++i===t&&e(n.join(vw))})})},Pk=(r,e)=>{const t=r.split(vw),n=[];for(let i=0;i<t.length;i++){const s=Tf(t[i],e);if(n.push(s),s.type==="error")break}return n};function Bk(){return new TransformStream({transform(r,e){Mk(r,t=>{const n=t.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const s=new DataView(i.buffer);s.setUint8(0,126),s.setUint16(1,n)}else{i=new Uint8Array(9);const s=new DataView(i.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(n))}r.data&&typeof r.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let Vc;function cl(r){return r.reduce((e,t)=>e+t.length,0)}function dl(r,e){if(r[0].length===e)return r.shift();const t=new Uint8Array(e);let n=0;for(let i=0;i<e;i++)t[i]=r[0][n++],n===r[0].length&&(r.shift(),n=0);return r.length&&n<r[0].length&&(r[0]=r[0].slice(n)),t}function zk(r,e){Vc||(Vc=new TextDecoder);const t=[];let n=0,i=-1,s=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(n===0){if(cl(t)<1)break;const l=dl(t,1);s=(l[0]&128)===128,i=l[0]&127,i<126?n=3:i===126?n=1:n=2}else if(n===1){if(cl(t)<2)break;const l=dl(t,2);i=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),n=3}else if(n===2){if(cl(t)<8)break;const l=dl(t,8),u=new DataView(l.buffer,l.byteOffset,l.length),c=u.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(uh);break}i=c*Math.pow(2,32)+u.getUint32(4),n=3}else{if(cl(t)<i)break;const l=dl(t,i);a.enqueue(Tf(s?l:Vc.decode(l),e)),n=0}if(i===0||i>r){a.enqueue(uh);break}}}})}const ww=4;function Ot(r){if(r)return Dk(r)}function Dk(r){for(var e in Ot.prototype)r[e]=Ot.prototype[e];return r}Ot.prototype.on=Ot.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};Ot.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};Ot.prototype.off=Ot.prototype.removeListener=Ot.prototype.removeAllListeners=Ot.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,i=0;i<t.length;i++)if(n=t[i],n===e||n.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+r],this};Ot.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,e)}return this};Ot.prototype.emitReserved=Ot.prototype.emit;Ot.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};Ot.prototype.hasListeners=function(r){return!!this.listeners(r).length};const Pu=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),cn=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Ok="arraybuffer";function Cw(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}const Fk=cn.setTimeout,Lk=cn.clearTimeout;function Bu(r,e){e.useNativeTimers?(r.setTimeoutFn=Fk.bind(cn),r.clearTimeoutFn=Lk.bind(cn)):(r.setTimeoutFn=cn.setTimeout.bind(cn),r.clearTimeoutFn=cn.clearTimeout.bind(cn))}const _k=1.33;function $k(r){return typeof r=="string"?Nk(r):Math.ceil((r.byteLength||r.size)*_k)}function Nk(r){let e=0,t=0;for(let n=0,i=r.length;n<i;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function bw(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Vk(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function Hk(r){let e={},t=r.split("&");for(let n=0,i=t.length;n<i;n++){let s=t[n].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}class jk extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Rf extends Ot{constructor(e){super(),this.writable=!1,Bu(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new jk(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Tf(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=Vk(e);return t.length?"?"+t:""}}class Yk extends Rf{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||t()})),this.writable||(n++,this.once("drain",function(){--n||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};Pk(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Rk(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=bw()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Sw=!1;try{Sw=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Wk=Sw;function Gk(){}class Xk extends Yk{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,s)=>{this.onError("xhr post error",i,s)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}class jn extends Ot{constructor(e,t,n){super(),this.createRequest=e,Bu(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=Cw(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=jn.requestsCount++,jn.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Gk,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete jn.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}jn.requestsCount=0;jn.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",lm);else if(typeof addEventListener=="function"){const r="onpagehide"in cn?"pagehide":"unload";addEventListener(r,lm,!1)}}function lm(){for(let r in jn.requests)jn.requests.hasOwnProperty(r)&&jn.requests[r].abort()}const Kk=function(){const r=xw({xdomain:!1});return r&&r.responseType!==null}();class Zk extends Xk{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Kk&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new jn(xw,this.uri(),e)}}function xw(r){const e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Wk))return new XMLHttpRequest}catch{}if(!e)try{return new cn[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Iw=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qk extends Rf{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Iw?{}:Cw(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;Af(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{}i&&Pu(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=bw()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Hc=cn.WebSocket||cn.MozWebSocket;class Qk extends qk{createSocket(e,t,n){return Iw?new Hc(e,t,n):t?new Hc(e,t):new Hc(e)}doWrite(e,t){this.ws.send(t)}}class Jk extends Rf{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=zk(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=Bk();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const s=()=>{n.read().then(({done:a,value:l})=>{a||(this.onPacket(l),s())}).catch(a=>{})};s();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;this._writer.write(n).then(()=>{i&&Pu(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const eE={websocket:Qk,webtransport:Jk,polling:Zk},tE=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,rE=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ch(r){if(r.length>8e3)throw"URI too long";const e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let i=tE.exec(r||""),s={},o=14;for(;o--;)s[rE[o]]=i[o]||"";return t!=-1&&n!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=nE(s,s.path),s.queryKey=iE(s,s.query),s}function nE(r,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function iE(r,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}const dh=typeof addEventListener=="function"&&typeof removeEventListener=="function",Pl=[];dh&&addEventListener("offline",()=>{Pl.forEach(r=>r())},!1);class Ri extends Ot{constructor(e,t){if(super(),this.binaryType=Ok,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const n=ch(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=ch(t.host).host);Bu(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{const i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Hk(this.opts.query)),dh&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Pl.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=ww,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&Ri.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",Ri.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(t+=$k(i)),n>0&&t>this._maxPayload)return this.writeBuffer.slice(0,n);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Pu(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const s={type:e,data:t,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Ri.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),dh&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Pl.indexOf(this._offlineEventListener);n!==-1&&Pl.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Ri.protocol=ww;class sE extends Ri{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Ri.priorWebsocketSuccess=!1;const i=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",d=>{if(!n)if(d.type==="pong"&&d.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Ri.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const h=new Error("probe error");h.transport=t.name,this.emitReserved("upgradeError",h)}}))};function s(){n||(n=!0,c(),t.close(),t=null)}const o=d=>{const h=new Error("probe error: "+d);h.transport=t.name,s(),this.emitReserved("upgradeError",h)};function a(){o("transport closed")}function l(){o("socket closed")}function u(d){t&&d.name!==t.name&&s()}const c=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",a),this.off("close",l),this.off("upgrading",u)};t.once("open",i),t.once("error",o),t.once("close",a),this.once("close",l),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let oE=class extends sE{constructor(e,t={}){const n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>eE[i]).filter(i=>!!i)),super(e,n)}};function aE(r,e="",t){let n=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),n=ch(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+e,n.href=n.protocol+"://"+s+(t&&t.port===n.port?"":":"+n.port),n}const lE=typeof ArrayBuffer=="function",uE=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,kw=Object.prototype.toString,cE=typeof Blob=="function"||typeof Blob<"u"&&kw.call(Blob)==="[object BlobConstructor]",dE=typeof File=="function"||typeof File<"u"&&kw.call(File)==="[object FileConstructor]";function Pf(r){return lE&&(r instanceof ArrayBuffer||uE(r))||cE&&r instanceof Blob||dE&&r instanceof File}function Bl(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(Bl(r[t]))return!0;return!1}if(Pf(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return Bl(r.toJSON(),!0);for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&Bl(r[t]))return!0;return!1}function hE(r){const e=[],t=r.data,n=r;return n.data=hh(t,e),n.attachments=e.length,{packet:n,buffers:e}}function hh(r,e){if(!r)return r;if(Pf(r)){const t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){const t=new Array(r.length);for(let n=0;n<r.length;n++)t[n]=hh(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){const t={};for(const n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=hh(r[n],e));return t}return r}function fE(r,e){return r.data=fh(r.data,e),delete r.attachments,r}function fh(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=fh(r[t],e);else if(typeof r=="object")for(const t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=fh(r[t],e));return r}const pE=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],gE=5;var Be;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Be||(Be={}));class mE{constructor(e){this.replacer=e}encode(e){return(e.type===Be.EVENT||e.type===Be.ACK)&&Bl(e)?this.encodeAsBinary({type:e.type===Be.EVENT?Be.BINARY_EVENT:Be.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Be.BINARY_EVENT||e.type===Be.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=hE(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}function um(r){return Object.prototype.toString.call(r)==="[object Object]"}class Bf extends Ot{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===Be.BINARY_EVENT;n||t.type===Be.BINARY_ACK?(t.type=n?Be.EVENT:Be.ACK,this.reconstructor=new yE(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Pf(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(Be[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Be.BINARY_EVENT||n.type===Be.BINARY_ACK){const s=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(s,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");n.attachments=Number(o)}if(e.charAt(t+1)==="/"){const s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(s,t)}else n.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const s=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){const s=this.tryParse(e.substr(t));if(Bf.isPayloadValid(n.type,s))n.data=s;else throw new Error("invalid payload")}return n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Be.CONNECT:return um(t);case Be.DISCONNECT:return t===void 0;case Be.CONNECT_ERROR:return typeof t=="string"||um(t);case Be.EVENT:case Be.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&pE.indexOf(t[0])===-1);case Be.ACK:case Be.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class yE{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=fE(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const vE=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Bf,Encoder:mE,get PacketType(){return Be},protocol:gE},Symbol.toStringTag,{value:"Module"}));function xn(r,e,t){return r.on(e,t),function(){r.off(e,t)}}const wE=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ew extends Ot{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[xn(e,"open",this.onopen.bind(this)),xn(e,"packet",this.onpacket.bind(this)),xn(e,"error",this.onerror.bind(this)),xn(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,i,s;if(wE.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:Be.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const c=this.ids++,d=t.pop();this._registerAckCallback(c,d),o.id=c}const a=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,l=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!a||(l?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&this.sendBuffer.splice(a,1);t.call(this,new Error("operation has timed out"))},i),o=(...a)=>{this.io.clearTimeoutFn(s),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((n,i)=>{const s=(o,a)=>o?i(o):n(a);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...s)=>n!==this._queue[0]?void 0:(i!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Be.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Be.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Be.EVENT:case Be.BINARY_EVENT:this.onevent(e);break;case Be.ACK:case Be.BINARY_ACK:this.onack(e);break;case Be.DISCONNECT:this.ondisconnect();break;case Be.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...i){n||(n=!0,t.packet({type:Be.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Be.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function mo(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}mo.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=Math.floor(e*10)&1?r+t:r-t}return Math.min(r,this.max)|0};mo.prototype.reset=function(){this.attempts=0};mo.prototype.setMin=function(r){this.ms=r};mo.prototype.setMax=function(r){this.max=r};mo.prototype.setJitter=function(r){this.jitter=r};class ph extends Ot{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,Bu(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new mo({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||vE;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new oE(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=xn(t,"open",function(){n.onopen(),e&&e()}),s=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=xn(t,"error",s);if(this._timeout!==!1){const a=this._timeout,l=this.setTimeoutFn(()=>{i(),s(new Error("timeout")),t.close()},a);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(xn(e,"ping",this.onping.bind(this)),xn(e,"data",this.ondata.bind(this)),xn(e,"error",this.onerror.bind(this)),xn(e,"close",this.onclose.bind(this)),xn(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){Pu(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Ew(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Oo={};function ua(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};const t=aE(r,e.path||"/socket.io"),n=t.source,i=t.id,s=t.path,o=Oo[i]&&s in Oo[i].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let l;return a?l=new ph(n,e):(Oo[i]||(Oo[i]=new ph(n,e)),l=Oo[i]),t.query&&!e.query&&(e.query=t.queryKey),l.socket(t.path,e)}Object.assign(ua,{Manager:ph,Socket:Ew,io:ua,connect:ua});var Mw=Object.defineProperty,CE=(r,e,t)=>e in r?Mw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,zf=(r,e)=>Mw(r,"name",{value:e,configurable:!0}),mt=(r,e,t)=>(CE(r,typeof e!="symbol"?e+"":e,t),t),Uw=class{constructor(e){if(mt(this,"socket",null),mt(this,"options"),mt(this,"_state",yt.Disconnected),mt(this,"pingTimestamp",0),mt(this,"latency",0),mt(this,"pingInterval",null),mt(this,"bridgeHandlers",new Map),mt(this,"bridgeSetup",!1),!e.url||typeof e.url!="string")throw new Error("SocketIOClient: Invalid URL - must be a non-empty string");try{if(!new globalThis.URL(e.url).protocol)throw new Error("Invalid protocol")}catch{throw new Error(`SocketIOClient: Invalid URL format - ${e.url}`)}if(e.reconnectDelay!==void 0&&(e.reconnectDelay<0||!Number.isFinite(e.reconnectDelay)))throw new Error(`SocketIOClient: Invalid reconnectDelay - must be a positive number (got ${e.reconnectDelay})`);if(e.maxReconnectAttempts!==void 0&&(!Number.isInteger(e.maxReconnectAttempts)||e.maxReconnectAttempts<0))throw new Error(`SocketIOClient: Invalid maxReconnectAttempts - must be a positive integer (got ${e.maxReconnectAttempts})`);if(e.timeout!==void 0&&(e.timeout<=0||!Number.isFinite(e.timeout)))throw new Error(`SocketIOClient: Invalid timeout - must be a positive number (got ${e.timeout})`);this.options={url:e.url,autoReconnect:e.autoReconnect??!0,reconnectDelay:e.reconnectDelay??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,timeout:e.timeout??5e3,auth:e.auth??{},iceServers:e.iceServers??[],path:e.path,debug:e.debug??!1,sessionId:e.sessionId},this.log("Client initialized",{url:this.options.url,autoReconnect:this.options.autoReconnect})}get state(){return this._state}isConnected(){var e;return this._state===yt.Connected&&((e=this.socket)==null?void 0:e.connected)===!0}async connect(){if(this.socket&&this.isConnected()){this.log("Already connected");return}return this.log(`Connecting to ${this.options.url}...`),this._state=yt.Connecting,this.bridgeSetup=!1,new Promise((e,t)=>{this.socket=ua(this.options.url,{path:this.options.path,auth:this.options.auth,reconnection:this.options.autoReconnect,reconnectionDelay:this.options.reconnectDelay,reconnectionAttempts:this.options.maxReconnectAttempts,timeout:this.options.timeout,transports:["websocket"]}),this.socket.on("connect",()=>{var n;this.log(`Connected with ID: ${(n=this.socket)==null?void 0:n.id}`),this._state=yt.Connected,this.startPingMonitor(),this.bridgeHandlers.size>0&&this.setupBridgeListener(),e()}),this.socket.on("connect_error",n=>{this.log(`Connection error: ${n.message}`),this._state=yt.Error,t(n)}),this.socket.on("disconnect",n=>{this.log(`Disconnected: ${n}`),this._state=yt.Disconnected,this.stopPingMonitor()}),this.socket.on("reconnect_attempt",n=>{this.log(`Reconnection attempt ${n}...`),this._state=yt.Reconnecting}),this.socket.on("reconnect",n=>{this.log(`Reconnected after ${n} attempts`),this._state=yt.Connected,this.startPingMonitor()}),this.socket.on("reconnect_failed",()=>{this.log("Reconnection failed"),this._state=yt.Error}),this.socket.on("pong",()=>{this.latency=Date.now()-this.pingTimestamp,this.log(`Ping: ${this.latency}ms`)})})}disconnect(){this.socket&&(this.log("Disconnecting..."),this.stopPingMonitor(),this.socket.disconnect(),this._state=yt.Disconnected)}send(e,t){if(!e||typeof e!="string"){this.log(`Cannot send: invalid event name (${typeof e})`);return}if(!this.isConnected()||!this.socket){this.log(`Cannot send '${e}': not connected`);return}try{this.socket.emit(e,t)}catch(n){this.log(`Error sending '${e}':`,n)}}sendVolatile(e,t){if(!(!e||typeof e!="string")&&!(!this.isConnected()||!this.socket))try{this.socket.volatile.emit(e,t)}catch(n){this.log(`Error sending volatile '${e}':`,n)}}on(e,t){if(!e||typeof e!="string")throw new Error(`Invalid event name: ${e}`);if(typeof t!="function")throw new Error(`Invalid handler for event '${e}': must be a function`);if(!this.socket){this.log(`Cannot listen to '${e}': socket not initialized`);return}this.socket.on(e,t),this.log(`Listening to '${e}'`)}off(e,t){this.socket&&(this.socket.off(e,t),this.log(`Stopped listening to '${e}'`))}removeAllListeners(e){this.socket&&(e?(this.socket.removeAllListeners(e),this.log(`Removed all listeners for '${e}'`)):(this.socket.removeAllListeners(),this.log("Removed all listeners")))}async request(e,t,n=5e3){if(!e||typeof e!="string")throw new Error(`Invalid event name: ${e}`);if(!Number.isFinite(n)||n<=0)throw new Error(`Invalid timeout: ${n} (must be a positive number)`);if(!this.isConnected())throw new Error("Cannot send request: not connected to server");return new Promise((i,s)=>{let o=`${e}_response`,a=setTimeout(()=>{this.off(o,l),s(new Error(`Request timeout after ${n}ms: ${e}`))},n),l=zf(u=>{clearTimeout(a),this.off(o,l),i(u)},"responseHandler");this.on(o,l),this.send(e,t),this.log(`Request sent: ${e} (timeout: ${n}ms)`)})}getPing(){return this.latency}sendBridge(e,t){if(!this.isConnected()||!this.socket){this.log(`Cannot send bridge '${e}': not connected`);return}try{let n={channel:e,data:JSON.stringify(t)};this.socket.emit("bridge",n),this.log(`Bridge sent on channel '${e}'`)}catch(n){this.log(`Error sending bridge: ${n}`)}}onBridge(e,t){this.bridgeHandlers.has(e)||this.bridgeHandlers.set(e,[]),this.bridgeHandlers.get(e).push(t),this.log(`Bridge handler registered for channel '${e}'`),this.setupBridgeListener()}offBridge(e,t){let n=this.bridgeHandlers.get(e);if(n){let i=n.indexOf(t);i!==-1&&(n.splice(i,1),this.log(`Bridge handler removed for channel '${e}'`))}}removeAllBridgeHandlers(e){e?(this.bridgeHandlers.delete(e),this.log(`All bridge handlers removed for channel '${e}'`)):(this.bridgeHandlers.clear(),this.log("All bridge handlers removed"))}setupBridgeListener(){this.bridgeSetup||!this.socket||(this.socket.on("bridge",e=>{this.handleBridgeMessage(e)}),this.bridgeSetup=!0,this.log("Bridge listener setup"))}handleBridgeMessage(e){try{let{channel:t,data:n}=e,i=JSON.parse(n),s=this.bridgeHandlers.get(t);s&&s.length>0?s.forEach(o=>{try{o(i)}catch(a){this.log(`Error in bridge handler for '${t}': ${a}`)}}):this.log(`No bridge handler for channel '${t}'`)}catch(t){this.log(`Error parsing bridge message: ${t}`)}}destroy(){this.log("Destroying client..."),this.stopPingMonitor(),this.bridgeHandlers.clear(),this.bridgeSetup=!1,this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null),this._state=yt.Disconnected,this.log("Client destroyed")}startPingMonitor(){this.pingInterval||(this.pingInterval=setInterval(()=>{this.isConnected()&&this.socket&&(this.pingTimestamp=Date.now(),this.socket.emit("ping"))},2e3),this.log("Ping monitor started"))}stopPingMonitor(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null,this.log("Ping monitor stopped"))}log(e,t){this.options.debug&&(t!==void 0?console.warn(`[SocketIOClient] ${e}`,t):console.warn(`[SocketIOClient] ${e}`))}};zf(Uw,"SocketIOClient");var bE=Uw,Aw=class{constructor(e){mt(this,"signalingSocket",null),mt(this,"peerConnection",null),mt(this,"reliableChannel",null),mt(this,"unreliableChannel",null),mt(this,"options"),mt(this,"_state",yt.Disconnected),mt(this,"p2pOnly",!0),mt(this,"eventHandlers",new Map),mt(this,"bridgeHandlers",new Map),mt(this,"chunkBuffers",new Map),mt(this,"remotePeerId",null),mt(this,"latency",0),mt(this,"retryCount",0),mt(this,"pingTimestamp",0),mt(this,"pingInterval",null),mt(this,"statsInterval",null);let t=e.sessionId?"https://signal.utsp.dev":void 0,n=e.url||t;if(!n)throw new Error("WebRTCClient: URL required (or sessionId for public relay)");this.options={url:n,autoReconnect:e.autoReconnect??!0,reconnectDelay:e.reconnectDelay??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,timeout:e.timeout??5e3,auth:e.auth??{},iceServers:e.iceServers??[{urls:"stun:stun.l.google.com:19302"}],debug:e.debug??!1,signalingPath:e.signalingPath??(e.sessionId?"/socket.io":"/utsp-signal"),sessionId:e.sessionId,p2pOnly:e.p2pOnly??!0},this.p2pOnly=this.options.p2pOnly??!0,this.on("bridge",i=>{if(!i||!i.channel)return;let s=i.data;if(typeof s=="string")try{s=JSON.parse(s)}catch{}let o=this.bridgeHandlers.get(i.channel);o&&o.forEach(a=>a(s))})}get state(){return this._state}isConnected(){return this._state===yt.Connected}async connect(){if(!(this._state===yt.Connected||this._state===yt.Connecting))return this._state=yt.Connecting,this.log("Connecting via WebRTC..."),new Promise((e,t)=>{this.signalingSocket=ua(this.options.url,{path:this.options.signalingPath,auth:this.options.auth,reconnection:this.options.autoReconnect,reconnectionDelay:this.options.reconnectDelay,reconnectionAttempts:this.options.maxReconnectAttempts,transports:["websocket","polling"]}),this.options.sessionId?(this.log(`Connecting via Public Relay to session: ${this.options.sessionId}`),this.signalingSocket.on("connect",()=>{this.log("Connected to Relay"),this.signalingSocket.emit("join-session",this.options.sessionId)}),this.signalingSocket.on("disconnect",i=>{this.warn(`Relay signaled disconnect: ${i}`)}),this.signalingSocket.on("signal",({from:i,type:s,data:o})=>{this.remotePeerId=i,s==="rtc:offer"?(this.log("Received RTC Offer via Relay"),this.handleOffer(o)):s==="rtc:candidate"&&this.peerConnection&&(this.log("Received ICE Candidate via Relay"),this.peerConnection.addIceCandidate(o).catch(a=>this.error("ICE Error",a)))})):(this.signalingSocket.on("connect",()=>{this.log("Signaling connected")}),this.signalingSocket.on("rtc:offer",async i=>{this.log("Received RTC Offer"),await this.handleOffer(i)}),this.signalingSocket.on("rtc:candidate",i=>{var o;let s=this.parseCandidateType(i.candidate);if(this.p2pOnly&&s==="relay"){this.warn("Strict P2P: Dropping received RELAY candidate");return}this.log(`Received ICE Candidate (${s})`),(o=this.peerConnection)==null||o.addIceCandidate(new RTCIceCandidate(i))})),this.signalingSocket.on("connect_error",i=>{this.error("Signaling connection error",i),this.signalingSocket&&!this.signalingSocket.active&&(this._state=yt.Error,t(i))}),this.signalingSocket.on("disconnect",()=>{this.log("Signaling disconnected"),this._state===yt.Connecting&&this.disconnect()}),this.signalingSocket.onAny((i,...s)=>{i.startsWith("rtc:")||i==="signal"||this.handleEvent(i,s[0])});let n=setTimeout(()=>{this._state!==yt.Connected&&(this.disconnect(),t(new Error("Connection timeout")))},this.options.timeout);this._connectResolve=()=>{clearTimeout(n),e()}})}async handleOffer(e){var t,n;this.peerConnection&&this.peerConnection.close(),this.peerConnection=new RTCPeerConnection({iceServers:this.options.iceServers}),this.setupPeerEvents();try{let i=this.p2pOnly?this.stripRelayFromSDP(e.sdp||""):e.sdp;await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:i}));let s=await this.peerConnection.createAnswer(),o=this.p2pOnly?this.stripRelayFromSDP(s.sdp||""):s.sdp||"";await this.peerConnection.setLocalDescription({type:"answer",sdp:o}),this.options.sessionId&&this.remotePeerId?(t=this.signalingSocket)==null||t.emit("signal",{target:this.remotePeerId,type:"rtc:answer",data:s}):(this.log("Sending RTC Answer"),(n=this.signalingSocket)==null||n.emit("rtc:answer",s))}catch(i){this.error("WebRTC Negotiation failed",i),this.disconnect()}}setupPeerEvents(){this.peerConnection&&(this.peerConnection.onicecandidate=e=>{var t,n;if(e.candidate)if(this.options.sessionId&&this.remotePeerId)(t=this.signalingSocket)==null||t.emit("signal",{target:this.remotePeerId,type:"rtc:candidate",data:e.candidate});else{let i=this.parseCandidateType(e.candidate.candidate);if(this.p2pOnly&&i==="relay"){this.warn("Strict P2P: Not sending RELAY candidate");return}this.log(`Sending ICE Candidate (${i})`),(n=this.signalingSocket)==null||n.emit("rtc:candidate",e.candidate)}},this.peerConnection.ondatachannel=e=>{let t=e.channel;this.log(`DataChannel received: ${t.label}`),t.label==="reliable"?(this.reliableChannel=t,this.setupChannel(t),t.onopen=()=>{this.log("Reliable Channel OPEN"),this._state=yt.Connected,this.startPingMonitor(),this.startStatsMonitor(),this._connectResolve&&this._connectResolve()}):t.label==="unreliable"&&(this.log("Unreliable Channel RECEIVED"),this.unreliableChannel=t,this.setupChannel(t))},this.peerConnection.onconnectionstatechange=()=>{var t,n;this.log(`Connection State: ${(t=this.peerConnection)==null?void 0:t.connectionState}`);let e=(n=this.peerConnection)==null?void 0:n.connectionState;e==="disconnected"||e==="failed"?this.options.autoReconnect&&this.retryCount<this.options.maxReconnectAttempts?(this.log(`WebRTC lost. Retrying in ${this.options.reconnectDelay}ms... (Attempt ${this.retryCount+1}/${this.options.maxReconnectAttempts})`),this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null),this.retryCount++,setTimeout(()=>{this._state=yt.Disconnected,this.connect().catch(i=>this.error("Reconnection failed",i))},this.options.reconnectDelay*Math.pow(1.5,this.retryCount))):this.disconnect():e==="connected"&&(this.retryCount=0)})}parsePayload(e){return JSON.parse(e,(t,n)=>{if(n&&typeof n=="object"&&n._b64){let i=atob(n._b64),s=new Uint8Array(i.length);for(let o=0;o<i.length;o++)s[o]=i.charCodeAt(o);return s}return n})}setupChannel(e){e.binaryType="arraybuffer",e.onmessage=t=>{let n=t.data;if(e.label,n instanceof ArrayBuffer){try{let i=new DataView(n),s=i.getUint8(0);if(s===255){let c=i.getUint8(1),d=new Uint8Array(n,2);this.handleEvent(c,d);return}let o=s,a=new Uint8Array(n,1,o),l=new TextDecoder("utf-8").decode(a),u=new Uint8Array(n,1+o);this.handleEvent(l,u)}catch(i){this.error("Failed to parse binary packet",i)}return}try{let[i,s]=this.parsePayload(n);this.handleEvent(i,s)}catch{}}}disconnect(){this._state=yt.Disconnected,this.reliableChannel&&this.reliableChannel.close(),this.unreliableChannel&&this.unreliableChannel.close(),this.peerConnection&&this.peerConnection.close(),this.signalingSocket&&this.signalingSocket.disconnect(),this.stopPingMonitor(),this.stopStatsMonitor(),this.reliableChannel=null,this.unreliableChannel=null,this.peerConnection=null,this.signalingSocket=null}preparePayload(e,t){let n=t;return t instanceof Uint8Array||t instanceof Int8Array||t instanceof Uint16Array||t instanceof Int16Array||t instanceof Uint32Array||t instanceof Int32Array||t instanceof Float32Array||t instanceof Float64Array?n=Array.from(t):t instanceof ArrayBuffer&&(n=Array.from(new Uint8Array(t))),JSON.stringify([e,n])}send(e,t){var n;if(((n=this.reliableChannel)==null?void 0:n.readyState)==="open"){if(typeof e=="number"&&(t instanceof Uint8Array||t instanceof ArrayBuffer)){let s=new Uint8Array(2);s[0]=255,s[1]=e;let o=t instanceof ArrayBuffer?new Uint8Array(t):t,a=new Uint8Array(s.length+o.length);a.set(s),a.set(o,s.length),this.reliableChannel.send(a);return}if(typeof e=="number"){let s=this.preparePayload(String(e),t);this.reliableChannel.send(s);return}let i=this.preparePayload(e,t);this.reliableChannel.send(i)}}sendVolatile(e,t){var i;let n=((i=this.unreliableChannel)==null?void 0:i.readyState)==="open"?this.unreliableChannel:this.reliableChannel;if((n==null?void 0:n.readyState)==="open"){if(n.bufferedAmount>16*1024){this.warn(`Backpressure: Dropping volatile packet on ${n.label} (buffered: ${n.bufferedAmount} bytes)`);return}if(typeof e=="number"&&(t instanceof Uint8Array||t instanceof ArrayBuffer)){let o=new Uint8Array(2);o[0]=255,o[1]=e;let a=t instanceof ArrayBuffer?new Uint8Array(t):t,l=new Uint8Array(o.length+a.length);l.set(o),l.set(a,o.length),n.send(l);return}let s=this.preparePayload(String(e),t);n.send(s)}}request(e,t,n=5e3){return Promise.reject(new Error(`Request not implemented: ${e}`))}on(e,t){let n=String(e);this.eventHandlers.has(n)||this.eventHandlers.set(n,[]),this.eventHandlers.get(n).push(t)}off(e,t){let n=String(e),i=this.eventHandlers.get(n);if(i){let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}removeAllListeners(e){e?this.eventHandlers.delete(String(e)):this.eventHandlers.clear()}handleEvent(e,t){let n=String(e);if(n==="__ch:start"){let{id:s,count:o}=t;this.chunkBuffers.set(s,{count:o,parts:new Array(o),received:0});return}if(n==="__ch:part"){let{id:s,idx:o,chunk:a}=t,l=this.chunkBuffers.get(s);if(l&&(l.parts[o]=a,l.received++,l.received===l.count)){this.chunkBuffers.delete(s);try{let u=l.parts.join(""),[c,d]=this.parsePayload(u);this.handleEvent(c,d)}catch(u){this.error("Failed to reassemble chunked payload",u)}}return}let i=this.eventHandlers.get(n);i&&i.forEach(s=>s(t)),n==="pong"&&(this.latency=Date.now()-this.pingTimestamp,this.log(`Ping: ${this.latency}ms`))}startPingMonitor(){this.stopPingMonitor(),this.pingInterval=setInterval(()=>{this.isConnected()&&(this.pingTimestamp=Date.now(),this.send("ping",null))},2e3)}stopPingMonitor(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}getPing(){return this.latency}startStatsMonitor(){this.stopStatsMonitor(),this.statsInterval=setInterval(async()=>{if(!(!this.peerConnection||this._state!==yt.Connected))try{let e=await this.peerConnection.getStats(),t=null;if(e.forEach(n=>{if(n.type==="transport"){let i=n.selectedCandidatePairId;t=e.get?e.get(i):e[i]}}),t){let n=e,i=n.get?n.get(t.localCandidateId):n[t.localCandidateId],s=n.get?n.get(t.remoteCandidateId):n[t.remoteCandidateId];this.options.debug&&this.log(`RTC Stats: Connection=${t.state} RTT=${t.currentRoundTripTime?Math.round(t.currentRoundTripTime*1e3):"N/A"}ms Path=${(i==null?void 0:i.candidateType)||"?"}<->${(s==null?void 0:s.candidateType)||"?"}`),this.p2pOnly&&((i==null?void 0:i.candidateType)==="relay"||(s==null?void 0:s.candidateType)==="relay")&&(this.error("STRICT P2P VIOLATION: Detected relay path in stats. DISCONNECTING."),this.disconnect())}}catch(e){this.error("Failed to get RTC stats",e)}},5e3)}stopStatsMonitor(){this.statsInterval&&(clearInterval(this.statsInterval),this.statsInterval=null)}stripRelayFromSDP(e){return e.split(`
|
|
255
|
+
`,pk=class{constructor(e={}){H(this,"options"),H(this,"fgCache",[]),H(this,"bgCache",[]),H(this,"lastPalette",null),this.options={optimizeColors:e.optimizeColors??!0,includeHome:e.includeHome??!0,hideCursor:e.hideCursor??!0,includeNewlines:e.includeNewlines??!0,includeReset:e.includeReset??!0}}buildColorCache(e){if(this.lastPalette!==e){this.fgCache=new Array(e.length),this.bgCache=new Array(e.length);for(let t=0;t<e.length;t++){let n=e[t];this.fgCache[t]=`\x1B[38;2;${n.r};${n.g};${n.b}m`,this.bgCache[t]=`\x1B[48;2;${n.r};${n.g};${n.b}m`}this.lastPalette=e}}render(e){let{width:t,height:n,cells:i,palette:s}=e;this.buildColorCache(s);let o="";this.options.hideCursor&&(o+=tm),this.options.includeHome&&(o+=em);let a=-1,l=-1,u=this.options.optimizeColors,c=this.options.includeNewlines;for(let d=0;d<n;d++){let h=d*t;for(let f=0;f<t;f++){let p=i[h+f],m=p.fgColorIndex,S=p.bgColorIndex;u?(S!==l&&(o+=this.bgCache[S],l=S),m!==a&&(o+=this.fgCache[m],a=m)):(o+=this.bgCache[S],o+=this.fgCache[m]),o+=p.char||" "}c&&d<n-1&&(o+=fk)}return this.options.includeReset&&(o+=_c),o}renderRow(e,t){let{width:n,cells:i,palette:s}=e;this.buildColorCache(s);let o=`\x1B[${t+1};1H`,a=-1,l=-1,u=this.options.optimizeColors,c=t*n;for(let d=0;d<n;d++){let h=i[c+d],f=h.fgColorIndex,p=h.bgColorIndex;u?(p!==l&&(o+=this.bgCache[p],l=p),f!==a&&(o+=this.fgCache[f],a=f)):(o+=this.bgCache[p],o+=this.fgCache[f]),o+=h.char||" "}return this.options.includeReset&&(o+=_c),o}clear(){return dk+em}showCursor(){return hk}hideCursor(){return tm}reset(){return _c}moveTo(e,t){return`\x1B[${e+1};${t+1}H`}};Pr(pk,"TerminalANSI");function gk(r){let e=r.startsWith("#")?r.slice(1):r,t=e.length===3?e[0]+e[0]+e[1]+e[1]+e[2]+e[2]:e,n=parseInt(t,16);return{r:n>>16&255,g:n>>8&255,b:n&255,a:255}}Pr(gk,"hexToRGB");function mk(r){let e=r.r.toString(16).padStart(2,"0"),t=r.g.toString(16).padStart(2,"0"),n=r.b.toString(16).padStart(2,"0");return`#${e}${t}${n}`}Pr(mk,"rgbToHex");function yk(r,e){let t=[{r:0,g:0,b:0,a:255},{r:128,g:0,b:0,a:255},{r:0,g:128,b:0,a:255},{r:128,g:128,b:0,a:255},{r:0,g:0,b:128,a:255},{r:128,g:0,b:128,a:255},{r:0,g:128,b:128,a:255},{r:192,g:192,b:192,a:255},{r:128,g:128,b:128,a:255},{r:255,g:0,b:0,a:255},{r:0,g:255,b:0,a:255},{r:255,g:255,b:0,a:255},{r:0,g:0,b:255,a:255},{r:255,g:0,b:255,a:255},{r:0,g:255,b:255,a:255},{r:255,g:255,b:255,a:255}];for(;t.length<256;)t.push({r:128,g:128,b:128,a:255});let n=[];for(let i=0;i<e;i++)for(let s=0;s<r;s++)n.push({char:String.fromCharCode(65+(s+i)%26),fgColorIndex:15,bgColorIndex:(s+i)%16,fgEmission:0,bgEmission:0});return{id:0,width:r,height:e,cells:n,palette:t}}Pr(yk,"createTestRenderState");var ew=Object.defineProperty,vk=(r,e,t)=>e in r?ew(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wr=(r,e)=>ew(r,"name",{value:e,configurable:!0}),ke=(r,e,t)=>(vk(r,typeof e!="symbol"?e+"":e,t),t),wk=(r=>(r.KeyDown="keydown",r.KeyUp="keyup",r.MouseDown="mousedown",r.MouseUp="mouseup",r.MouseMove="mousemove",r.MouseWheel="mousewheel",r.TouchStart="touchstart",r.TouchEnd="touchend",r.TouchMove="touchmove",r.GamepadConnected="gamepadconnected",r.GamepadDisconnected="gamepaddisconnected",r.GamepadButton="gamepadbutton",r.GamepadAxis="gamepadaxis",r))(wk||{}),tw=class{constructor(e=window,t={}){ke(this,"isActive",!1),ke(this,"targetElement"),ke(this,"config"),ke(this,"callbacks",{}),this.targetElement=e,this.config={enabled:!0,preventDefault:!1,stopPropagation:!1,debug:!1,...t}}isListening(){return this.isActive}destroy(){this.stop(),this.clearCallbacks()}setCallbacks(e){typeof e=="object"&&e!==null&&Object.assign(this.callbacks,e)}clearCallbacks(){this.callbacks={}}getTargetElement(){return this.targetElement}enable(){this.config.enabled=!0,this.isActive||this.start()}disable(){this.config.enabled=!1,this.isActive&&this.stop()}isEnabled(){return this.config.enabled??!0}emit(e,...t){this.callbacks[e]&&this.callbacks[e].forEach(n=>{try{n(...t)}catch(i){this.config.debug&&console.error(`Error in ${e} callback:`,i)}})}log(...e){}};wr(tw,"BaseInputs");var Fa=tw;function Ck(r){return typeof r=="object"&&r!==null&&"start"in r&&"stop"in r&&"reset"in r&&"isListening"in r&&"destroy"in r}wr(Ck,"isInputs");var rw=class extends Fa{constructor(e=window,t={}){super(e,t),ke(this,"keys",{}),ke(this,"keyboardCallbacks",{}),ke(this,"textInputsThisFrame",[]),ke(this,"boundHandlers"),this.boundHandlers={keyDown:this.handleKeyDown.bind(this),keyUp:this.handleKeyUp.bind(this)}}start(){this.isActive||(this.targetElement.addEventListener("keydown",this.boundHandlers.keyDown),this.targetElement.addEventListener("keyup",this.boundHandlers.keyUp),this.isActive=!0)}stop(){this.isActive&&(this.targetElement.removeEventListener("keydown",this.boundHandlers.keyDown),this.targetElement.removeEventListener("keyup",this.boundHandlers.keyUp),this.isActive=!1)}reset(){this.keys={}}resetDelta(){}poll(){for(let e in this.keys)this.keys[e].justPressed=!1,this.keys[e].justReleased=!1;this.textInputsThisFrame=[]}getTextInputs(){return this.textInputsThisFrame}isKeyPressed(e){var t;return((t=this.keys[e])==null?void 0:t.pressed)||!1}isKeyJustPressed(e){var t;return((t=this.keys[e])==null?void 0:t.justPressed)||!1}isKeyJustReleased(e){var t;return((t=this.keys[e])==null?void 0:t.justReleased)||!1}getKeysPressed(){return Object.keys(this.keys).filter(e=>this.keys[e].pressed)}getKeysJustPressed(){return Object.keys(this.keys).filter(e=>this.keys[e].justPressed)}getKeysJustReleased(){return Object.keys(this.keys).filter(e=>this.keys[e].justReleased)}isAnyKeyPressed(){return Object.values(this.keys).some(e=>e.pressed)}setKeyboardCallbacks(e){this.keyboardCallbacks={...this.keyboardCallbacks,...e}}clearKeyboardCallbacks(){this.keyboardCallbacks={}}setCallbacks(e){this.isKeyboardCallbacks(e)&&this.setKeyboardCallbacks(e)}isKeyboardCallbacks(e){return typeof e=="object"&&e!==null&&("onKeyDown"in e||"onKeyUp"in e)}shouldAllowDefault(e,t){let n=/^F([1-9]|1[0-2])$/.test(e),i=(t.ctrlKey||t.metaKey)&&(e==="KeyT"||e==="KeyW"||e==="KeyR"||e==="KeyN"||e==="Tab");return n||i}handleKeyDown(e){var t,n;try{let i=e.code,s=this.shouldAllowDefault(i,e);this.config.preventDefault&&!s&&e.preventDefault(),this.config.stopPropagation&&!s&&e.stopPropagation(),this.keys[i]||(this.keys[i]={pressed:!1,justPressed:!1,justReleased:!1}),this.keys[i].pressed||(this.keys[i].justPressed=!0,(n=(t=this.keyboardCallbacks).onKeyDown)==null||n.call(t,i,e)),this.keys[i].pressed=!0,this.keys[i].justReleased=!1;let o=e.key;o.length===1&&!e.ctrlKey&&!e.metaKey&&this.textInputsThisFrame.push(o)}catch(i){console.error("Error in keyboard keydown handler:",i)}}handleKeyUp(e){var t,n;try{let i=e.code,s=this.shouldAllowDefault(i,e);this.config.preventDefault&&!s&&e.preventDefault(),this.config.stopPropagation&&!s&&e.stopPropagation(),this.keys[i]||(this.keys[i]={pressed:!1,justPressed:!1,justReleased:!1}),this.keys[i].pressed&&(this.keys[i].justReleased=!0,(n=(t=this.keyboardCallbacks).onKeyUp)==null||n.call(t,i,e)),this.keys[i].pressed=!1,this.keys[i].justPressed=!1}catch(i){console.error("Error in keyboard keyup handler:",i)}}};wr(rw,"KeyboardInputs");var nw=rw;function bk(r,e){let t=new nw(r);return e&&t.setCallbacks(e),t.start(),t}wr(bk,"useKeyboardInputs");var oh=class iw extends Fa{constructor(e=window,t={}){super(e,t),ke(this,"mouseButtons",{left:{pressed:!1,justPressed:!1,justReleased:!1},middle:{pressed:!1,justPressed:!1,justReleased:!1},right:{pressed:!1,justPressed:!1,justReleased:!1}}),ke(this,"mousePosition",Yt.zero()),ke(this,"mouseDelta",Yt.zero()),ke(this,"wheelDelta",0),ke(this,"mouseCallbacks",{}),ke(this,"boundHandlers"),this.boundHandlers={mouseDown:this.handleMouseDown.bind(this),mouseUp:this.handleMouseUp.bind(this),mouseMove:this.handleMouseMove.bind(this),wheel:this.handleWheel.bind(this),mouseEnter:this.handleMouseEnter.bind(this),mouseLeave:this.handleMouseLeave.bind(this),contextMenu:this.handleContextMenu.bind(this)}}start(){this.isActive||(this.targetElement.addEventListener("mousedown",this.boundHandlers.mouseDown),this.targetElement.addEventListener("mouseup",this.boundHandlers.mouseUp),this.targetElement.addEventListener("mousemove",this.boundHandlers.mouseMove),this.targetElement.addEventListener("wheel",this.boundHandlers.wheel),this.targetElement.addEventListener("mouseenter",this.boundHandlers.mouseEnter),this.targetElement.addEventListener("mouseleave",this.boundHandlers.mouseLeave),this.targetElement.addEventListener("contextmenu",this.boundHandlers.contextMenu),this.isActive=!0)}stop(){this.isActive&&(this.targetElement.removeEventListener("mousedown",this.boundHandlers.mouseDown),this.targetElement.removeEventListener("mouseup",this.boundHandlers.mouseUp),this.targetElement.removeEventListener("mousemove",this.boundHandlers.mouseMove),this.targetElement.removeEventListener("wheel",this.boundHandlers.wheel),this.targetElement.removeEventListener("mouseenter",this.boundHandlers.mouseEnter),this.targetElement.removeEventListener("mouseleave",this.boundHandlers.mouseLeave),this.targetElement.removeEventListener("contextmenu",this.boundHandlers.contextMenu),this.isActive=!1)}reset(){this.mouseButtons={left:{pressed:!1,justPressed:!1,justReleased:!1},middle:{pressed:!1,justPressed:!1,justReleased:!1},right:{pressed:!1,justPressed:!1,justReleased:!1}},this.mousePosition=Yt.zero(),this.mouseDelta=Yt.zero(),this.wheelDelta=0}poll(){this.mouseButtons.left.justPressed=!1,this.mouseButtons.left.justReleased=!1,this.mouseButtons.middle.justPressed=!1,this.mouseButtons.middle.justReleased=!1,this.mouseButtons.right.justPressed=!1,this.mouseButtons.right.justReleased=!1,this.resetDelta()}resetDelta(){this.mouseDelta=Yt.zero(),this.wheelDelta=0}isLeftMousePressed(){return this.mouseButtons.left.pressed}isLeftMouseJustPressed(){return this.mouseButtons.left.justPressed}isLeftMouseJustReleased(){return this.mouseButtons.left.justReleased}isRightMousePressed(){return this.mouseButtons.right.pressed}isRightMouseJustPressed(){return this.mouseButtons.right.justPressed}isRightMouseJustReleased(){return this.mouseButtons.right.justReleased}isMiddleMousePressed(){return this.mouseButtons.middle.pressed}isMiddleMouseJustPressed(){return this.mouseButtons.middle.justPressed}isMiddleMouseJustReleased(){return this.mouseButtons.middle.justReleased}getMousePosition(){return this.mousePosition.clone()}getMouseDelta(){return this.mouseDelta.clone()}getWheelDelta(){return this.wheelDelta}setMouseCallbacks(e){this.mouseCallbacks={...this.mouseCallbacks,...e}}clearMouseCallbacks(){this.mouseCallbacks={}}setCallbacks(e){this.isMouseCallbacks(e)&&this.setMouseCallbacks(e)}isMouseCallbacks(e){return typeof e=="object"&&e!==null&&("onMouseDown"in e||"onMouseUp"in e||"onMouseMove"in e||"onMouseWheel"in e||"onMouseEnter"in e||"onMouseLeave"in e)}getButtonByIndex(e){let t=iw.BUTTON_NAMES[e];return t?{state:this.mouseButtons[t],name:t}:null}handleMouseDown(e){var t,n;try{this.shouldPreventDefault(e)&&this.config.preventDefault&&e.preventDefault(),this.config.stopPropagation&&e.stopPropagation();let i=this.getButtonByIndex(e.button);i&&(i.state.pressed||(i.state.justPressed=!0),i.state.pressed=!0,i.state.justReleased=!1,(n=(t=this.mouseCallbacks).onMouseDown)==null||n.call(t,i.name,this.mousePosition,e))}catch(i){console.error("Error in mouse down handler:",i)}}handleMouseUp(e){var t,n;try{this.shouldPreventDefault(e)&&this.config.preventDefault&&e.preventDefault(),this.config.stopPropagation&&e.stopPropagation();let i=this.getButtonByIndex(e.button);i&&(i.state.pressed&&(i.state.justReleased=!0),i.state.pressed=!1,i.state.justPressed=!1,(n=(t=this.mouseCallbacks).onMouseUp)==null||n.call(t,i.name,this.mousePosition,e))}catch(i){console.error("Error in mouse up handler:",i)}}handleMouseMove(e){var t,n;try{this.shouldPreventDefault(e)&&this.config.preventDefault&&e.preventDefault(),this.config.stopPropagation&&e.stopPropagation();let i=new Yt(e.clientX,e.clientY);this.mouseDelta=i.subtract(this.mousePosition),this.mousePosition=i,(n=(t=this.mouseCallbacks).onMouseMove)==null||n.call(t,this.mousePosition,this.mouseDelta,e)}catch(i){console.error("Error in mouse move handler:",i)}}handleWheel(e){var t,n;try{this.shouldPreventDefault(e)&&this.config.preventDefault&&e.preventDefault(),this.config.stopPropagation&&e.stopPropagation(),this.wheelDelta=e.deltaY,(n=(t=this.mouseCallbacks).onMouseWheel)==null||n.call(t,this.wheelDelta,e)}catch(i){console.error("Error in mouse wheel handler:",i)}}handleMouseEnter(e){var t,n;try{(n=(t=this.mouseCallbacks).onMouseEnter)==null||n.call(t,e)}catch(i){console.error("Error in mouse enter handler:",i)}}handleMouseLeave(e){var t,n;try{(n=(t=this.mouseCallbacks).onMouseLeave)==null||n.call(t,e)}catch(i){console.error("Error in mouse leave handler:",i)}}handleContextMenu(e){try{this.isInteractiveSurfaceEvent(e)&&e.preventDefault(),this.config.stopPropagation&&e.stopPropagation()}catch(t){console.error("Error in context menu handler:",t)}}shouldPreventDefault(e){return this.isInteractiveSurfaceEvent(e)}isInteractiveSurfaceEvent(e){var n,i;let t=e.target;return t?(t.tagName??"").toLowerCase()==="canvas"||(((n=t.getAttribute)==null?void 0:n.call(t,"data-utsp-input-surface"))??"").toLowerCase()==="true"?!0:!!((i=t.closest)!=null&&i.call(t,'canvas,[data-utsp-input-surface="true"]')):!1}};wr(oh,"MouseInputs"),ke(oh,"BUTTON_NAMES",["left","middle","right"]);var sw=oh;function Sk(r,e){let t=new sw(r);return e&&t.setCallbacks(e),t.start(),t}wr(Sk,"useMouseInputs");var ow=class extends Fa{constructor(e=window,t={}){super(e,t),ke(this,"touches",new Map),ke(this,"nativeToInternal",new Map),ke(this,"mobileCallbacks",{}),ke(this,"mobileConfig"),ke(this,"maxTouches",10),ke(this,"lastLogTime",0),ke(this,"boundHandlers"),this.mobileConfig={targetElement:e,preventDefault:t.preventDefault??!1,passive:t.passive??!0,maxTouches:t.maxTouches??10,enabled:t.enabled??!0,debug:t.debug??!1,stopPropagation:t.stopPropagation??!1},this.maxTouches=this.mobileConfig.maxTouches,this.mobileConfig.preventDefault&&this.mobileConfig.passive&&(console.warn("[MobileInputs] passive=true prevents preventDefault() from working! Setting passive=false."),this.mobileConfig.passive=!1),this.boundHandlers={touchStart:this.handleTouchStart.bind(this),touchEnd:this.handleTouchEnd.bind(this),touchMove:this.handleTouchMove.bind(this),touchCancel:this.handleTouchCancel.bind(this),orientationChange:this.handleOrientationChange.bind(this)}}start(){if(this.isActive)return;let e={passive:!this.mobileConfig.preventDefault&&this.mobileConfig.passive};this.targetElement.addEventListener("touchstart",this.boundHandlers.touchStart,e),this.targetElement.addEventListener("touchend",this.boundHandlers.touchEnd,e),this.targetElement.addEventListener("touchmove",this.boundHandlers.touchMove,e),this.targetElement.addEventListener("touchcancel",this.boundHandlers.touchCancel,e),window.addEventListener("orientationchange",this.boundHandlers.orientationChange),this.isActive=!0}stop(){this.isActive&&(this.targetElement.removeEventListener("touchstart",this.boundHandlers.touchStart),this.targetElement.removeEventListener("touchend",this.boundHandlers.touchEnd),this.targetElement.removeEventListener("touchmove",this.boundHandlers.touchMove),this.targetElement.removeEventListener("touchcancel",this.boundHandlers.touchCancel),window.removeEventListener("orientationchange",this.boundHandlers.orientationChange),this.isActive=!1)}reset(){this.touches.clear(),this.nativeToInternal.clear()}resetDelta(){}poll(){let e=[];for(let[t,n]of this.touches.entries())n.justReleased&&(e.push(t),this.nativeToInternal.delete(n.nativeId)),n.justTouched=!1,n.justReleased=!1;for(let t of e)this.touches.delete(t)}isTouchActive(e){if(e<0||e>=this.maxTouches)return!1;let t=this.touches.get(e);return t?t.active:!1}getTouchPosition(e){if(e<0||e>=this.maxTouches)return null;let t=this.touches.get(e);return t?t.position.clone():null}getTouchStartPosition(e){if(e<0||e>=this.maxTouches)return null;let t=this.touches.get(e);return t?t.startPosition.clone():null}getTouchDelta(e){if(e<0||e>=this.maxTouches)return null;let t=this.touches.get(e);return t?t.position.subtract(t.startPosition):null}getTouchCount(){let e=0;for(let t of this.touches.values())t.active&&e++;return e}isTouchJustStarted(e){if(e<0||e>=this.maxTouches)return!1;let t=this.touches.get(e);return t?t.justTouched:!1}isTouchJustReleased(e){if(e<0||e>=this.maxTouches)return!1;let t=this.touches.get(e);return t?t.justReleased:!1}isAnyTouchJustStarted(){for(let e of this.touches.values())if(e.justTouched)return!0;return!1}isAnyTouchJustReleased(){for(let e of this.touches.values())if(e.justReleased)return!0;return!1}getJustReleasedTouches(){return Array.from(this.touches.values()).filter(e=>e.justReleased)}getAllTouches(){return Array.from(this.touches.values()).filter(e=>e.active)}setMobileCallbacks(e){this.mobileCallbacks={...this.mobileCallbacks,...e}}clearMobileCallbacks(){this.mobileCallbacks={}}setCallbacks(e){this.isMobileCallbacks(e)&&this.setMobileCallbacks(e)}isMobileCallbacks(e){return typeof e=="object"&&e!==null&&("onTouchStart"in e||"onTouchEnd"in e||"onTouchMove"in e||"onTouchCancel"in e||"onOrientationChange"in e)}handleTouchStart(e){var t,n;try{this.mobileConfig.preventDefault&&e.preventDefault();let i=Array.from(e.changedTouches),s=[];for(let o of i){if(this.touches.size>=this.maxTouches)break;let a=this.nativeToInternal.get(o.identifier);if(a!==void 0){let d=this.touches.get(a);if(d){let h=new Yt(o.clientX,o.clientY);d.position=h.clone(),d.startPosition=h.clone(),d.active=!0,d.justTouched=!0,d.justReleased=!1,s.push({...d})}continue}let l=-1;for(let d=0;d<this.maxTouches;d++)if(!this.touches.has(d)){l=d;break}if(l===-1)continue;let u=new Yt(o.clientX,o.clientY),c={id:l,nativeId:o.identifier,position:u.clone(),startPosition:u.clone(),active:!0,justTouched:!0,justReleased:!1};this.touches.set(l,c),this.nativeToInternal.set(o.identifier,l),s.push(c),console.warn(`👆 Touch START - ID: ${l}`)}(n=(t=this.mobileCallbacks).onTouchStart)==null||n.call(t,s,e)}catch(i){console.error("Error in touch start handler:",i)}}handleTouchEnd(e){var t,n;try{this.mobileConfig.preventDefault&&e.preventDefault();let i=Array.from(e.changedTouches),s=[];for(let o of i){let a=this.nativeToInternal.get(o.identifier);if(a!==void 0){let l=this.touches.get(a);l&&(l.justReleased=!0,l.justTouched=!1,l.active=!1,s.push({...l}),console.warn(`👇 Touch END - ID: ${a}`))}}(n=(t=this.mobileCallbacks).onTouchEnd)==null||n.call(t,s,e)}catch(i){console.error("Error in touch end handler:",i)}}handleTouchMove(e){var t,n;try{let i=Array.from(e.changedTouches);this.mobileConfig.debug&&(!this.lastLogTime||Date.now()-this.lastLogTime>200)&&(console.warn(`🔄 TouchMove event - ${i.length} touches changed`),this.lastLogTime=Date.now());for(let s of i){let o=this.nativeToInternal.get(s.identifier);if(o!==void 0){let a=this.touches.get(o);if(a){let l=a.position.clone();a.position=new Yt(s.clientX,s.clientY),this.mobileConfig.debug&&(!this.lastLogTime||Date.now()-this.lastLogTime>200)&&console.warn(`🔄 Updated touch ${a.id} (native ${s.identifier}) - ${l.x.toFixed(1)},${l.y.toFixed(1)} → ${s.clientX.toFixed(1)},${s.clientY.toFixed(1)}`)}}else this.mobileConfig.debug&&console.warn(`⚠️ Touch move for unknown native ID ${s.identifier}`)}(n=(t=this.mobileCallbacks).onTouchMove)==null||n.call(t,this.getAllTouches(),e)}catch(i){console.error("Error in touch move handler:",i)}}handleTouchCancel(e){var t,n;try{this.mobileConfig.preventDefault&&e.preventDefault();let i=[],s=Array.from(e.changedTouches);for(let o of s){let a=this.nativeToInternal.get(o.identifier);if(a!==void 0){let l=this.touches.get(a);l&&(l.justReleased=!0,l.justTouched=!1,l.active=!1,i.push({...l}),this.mobileConfig.debug&&console.warn(`❌ Touch CANCEL - ID: ${a}, nativeId: ${o.identifier}`))}}(n=(t=this.mobileCallbacks).onTouchCancel)==null||n.call(t,i,e)}catch(i){console.error("Error in touch cancel handler:",i)}}handleOrientationChange(e){var t,n;try{let i=(window.screen.orientation&&window.screen.orientation.angle)??window.orientation??0;(n=(t=this.mobileCallbacks).onOrientationChange)==null||n.call(t,i)}catch(i){console.error("Error in orientation change handler:",i)}}};wr(ow,"MobileInputs");var ah=ow;function xk(r,e,t){console.warn("[MobileInputs] useMobileInputs() is deprecated and causes memory leaks. Use useMemo + useEffect instead.");let n=new ah(r,t);return e&&n.setCallbacks(e),n.start(),n}wr(xk,"useMobileInputs");var aw=class extends Fa{constructor(e,t){super(t.targetElement,t),this.mobile=e,ke(this,"zones",[]),ke(this,"zoneState",new Map),ke(this,"gridWidth"),ke(this,"gridHeight"),ke(this,"rendererOffsets"),this.gridWidth=t.gridWidth,this.gridHeight=t.gridHeight,this.rendererOffsets=t.rendererOffsets??{offsetX:0,offsetY:0},t.zones&&this.setZones(t.zones)}start(){this.isActive=!0}stop(){this.isActive=!1}reset(){this.clearZones()}resetDelta(){}setLayout(e,t,n){this.gridWidth=e,this.gridHeight=t,n&&(this.rendererOffsets=n)}setZones(e){this.zones=e.filter(t=>t.id>=0&&t.id<=31),this.zoneState.clear();for(let t of this.zones)this.zoneState.set(t.id,{pressed:!1,justPressed:!1,justReleased:!1,lastX:t.x,lastY:t.y})}clearZones(){this.zones=[],this.zoneState.clear()}updateFromTouches(){if(this.zones.length===0)return;let e=this.targetElement,t=e.getBoundingClientRect(),{renderWidth:n,renderHeight:i,offsetX:s,offsetY:o}=this.calculateRenderMetrics(e,t),a=n/this.gridWidth,l=i/this.gridHeight,u=new Map,c=new Map,d=this.mobile.getAllTouches();for(let h of d){let f=h.position.x-t.left-s,p=h.position.y-t.top-o,m=Math.floor(f/a),S=Math.floor(p/l);for(let w of this.zones)this.isInsideZone(m,S,w)&&(u.set(w.id,(u.get(w.id)??0)+1),c.set(w.id,{x:Math.max(w.x,Math.min(w.x+w.width-1,m)),y:Math.max(w.y,Math.min(w.y+w.height-1,S))}))}for(let h of this.zones){let f=this.zoneState.get(h.id)??{pressed:!1,justPressed:!1,justReleased:!1,lastX:h.x,lastY:h.y},p=(u.get(h.id)??0)>0;p&&!f.pressed&&(f.justPressed=!0),!p&&f.pressed&&(f.justReleased=!0),f.pressed=p;let m=c.get(h.id);m&&(f.lastX=m.x,f.lastY=m.y),this.zoneState.set(h.id,f)}}poll(){for(let e of this.zoneState.values())e.justPressed=!1,e.justReleased=!1}isZonePressed(e){var t;return((t=this.zoneState.get(e))==null?void 0:t.pressed)??!1}isZoneJustPressed(e){var t;return((t=this.zoneState.get(e))==null?void 0:t.justPressed)??!1}isZoneJustReleased(e){var t;return((t=this.zoneState.get(e))==null?void 0:t.justReleased)??!1}getZoneAxis(e,t){let n=this.zoneState.get(e);if(!n||!n.pressed)return 0;let i=this.zones.find(s=>s.id===e);if(!i)return 0;if(t==="x"){let s=(i.width-1)/2,o=i.x+s;return s>0?(n.lastX-o)/s:0}else{let s=(i.height-1)/2,o=i.y+s;return s>0?(n.lastY-o)/s:0}}getZonePosition(e){let t=this.zoneState.get(e);return t?{x:t.lastX,y:t.lastY}:null}calculateRenderMetrics(e,t){let n=e.width,i=e.height,s=n/i,o=t.width/t.height,a,l,u,c;s>o?(a=t.width,l=t.width/s,u=0,c=(t.height-l)/2):(a=t.height*s,l=t.height,u=(t.width-a)/2,c=0);let d=this.rendererOffsets;return u+=d.offsetX,c+=d.offsetY,a-=d.offsetX*2,l-=d.offsetY*2,{renderWidth:a,renderHeight:l,offsetX:u,offsetY:c}}isInsideZone(e,t,n){return e>=n.x&&e<n.x+n.width&&t>=n.y&&t<n.y+n.height}};wr(aw,"TouchZoneInputs");var rm=aw,wn={tap:10,mediumTap:25,heavyTap:50,success:[30,50,30],error:[50,30,50,30,50],warning:[100],selection:5,impactLight:15,impactMedium:30,impactHeavy:50,notification:[100,100,100,100,100]},lw=class{constructor(e={}){ke(this,"config"),ke(this,"supported",!1),ke(this,"userActivated",!1),this.config={enabled:e.enabled??!0,debug:e.debug??!1,intensity:Math.max(0,Math.min(1,e.intensity??1))},this.supported=typeof navigator<"u"&&"vibrate"in navigator,this.config.debug&&console.log(`[MobileVibration] Vibration API supported: ${this.supported}`)}isSupported(){return this.supported}isEnabled(){return this.config.enabled&&this.supported}setEnabled(e){this.config.enabled=e,this.config.debug&&console.log(`[MobileVibration] Enabled: ${e}`)}setIntensity(e){this.config.intensity=Math.max(0,Math.min(1,e)),this.config.debug&&console.log(`[MobileVibration] Intensity set to: ${this.config.intensity}`)}getIntensity(){return this.config.intensity}vibrate(e){if(!this.isEnabled())return!1;try{let t=this.scalePattern(e),n=typeof t=="number"?t:[...t],i=navigator.vibrate(n);return this.config.debug&&console.log(`[MobileVibration] Vibrate: ${JSON.stringify(t)} -> ${i}`),i&&(this.userActivated=!0),i}catch(t){return this.config.debug&&console.error("[MobileVibration] Vibration failed:",t),!1}}cancel(){this.supported&&(navigator.vibrate(0),this.config.debug&&console.log("[MobileVibration] Vibration cancelled"))}hasUserActivation(){return this.userActivated}tap(){return this.vibrate(wn.tap)}mediumTap(){return this.vibrate(wn.mediumTap)}heavyTap(){return this.vibrate(wn.heavyTap)}success(){return this.vibrate(wn.success)}error(){return this.vibrate(wn.error)}warning(){return this.vibrate(wn.warning)}selection(){return this.vibrate(wn.selection)}impactLight(){return this.vibrate(wn.impactLight)}impactMedium(){return this.vibrate(wn.impactMedium)}impactHeavy(){return this.vibrate(wn.impactHeavy)}notification(){return this.vibrate(wn.notification)}scalePattern(e){return this.config.intensity===1?e:typeof e=="number"?Math.round(e*this.config.intensity):e.map((t,n)=>n%2===0?Math.round(t*this.config.intensity):t)}};wr(lw,"MobileVibration");var Uf=lw,$c=null;function Ik(){return $c||($c=new Uf),$c}wr(Ik,"getMobileVibration");var kk=.01,uw=class extends Fa{constructor(e={}){super(window,e),ke(this,"gamepads",new Map),ke(this,"previousGamepads",new Map),ke(this,"gamepadCallbacks",{}),ke(this,"gamepadConfig"),ke(this,"pollingIntervalId",null),ke(this,"rafId",null),ke(this,"boundHandlers"),ke(this,"vibrationPresets",{tap:{duration:50,strongMagnitude:.3,weakMagnitude:.5},impact:{duration:100,strongMagnitude:.7,weakMagnitude:.3},heavy:{duration:200,strongMagnitude:1,weakMagnitude:.2},success:{duration:150,strongMagnitude:.4,weakMagnitude:.6},error:{duration:300,strongMagnitude:.8,weakMagnitude:.4},explosion:{duration:400,strongMagnitude:1,weakMagnitude:.8},engine:{duration:1e3,strongMagnitude:.5,weakMagnitude:.2},heartbeat:{duration:100,strongMagnitude:.6,weakMagnitude:.1}}),this.gamepadConfig={targetElement:window,maxGamepads:e.maxGamepads??4,axisDeadzone:e.axisDeadzone??.1,pollingInterval:e.pollingInterval??16,autoPolling:e.autoPolling??!0,enabled:e.enabled??!0,debug:e.debug??!1,preventDefault:e.preventDefault??!1,stopPropagation:e.stopPropagation??!1},this.boundHandlers={connected:this.handleGamepadConnected.bind(this),disconnected:this.handleGamepadDisconnected.bind(this)}}start(){this.isActive||(window.addEventListener("gamepadconnected",this.boundHandlers.connected),window.addEventListener("gamepaddisconnected",this.boundHandlers.disconnected),this.gamepadConfig.autoPolling&&this.startPolling(),this.isActive=!0,this.log("GamepadInputs started"))}stop(){this.isActive&&(window.removeEventListener("gamepadconnected",this.boundHandlers.connected),window.removeEventListener("gamepaddisconnected",this.boundHandlers.disconnected),this.stopPolling(),this.isActive=!1,this.log("GamepadInputs stopped"))}reset(){this.gamepads.clear(),this.previousGamepads.clear()}resetDelta(){this.previousGamepads.clear(),this.gamepads.forEach((e,t)=>{this.previousGamepads.set(t,this.cloneGamepadState(e))})}startPolling(){if(this.pollingIntervalId!==null||this.rafId!==null)return;let e=wr(()=>{this.poll(),this.rafId=requestAnimationFrame(e)},"poll");this.rafId=requestAnimationFrame(e),this.log("Polling started")}stopPolling(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.pollingIntervalId!==null&&(clearInterval(this.pollingIntervalId),this.pollingIntervalId=null),this.log("Polling stopped")}poll(){let e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t<e.length&&t<this.gamepadConfig.maxGamepads;t++){let n=e[t];n&&this.updateGamepadState(n)}}getConnectedGamepadCount(){return this.gamepads.size}isGamepadConnected(e){return this.gamepads.has(e)&&this.gamepads.get(e).connected}getGamepadState(e){return this.gamepads.get(e)||null}getAllGamepads(){return Array.from(this.gamepads.values()).filter(e=>e.connected)}isButtonPressed(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid gamepadIndex: ${e}. Must be a non-negative integer.`);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid buttonIndex: ${t}. Must be a non-negative integer.`);let n=this.gamepads.get(e);return!n||!n.connected||t>=n.buttons.length?!1:n.buttons[t].pressed}isButtonJustPressed(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid gamepadIndex: ${e}. Must be a non-negative integer.`);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid buttonIndex: ${t}. Must be a non-negative integer.`);let n=this.gamepads.get(e);return!n||!n.connected||t>=n.buttons.length?!1:n.buttons[t].justPressed}isButtonJustReleased(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid gamepadIndex: ${e}. Must be a non-negative integer.`);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid buttonIndex: ${t}. Must be a non-negative integer.`);let n=this.gamepads.get(e);return!n||!n.connected||t>=n.buttons.length?!1:n.buttons[t].justReleased}getButtonValue(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid gamepadIndex: ${e}. Must be a non-negative integer.`);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid buttonIndex: ${t}. Must be a non-negative integer.`);let n=this.gamepads.get(e);return!n||!n.connected||t>=n.buttons.length?0:n.buttons[t].value}getAxis(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid gamepadIndex: ${e}. Must be a non-negative integer.`);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid axisIndex: ${t}. Must be a non-negative integer.`);let n=this.gamepads.get(e);if(!n||!n.connected||t>=n.axes.length)return 0;let i=n.axes[t];return this.applyDeadzone(i)}getAxisRaw(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`Invalid gamepadIndex: ${e}. Must be a non-negative integer.`);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid axisIndex: ${t}. Must be a non-negative integer.`);let n=this.gamepads.get(e);return!n||!n.connected||t>=n.axes.length?0:n.axes[t]}getLeftStick(e){return{x:this.getAxis(e,0),y:this.getAxis(e,1)}}getRightStick(e){return{x:this.getAxis(e,2),y:this.getAxis(e,3)}}supportsVibration(e){let t=this.getNativeGamepad(e);if(!t)return!1;let n=t.vibrationActuator;if(n&&typeof n.playEffect=="function")return!0;let i=t.hapticActuators;return!!(i&&i.length>0)}async vibrate(e,t){let n=this.getNativeGamepad(e);if(!n)return this.log(`Vibrate failed: gamepad ${e} not found`),!1;let{duration:i,strongMagnitude:s=1,weakMagnitude:o=.5,startDelay:a=0}=t;try{let l=n.vibrationActuator;if(l&&typeof l.playEffect=="function"){let c=await l.playEffect("dual-rumble",{startDelay:a,duration:i,strongMagnitude:Math.min(1,Math.max(0,s)),weakMagnitude:Math.min(1,Math.max(0,o))});return this.log(`Vibration effect result: ${c}`),c==="complete"}let u=n.hapticActuators;if(u&&u.length>0){let c=Math.max(s,o);return await u[0].pulse(c,i),!0}return this.log(`Vibrate failed: gamepad ${e} does not support vibration`),!1}catch(l){return this.log("Vibrate error:",l),!1}}async stopVibration(e){let t=this.getNativeGamepad(e);if(!t)return!1;try{let n=t.vibrationActuator;return n&&typeof n.reset=="function"?(await n.reset(),!0):n&&typeof n.playEffect=="function"?(await n.playEffect("dual-rumble",{duration:0,strongMagnitude:0,weakMagnitude:0}),!0):!1}catch(n){return this.log("Stop vibration error:",n),!1}}async stopAllVibrations(){let e=[];for(let[t]of this.gamepads)e.push(this.stopVibration(t));await Promise.all(e)}async vibrateAll(e){let t=[];for(let[n]of this.gamepads)t.push(this.vibrate(n,e));await Promise.all(t)}async vibratePreset(e,t){let n=this.vibrationPresets[t];return n?this.vibrate(e,n):(this.log(`Unknown vibration preset: ${t}`),!1)}getNativeGamepad(e){return(navigator.getGamepads?navigator.getGamepads():[])[e]||null}setGamepadCallbacks(e){this.gamepadCallbacks={...this.gamepadCallbacks,...e}}clearGamepadCallbacks(){this.gamepadCallbacks={}}setCallbacks(e){this.isGamepadCallbacks(e)&&this.setGamepadCallbacks(e)}isGamepadCallbacks(e){return typeof e=="object"&&e!==null&&("onGamepadConnected"in e||"onGamepadDisconnected"in e||"onButtonDown"in e||"onButtonUp"in e||"onAxisMove"in e)}updateGamepadState(e){let t=this.gamepads.get(e.index),n=Array.from(e.buttons).map((o,a)=>{let l=t==null?void 0:t.buttons[a],u=o.pressed,c=(l==null?void 0:l.pressed)??!1;return{pressed:u,justPressed:u&&!c,justReleased:!u&&c,value:o.value,touched:o.touched??!1}}),i=Array.from(e.axes),s={id:e.id,index:e.index,connected:e.connected,buttons:n,axes:i,timestamp:e.timestamp,mapping:e.mapping};this.gamepads.set(e.index,s),this.triggerCallbacks(s,t)}triggerCallbacks(e,t){try{e.buttons.forEach((n,i)=>{var s,o,a,l;n.justPressed&&((o=(s=this.gamepadCallbacks).onButtonDown)==null||o.call(s,e.index,i,n.value)),n.justReleased&&((l=(a=this.gamepadCallbacks).onButtonUp)==null||l.call(a,e.index,i))}),e.axes.forEach((n,i)=>{var l,u;let s=(t==null?void 0:t.axes[i])??0,o=this.applyDeadzone(n),a=this.applyDeadzone(s);Math.abs(o-a)>kk&&((u=(l=this.gamepadCallbacks).onAxisMove)==null||u.call(l,e.index,i,o))})}catch(n){this.log("Error in gamepad callbacks:",n)}}handleGamepadConnected(e){var t,n;try{this.log(`Gamepad connected: ${e.gamepad.id} at index ${e.gamepad.index}`);let i={id:e.gamepad.id,index:e.gamepad.index,connected:!0,buttons:Array.from(e.gamepad.buttons).map(s=>({pressed:s.pressed,justPressed:!1,justReleased:!1,value:s.value,touched:s.touched??!1})),axes:Array.from(e.gamepad.axes),timestamp:e.gamepad.timestamp,mapping:e.gamepad.mapping};this.gamepads.set(e.gamepad.index,i),(n=(t=this.gamepadCallbacks).onGamepadConnected)==null||n.call(t,i)}catch(i){this.log("Error handling gamepad connected:",i)}}handleGamepadDisconnected(e){var t,n;try{this.log(`Gamepad disconnected at index ${e.gamepad.index}`),this.gamepads.delete(e.gamepad.index),this.previousGamepads.delete(e.gamepad.index),(n=(t=this.gamepadCallbacks).onGamepadDisconnected)==null||n.call(t,e.gamepad.index)}catch(i){this.log("Error handling gamepad disconnected:",i)}}applyDeadzone(e){let t=this.gamepadConfig.axisDeadzone;return Math.abs(e)<t?0:(e>0?1:-1)*((Math.abs(e)-t)/(1-t))}cloneGamepadState(e){return{...e,buttons:e.buttons.map(t=>({...t})),axes:[...e.axes]}}};wr(uw,"GamepadInputs");var cw=uw;function Ek(r,e){let t=new cw(e);return r&&t.setGamepadCallbacks(r),t.start(),t}wr(Ek,"useGamepadInputs");var dw=class{constructor(e={}){ke(this,"keyboard",null),ke(this,"mouse",null),ke(this,"gamepad",null),ke(this,"mobile",null),ke(this,"touchZones",null),ke(this,"config"),this.config={enableKeyboardMouse:e.enableKeyboardMouse??!0,enableGamepad:e.enableGamepad??!0,enableMobile:e.enableMobile??!1,targetElement:e.targetElement??window,mobileTargetElement:e.mobileTargetElement??e.targetElement??window,debug:e.debug??!1,keyboardConfig:{preventDefault:!1,stopPropagation:!1,...e.keyboardConfig},mouseConfig:{preventDefault:!1,stopPropagation:!1,...e.mouseConfig},mobileConfig:{preventDefault:!0,passive:!1,maxTouches:10,...e.mobileConfig},enableTouchZones:e.enableTouchZones??!1,touchZoneConfig:e.touchZoneConfig??{gridWidth:0,gridHeight:0}},this.initialize()}initialize(){var e,t,n,i,s,o,a,l,u;if(this.config.enableKeyboardMouse&&(this.keyboard=new nw(this.config.targetElement,{preventDefault:((e=this.config.keyboardConfig)==null?void 0:e.preventDefault)??!1,stopPropagation:((t=this.config.keyboardConfig)==null?void 0:t.stopPropagation)??!1,debug:this.config.debug}),this.keyboard.start(),this.mouse=new sw(this.config.targetElement,{preventDefault:((n=this.config.mouseConfig)==null?void 0:n.preventDefault)??!1,stopPropagation:((i=this.config.mouseConfig)==null?void 0:i.stopPropagation)??!1,debug:this.config.debug}),this.mouse.start(),this.log("Keyboard/Mouse initialized")),this.config.enableGamepad&&(this.gamepad=new cw({debug:this.config.debug}),this.gamepad.start(),this.log("Gamepad initialized")),this.config.enableMobile&&(this.config.mobileTargetElement?(this.mobile=new ah(this.config.mobileTargetElement,this.config.mobileConfig),this.mobile.start(),this.log("Mobile/Touch initialized")):this.warn("Mobile input enabled but no canvas provided - mobile input will be disabled until setMobileTarget() is called")),this.config.enableTouchZones){let c=((s=this.config.touchZoneConfig)==null?void 0:s.targetElement)??this.config.mobileTargetElement;if(!c||!c.getBoundingClientRect)this.warn("Touch zones enabled but no canvas HTMLElement provided - touch zones disabled");else if(!this.mobile)this.warn("Touch zones require mobile input to be enabled - touch zones disabled");else{let d={targetElement:c,gridWidth:((o=this.config.touchZoneConfig)==null?void 0:o.gridWidth)??0,gridHeight:((a=this.config.touchZoneConfig)==null?void 0:a.gridHeight)??0,rendererOffsets:(l=this.config.touchZoneConfig)==null?void 0:l.rendererOffsets,zones:(u=this.config.touchZoneConfig)==null?void 0:u.zones,enabled:!0,debug:this.config.debug};this.disableSystemLongPressHaptics(c),this.touchZones=new rm(this.mobile,d),this.log("Touch zones initialized")}}}getButton(e,t){if(!aa({device:e,input:t}))return this.warn(`Input ${t} on device ${e} is not a button`),!1;switch(e){case ce.Keyboard:return this.getKeyboardButton(t);case ce.Mouse:return this.getMouseButton(t);case ce.Gamepad:return this.getGamepadButton(t);case ce.Touch:return this.getTouchButton(t);case ce.TouchZone:return this.getTouchZoneButton(t);default:return this.warn(`Unknown device type: ${e}`),!1}}getButtonJustPressed(e,t){if(!aa({device:e,input:t}))return this.warn(`Input ${t} on device ${e} is not a button`),!1;switch(e){case ce.Keyboard:return this.getKeyboardButtonJustPressed(t);case ce.Mouse:return this.getMouseButtonJustPressed(t);case ce.Gamepad:return this.getGamepadButtonJustPressed(t);case ce.Touch:return this.getTouchButtonJustPressed(t);case ce.TouchZone:return this.getTouchZoneButtonJustPressed(t);default:return this.warn(`Unknown device type: ${e}`),!1}}getButtonJustReleased(e,t){if(!aa({device:e,input:t}))return this.warn(`Input ${t} on device ${e} is not a button`),!1;switch(e){case ce.Keyboard:return this.getKeyboardButtonJustReleased(t);case ce.Mouse:return this.getMouseButtonJustReleased(t);case ce.Gamepad:return this.getGamepadButtonJustReleased(t);case ce.Touch:return this.getTouchButtonJustReleased(t);case ce.TouchZone:return this.getTouchZoneButtonJustReleased(t);default:return this.warn(`Unknown device type: ${e}`),!1}}getAxis(e,t){if(!I1({device:e,input:t}))return this.warn(`Input ${t} on device ${e} is not an axis`),0;switch(e){case ce.Keyboard:return this.warn("Keyboard does not have axis inputs"),0;case ce.Mouse:return this.getMouseAxis(t);case ce.Gamepad:return this.getGamepadAxis(t);case ce.Touch:return this.getTouchAxis(t);case ce.TouchZone:return this.getTouchZoneAxis(t);default:return this.warn(`Unknown device type: ${e}`),0}}isLeftMousePressed(){return this.mouse?this.mouse.isLeftMousePressed():!1}getKeyboardButton(e){if(!this.keyboard)return!1;let t=Ai[e];return this.keyboard.isKeyPressed(t)}getKeyboardButtonJustPressed(e){if(!this.keyboard)return!1;let t=Ai[e];return this.keyboard.isKeyJustPressed(t)}getKeyboardButtonJustReleased(e){if(!this.keyboard)return!1;let t=Ai[e];return this.keyboard.isKeyJustReleased(t)}getMouseButton(e){if(!this.mouse)return!1;switch(e){case Nt.LeftButton:return this.mouse.isLeftMousePressed();case Nt.RightButton:return this.mouse.isRightMousePressed();case Nt.MiddleButton:return this.mouse.isMiddleMousePressed();default:return!1}}getMouseButtonJustPressed(e){if(!this.mouse)return!1;switch(e){case Nt.LeftButton:return this.mouse.isLeftMouseJustPressed();case Nt.RightButton:return this.mouse.isRightMouseJustPressed();case Nt.MiddleButton:return this.mouse.isMiddleMouseJustPressed();default:return!1}}getMouseButtonJustReleased(e){if(!this.mouse)return!1;switch(e){case Nt.LeftButton:return this.mouse.isLeftMouseJustReleased();case Nt.RightButton:return this.mouse.isRightMouseJustReleased();case Nt.MiddleButton:return this.mouse.isMiddleMouseJustReleased();default:return!1}}getGamepadButton(e){return!this.gamepad||e>=100?!1:this.gamepad.isButtonPressed(0,e)}getGamepadButtonJustPressed(e){return!this.gamepad||e>=100?!1:this.gamepad.isButtonJustPressed(0,e)}getGamepadButtonJustReleased(e){return!this.gamepad||e>=100?!1:this.gamepad.isButtonJustReleased(0,e)}getTouchButton(e){var t,n;return this.mobile?e>=100?!1:((n=(t=this.mobile).isTouchActive)==null?void 0:n.call(t,e))??!1:(console.warn("🚫 MobileInputs not initialized!"),!1)}getTouchButtonJustPressed(e){var t,n;return!this.mobile||e>=100?!1:((n=(t=this.mobile).isTouchJustStarted)==null?void 0:n.call(t,e))??!1}getTouchButtonJustReleased(e){var t,n;return!this.mobile||e>=100?!1:((n=(t=this.mobile).isTouchJustReleased)==null?void 0:n.call(t,e))??!1}ensureTouchZonesSynced(){var e;(e=this.touchZones)==null||e.updateFromTouches()}getTouchZoneButton(e){if(!this.touchZones)return!1;this.ensureTouchZonesSynced();let t=e;return this.touchZones.isZonePressed(t)}getTouchZoneButtonJustPressed(e){if(!this.touchZones)return!1;this.ensureTouchZonesSynced();let t=e;return this.touchZones.isZoneJustPressed(t)}getTouchZoneButtonJustReleased(e){if(!this.touchZones)return!1;this.ensureTouchZonesSynced();let t=e;return this.touchZones.isZoneJustReleased(t)}getTouchZoneAxis(e){if(!this.touchZones||e<100)return 0;this.ensureTouchZonesSynced();let t=Math.floor((e-100)/2),n=(e-100)%2===0;return this.touchZones.getZoneAxis(t,n?"x":"y")}getMouseAxis(e){if(!this.mouse)return 0;switch(e){case Nt.PositionX:return this.mouse.getMousePosition().x;case Nt.PositionY:return this.mouse.getMousePosition().y;case Nt.DeltaX:return this.mouse.getMouseDelta().x;case Nt.DeltaY:return this.mouse.getMouseDelta().y;case Nt.WheelDeltaY:return this.mouse.getWheelDelta();default:return 0}}getGamepadAxis(e){if(!this.gamepad||e<100)return 0;let t=e-100;return this.gamepad.getAxis(0,t)}getTouchAxis(e){var t,n;if(!this.mobile)return 0;if(e>=100&&e<200){let i=Math.floor((e-100)/2),s=(e-100)%2===0,o=(n=(t=this.mobile).getTouchPosition)==null?void 0:n.call(t,i);return this.config.debug&&o&&console.warn(`🎯 getTouchAxis(${e}) - touchIndex: ${i}, ${s?"X":"Y"}: ${s?o.x:o.y}`),o?s?o.x:o.y:0}return 0}getMousePosition(){if(!this.mouse)return null;let e=this.mouse.getMousePosition();return{x:e.x,y:e.y}}setMobileTarget(e){if(!e){this.warn("setMobileTarget() called with null/undefined canvas - mobile input will remain disabled");return}if(this.config.mobileTargetElement=e,!this.config.enableMobile){this.warn("setMobileTarget() called but mobile input is disabled in config");return}this.mobile&&this.mobile.stop(),this.mobile=new ah(e,this.config.mobileConfig),this.mobile.start()}getTextInputs(){return this.keyboard?this.keyboard.getTextInputs():[]}start(){var e,t;(e=this.keyboard)==null||e.start(),(t=this.mouse)==null||t.start(),this.log("Input router started")}stop(){var e,t;(e=this.keyboard)==null||e.stop(),(t=this.mouse)==null||t.stop(),this.log("Input router stopped")}reset(){var e,t;(e=this.keyboard)==null||e.reset(),(t=this.mouse)==null||t.reset(),this.log("Input router reset")}poll(){var e,t,n,i,s;(e=this.keyboard)==null||e.poll(),(t=this.mouse)==null||t.poll(),(n=this.gamepad)==null||n.poll(),(i=this.mobile)==null||i.poll(),(s=this.touchZones)==null||s.poll()}isListening(){return this.keyboard!==null&&this.config.enableKeyboardMouse||this.gamepad!==null&&this.config.enableGamepad||this.mobile!==null&&this.config.enableMobile||this.touchZones!==null&&this.config.enableTouchZones}getGamepad(){return this.gamepad}getKeyboard(){return this.keyboard}getMouse(){return this.mouse}getMobile(){return this.mobile}getTouchZones(){return this.touchZones}enableTouchZonesDevice(e,t,n,i){let s=Math.max(1,t),o=Math.max(1,n);if(this.touchZones)return i&&this.touchZones.setZones(i),this.touchZones.setLayout(s,o),!0;if(!this.mobile)return this.warn("Cannot enable touch zones: mobile input not initialized"),!1;let a={targetElement:e,gridWidth:s,gridHeight:o,zones:i,enabled:!0,debug:this.config.debug};return this.disableSystemLongPressHaptics(e),this.touchZones=new rm(this.mobile,a),this.touchZones.start(),this.log(`Touch zones dynamically enabled with ${(i==null?void 0:i.length)??0} zones`),!0}updateTouchZoneLayout(e,t,n){var o;let i=Math.max(1,e),s=Math.max(1,t);(o=this.touchZones)==null||o.setLayout(i,s,n)}destroy(){var e,t;(e=this.keyboard)==null||e.destroy(),(t=this.mouse)==null||t.destroy(),this.keyboard=null,this.mouse=null,this.gamepad=null,this.mobile=null,this.touchZones=null,this.log("Input router destroyed")}log(e){}warn(e){console.warn(`[InputRouter] ${e}`)}disableSystemLongPressHaptics(e){let t="__utspTouchSurfacePatched";if(e[t])return;e[t]=!0;let n=e.tagName.toLowerCase()==="canvas"||(e.getAttribute("data-utsp-input-surface")??"").toLowerCase()==="true";n&&(e.style.setProperty("touch-action","none"),e.style.setProperty("user-select","none"),e.style.setProperty("-webkit-user-select","none"),e.style.setProperty("-webkit-touch-callout","none")),e.addEventListener("contextmenu",i=>i.preventDefault()),n&&e.addEventListener("touchstart",i=>{this.config.mobileConfig.preventDefault&&i.preventDefault()},{passive:!this.config.mobileConfig.preventDefault})}};wr(dw,"UnifiedInputRouter");var hw=dw,nm=100,im=2,fw=class lh{static calculateRenderMetrics(e,t){let n=e.getBoundingClientRect(),i=e.width/e.height,s=n.width/n.height,o,a,l,u;i>s?(o=n.width,a=n.width/i,l=0,u=(n.height-a)/2):(o=n.height*i,a=n.height,l=(n.width-o)/2,u=0);let c=(t==null?void 0:t.offsetX)||0,d=(t==null?void 0:t.offsetY)||0;return l+=c,u+=d,o-=c*2,a-=d*2,{renderWidth:o,renderHeight:a,offsetX:l,offsetY:u,rect:n}}static collectAxisSources(e,t){let n=new Map;for(let i of e)for(let s of i.sources){if(n.has(s.sourceId))continue;let o=0,a=!1;if(s.type===ce.Keyboard&&s.negativeKey!==void 0&&s.positiveKey!==void 0){let l=t.getButton(ce.Keyboard,s.negativeKey);t.getButton(ce.Keyboard,s.positiveKey)&&(o+=1),l&&(o-=1),a=!0}else if(s.type===ce.Mouse&&s.mouseAxis!==void 0)o=t.getAxis(ce.Mouse,s.mouseAxis),a=!0;else if(s.type===ce.Gamepad&&s.axis!==void 0)o=t.getAxis(ce.Gamepad,s.axis),a=!0;else if(s.type===ce.Touch&&s.touchId!==void 0&&s.touchAxis!==void 0){let l=100+s.touchId*2,u=s.touchAxis==="x"?l:l+1;o=t.getAxis(ce.Touch,u),a=!0}else if(s.type===ce.TouchZone&&s.touchZoneId!==void 0&&s.touchZoneAxis!==void 0){let l=100+s.touchZoneId*2,u=s.touchZoneAxis==="x"?l:l+1;o=t.getAxis(ce.TouchZone,u),a=!0}a&&n.set(s.sourceId,o)}return n}static collectButtonSources(e,t){let n=new Map;for(let i of e)for(let s of i.sources){if(n.has(s.sourceId))continue;let o=!1,a=!1;s.type===ce.Keyboard&&s.key!==void 0?(o=t.getButton(ce.Keyboard,s.key),a=!0):s.type===ce.Mouse&&s.mouseButton!==void 0?(o=t.getButton(ce.Mouse,s.mouseButton),a=!0):s.type===ce.Gamepad&&s.button!==void 0?(o=t.getButton(ce.Gamepad,s.button),a=!0):s.type===ce.Touch&&s.touchButton!==void 0?(o=t.getButton(ce.Touch,s.touchButton),a=!0):s.type===ce.TouchZone&&s.touchZoneId!==void 0&&(o=t.getButton(ce.TouchZone,s.touchZoneId),a=!0),a&&n.set(s.sourceId,o)}return n}static collectButtonSourcesWithTransitions(e,t){var i,s,o,a,l,u,c,d,h,f;let n=new Map;for(let p of e)for(let m of p.sources){if(n.has(m.sourceId))continue;let S=!1,w=!1,g=!1,y=!1;m.type===ce.Keyboard&&m.key!==void 0?(S=t.getButton(ce.Keyboard,m.key),w=((i=t.getButtonJustPressed)==null?void 0:i.call(t,ce.Keyboard,m.key))??!1,g=((s=t.getButtonJustReleased)==null?void 0:s.call(t,ce.Keyboard,m.key))??!1,y=!0):m.type===ce.Mouse&&m.mouseButton!==void 0?(S=t.getButton(ce.Mouse,m.mouseButton),w=((o=t.getButtonJustPressed)==null?void 0:o.call(t,ce.Mouse,m.mouseButton))??!1,g=((a=t.getButtonJustReleased)==null?void 0:a.call(t,ce.Mouse,m.mouseButton))??!1,y=!0):m.type===ce.Gamepad&&m.button!==void 0?(S=t.getButton(ce.Gamepad,m.button),w=((l=t.getButtonJustPressed)==null?void 0:l.call(t,ce.Gamepad,m.button))??!1,g=((u=t.getButtonJustReleased)==null?void 0:u.call(t,ce.Gamepad,m.button))??!1,y=!0):m.type===ce.Touch&&m.touchButton!==void 0?(S=t.getButton(ce.Touch,m.touchButton),w=((c=t.getButtonJustPressed)==null?void 0:c.call(t,ce.Touch,m.touchButton))??!1,g=((d=t.getButtonJustReleased)==null?void 0:d.call(t,ce.Touch,m.touchButton))??!1,y=!0):m.type===ce.TouchZone&&m.touchZoneId!==void 0&&(S=t.getButton(ce.TouchZone,m.touchZoneId),w=((h=t.getButtonJustPressed)==null?void 0:h.call(t,ce.TouchZone,m.touchZoneId))??!1,g=((f=t.getButtonJustReleased)==null?void 0:f.call(t,ce.TouchZone,m.touchZoneId))??!1,y=!0),y&&n.set(m.sourceId,{pressed:S,justPressed:w,justReleased:g})}return n}static collectMousePosition(e,t,n,i,s){var x;let o=e.getAxis(ce.Mouse,Nt.PositionX),a=e.getAxis(ce.Mouse,Nt.PositionY),l=((x=e.isLeftMousePressed)==null?void 0:x.call(e))??!1,{renderWidth:u,renderHeight:c,offsetX:d,offsetY:h,rect:f}=lh.calculateRenderMetrics(t,s),p=o-f.left-d,m=a-f.top-h,S=u/n,w=c/i,g=Math.floor(p/S),y=Math.floor(m/w),C=p>=0&&p<u&&m>=0&&m<c;return{x:Math.max(0,Math.min(n-1,g)),y:Math.max(0,Math.min(i-1,y)),over:C,isLeftDown:l}}static collectTouchPositions(e,t,n,i,s=10,o){let a=[],{renderWidth:l,renderHeight:u,offsetX:c,offsetY:d,rect:h}=lh.calculateRenderMetrics(t,o),f=l/n,p=u/i;for(let m=0;m<s;m++){let S=m;if(e.getButton(ce.Touch,S)){let w=nm+m*im,g=nm+m*im+1,y=e.getAxis(ce.Touch,w),C=e.getAxis(ce.Touch,g),x=y-h.left-c,I=C-h.top-d,E=Math.floor(x/f),A=Math.floor(I/p),R=x>=0&&x<l&&I>=0&&I<u;a.push({id:m,x:Math.max(0,Math.min(n-1,E)),y:Math.max(0,Math.min(i-1,A)),over:R})}}return a}static collectTextInputs(e){return typeof e.getTextInputs=="function"?e.getTextInputs():[]}};wr(fw,"InputCollector");var Er=fw;const Yn=Object.create(null);Yn.open="0";Yn.close="1";Yn.ping="2";Yn.pong="3";Yn.message="4";Yn.upgrade="5";Yn.noop="6";const Rl=Object.create(null);Object.keys(Yn).forEach(r=>{Rl[Yn[r]]=r});const uh={type:"error",data:"parser error"},pw=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",gw=typeof ArrayBuffer=="function",mw=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,Af=({type:r,data:e},t,n)=>pw&&e instanceof Blob?t?n(e):sm(e,n):gw&&(e instanceof ArrayBuffer||mw(e))?t?n(e):sm(new Blob([e]),n):n(Yn[r]+(e||"")),sm=(r,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)};function om(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Nc;function Mk(r,e){if(pw&&r.data instanceof Blob)return r.data.arrayBuffer().then(om).then(e);if(gw&&(r.data instanceof ArrayBuffer||mw(r.data)))return e(om(r.data));Af(r,!1,t=>{Nc||(Nc=new TextEncoder),e(Nc.encode(t))})}const am="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Wo=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<am.length;r++)Wo[am.charCodeAt(r)]=r;const Uk=r=>{let e=r.length*.75,t=r.length,n,i=0,s,o,a,l;r[r.length-1]==="="&&(e--,r[r.length-2]==="="&&e--);const u=new ArrayBuffer(e),c=new Uint8Array(u);for(n=0;n<t;n+=4)s=Wo[r.charCodeAt(n)],o=Wo[r.charCodeAt(n+1)],a=Wo[r.charCodeAt(n+2)],l=Wo[r.charCodeAt(n+3)],c[i++]=s<<2|o>>4,c[i++]=(o&15)<<4|a>>2,c[i++]=(a&3)<<6|l&63;return u},Ak=typeof ArrayBuffer=="function",Tf=(r,e)=>{if(typeof r!="string")return{type:"message",data:yw(r,e)};const t=r.charAt(0);return t==="b"?{type:"message",data:Tk(r.substring(1),e)}:Rl[t]?r.length>1?{type:Rl[t],data:r.substring(1)}:{type:Rl[t]}:uh},Tk=(r,e)=>{if(Ak){const t=Uk(r);return yw(t,e)}else return{base64:!0,data:r}},yw=(r,e)=>{switch(e){case"blob":return r instanceof Blob?r:new Blob([r]);case"arraybuffer":default:return r instanceof ArrayBuffer?r:r.buffer}},vw="",Rk=(r,e)=>{const t=r.length,n=new Array(t);let i=0;r.forEach((s,o)=>{Af(s,!1,a=>{n[o]=a,++i===t&&e(n.join(vw))})})},Pk=(r,e)=>{const t=r.split(vw),n=[];for(let i=0;i<t.length;i++){const s=Tf(t[i],e);if(n.push(s),s.type==="error")break}return n};function Bk(){return new TransformStream({transform(r,e){Mk(r,t=>{const n=t.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const s=new DataView(i.buffer);s.setUint8(0,126),s.setUint16(1,n)}else{i=new Uint8Array(9);const s=new DataView(i.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(n))}r.data&&typeof r.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let Vc;function cl(r){return r.reduce((e,t)=>e+t.length,0)}function dl(r,e){if(r[0].length===e)return r.shift();const t=new Uint8Array(e);let n=0;for(let i=0;i<e;i++)t[i]=r[0][n++],n===r[0].length&&(r.shift(),n=0);return r.length&&n<r[0].length&&(r[0]=r[0].slice(n)),t}function zk(r,e){Vc||(Vc=new TextDecoder);const t=[];let n=0,i=-1,s=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(n===0){if(cl(t)<1)break;const l=dl(t,1);s=(l[0]&128)===128,i=l[0]&127,i<126?n=3:i===126?n=1:n=2}else if(n===1){if(cl(t)<2)break;const l=dl(t,2);i=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),n=3}else if(n===2){if(cl(t)<8)break;const l=dl(t,8),u=new DataView(l.buffer,l.byteOffset,l.length),c=u.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(uh);break}i=c*Math.pow(2,32)+u.getUint32(4),n=3}else{if(cl(t)<i)break;const l=dl(t,i);a.enqueue(Tf(s?l:Vc.decode(l),e)),n=0}if(i===0||i>r){a.enqueue(uh);break}}}})}const ww=4;function Dt(r){if(r)return Ok(r)}function Ok(r){for(var e in Dt.prototype)r[e]=Dt.prototype[e];return r}Dt.prototype.on=Dt.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this};Dt.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this};Dt.prototype.off=Dt.prototype.removeListener=Dt.prototype.removeAllListeners=Dt.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,i=0;i<t.length;i++)if(n=t[i],n===e||n.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+r],this};Dt.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,e)}return this};Dt.prototype.emitReserved=Dt.prototype.emit;Dt.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]};Dt.prototype.hasListeners=function(r){return!!this.listeners(r).length};const Pu=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),cn=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Dk="arraybuffer";function Cw(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}const Fk=cn.setTimeout,Lk=cn.clearTimeout;function Bu(r,e){e.useNativeTimers?(r.setTimeoutFn=Fk.bind(cn),r.clearTimeoutFn=Lk.bind(cn)):(r.setTimeoutFn=cn.setTimeout.bind(cn),r.clearTimeoutFn=cn.clearTimeout.bind(cn))}const _k=1.33;function $k(r){return typeof r=="string"?Nk(r):Math.ceil((r.byteLength||r.size)*_k)}function Nk(r){let e=0,t=0;for(let n=0,i=r.length;n<i;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function bw(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Vk(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function Hk(r){let e={},t=r.split("&");for(let n=0,i=t.length;n<i;n++){let s=t[n].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}class jk extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Rf extends Dt{constructor(e){super(),this.writable=!1,Bu(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new jk(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Tf(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=Vk(e);return t.length?"?"+t:""}}class Yk extends Rf{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||t()})),this.writable||(n++,this.once("drain",function(){--n||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};Pk(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Rk(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=bw()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Sw=!1;try{Sw=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Wk=Sw;function Gk(){}class Xk extends Yk{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,s)=>{this.onError("xhr post error",i,s)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}class jn extends Dt{constructor(e,t,n){super(),this.createRequest=e,Bu(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=Cw(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=jn.requestsCount++,jn.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Gk,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete jn.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}jn.requestsCount=0;jn.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",lm);else if(typeof addEventListener=="function"){const r="onpagehide"in cn?"pagehide":"unload";addEventListener(r,lm,!1)}}function lm(){for(let r in jn.requests)jn.requests.hasOwnProperty(r)&&jn.requests[r].abort()}const Kk=function(){const r=xw({xdomain:!1});return r&&r.responseType!==null}();class Zk extends Xk{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Kk&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new jn(xw,this.uri(),e)}}function xw(r){const e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Wk))return new XMLHttpRequest}catch{}if(!e)try{return new cn[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Iw=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qk extends Rf{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=Iw?{}:Cw(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;Af(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{}i&&Pu(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=bw()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Hc=cn.WebSocket||cn.MozWebSocket;class Qk extends qk{createSocket(e,t,n){return Iw?new Hc(e,t,n):t?new Hc(e,t):new Hc(e)}doWrite(e,t){this.ws.send(t)}}class Jk extends Rf{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=zk(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=Bk();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const s=()=>{n.read().then(({done:a,value:l})=>{a||(this.onPacket(l),s())}).catch(a=>{})};s();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;this._writer.write(n).then(()=>{i&&Pu(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const eE={websocket:Qk,webtransport:Jk,polling:Zk},tE=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,rE=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ch(r){if(r.length>8e3)throw"URI too long";const e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let i=tE.exec(r||""),s={},o=14;for(;o--;)s[rE[o]]=i[o]||"";return t!=-1&&n!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=nE(s,s.path),s.queryKey=iE(s,s.query),s}function nE(r,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function iE(r,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}const dh=typeof addEventListener=="function"&&typeof removeEventListener=="function",Pl=[];dh&&addEventListener("offline",()=>{Pl.forEach(r=>r())},!1);class Ri extends Dt{constructor(e,t){if(super(),this.binaryType=Dk,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const n=ch(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=ch(t.host).host);Bu(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{const i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Hk(this.opts.query)),dh&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Pl.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=ww,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&Ri.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",Ri.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(t+=$k(i)),n>0&&t>this._maxPayload)return this.writeBuffer.slice(0,n);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Pu(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const s={type:e,data:t,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Ri.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),dh&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Pl.indexOf(this._offlineEventListener);n!==-1&&Pl.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Ri.protocol=ww;class sE extends Ri{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Ri.priorWebsocketSuccess=!1;const i=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",d=>{if(!n)if(d.type==="pong"&&d.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Ri.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const h=new Error("probe error");h.transport=t.name,this.emitReserved("upgradeError",h)}}))};function s(){n||(n=!0,c(),t.close(),t=null)}const o=d=>{const h=new Error("probe error: "+d);h.transport=t.name,s(),this.emitReserved("upgradeError",h)};function a(){o("transport closed")}function l(){o("socket closed")}function u(d){t&&d.name!==t.name&&s()}const c=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",a),this.off("close",l),this.off("upgrading",u)};t.once("open",i),t.once("error",o),t.once("close",a),this.once("close",l),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let oE=class extends sE{constructor(e,t={}){const n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>eE[i]).filter(i=>!!i)),super(e,n)}};function aE(r,e="",t){let n=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),n=ch(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+e,n.href=n.protocol+"://"+s+(t&&t.port===n.port?"":":"+n.port),n}const lE=typeof ArrayBuffer=="function",uE=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,kw=Object.prototype.toString,cE=typeof Blob=="function"||typeof Blob<"u"&&kw.call(Blob)==="[object BlobConstructor]",dE=typeof File=="function"||typeof File<"u"&&kw.call(File)==="[object FileConstructor]";function Pf(r){return lE&&(r instanceof ArrayBuffer||uE(r))||cE&&r instanceof Blob||dE&&r instanceof File}function Bl(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(Bl(r[t]))return!0;return!1}if(Pf(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return Bl(r.toJSON(),!0);for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&Bl(r[t]))return!0;return!1}function hE(r){const e=[],t=r.data,n=r;return n.data=hh(t,e),n.attachments=e.length,{packet:n,buffers:e}}function hh(r,e){if(!r)return r;if(Pf(r)){const t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){const t=new Array(r.length);for(let n=0;n<r.length;n++)t[n]=hh(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){const t={};for(const n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=hh(r[n],e));return t}return r}function fE(r,e){return r.data=fh(r.data,e),delete r.attachments,r}function fh(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=fh(r[t],e);else if(typeof r=="object")for(const t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=fh(r[t],e));return r}const pE=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],gE=5;var Be;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(Be||(Be={}));class mE{constructor(e){this.replacer=e}encode(e){return(e.type===Be.EVENT||e.type===Be.ACK)&&Bl(e)?this.encodeAsBinary({type:e.type===Be.EVENT?Be.BINARY_EVENT:Be.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Be.BINARY_EVENT||e.type===Be.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=hE(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}function um(r){return Object.prototype.toString.call(r)==="[object Object]"}class Bf extends Dt{constructor(e){super(),this.reviver=e}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===Be.BINARY_EVENT;n||t.type===Be.BINARY_ACK?(t.type=n?Be.EVENT:Be.ACK,this.reconstructor=new yE(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Pf(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(Be[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Be.BINARY_EVENT||n.type===Be.BINARY_ACK){const s=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(s,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");n.attachments=Number(o)}if(e.charAt(t+1)==="/"){const s=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(s,t)}else n.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const s=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){const s=this.tryParse(e.substr(t));if(Bf.isPayloadValid(n.type,s))n.data=s;else throw new Error("invalid payload")}return n}tryParse(e){try{return JSON.parse(e,this.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case Be.CONNECT:return um(t);case Be.DISCONNECT:return t===void 0;case Be.CONNECT_ERROR:return typeof t=="string"||um(t);case Be.EVENT:case Be.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&pE.indexOf(t[0])===-1);case Be.ACK:case Be.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class yE{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=fE(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const vE=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Bf,Encoder:mE,get PacketType(){return Be},protocol:gE},Symbol.toStringTag,{value:"Module"}));function xn(r,e,t){return r.on(e,t),function(){r.off(e,t)}}const wE=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ew extends Dt{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[xn(e,"open",this.onopen.bind(this)),xn(e,"packet",this.onpacket.bind(this)),xn(e,"error",this.onerror.bind(this)),xn(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,i,s;if(wE.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:Be.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const c=this.ids++,d=t.pop();this._registerAckCallback(c,d),o.id=c}const a=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,l=this.connected&&!(!((s=this.io.engine)===null||s===void 0)&&s._hasPingExpired());return this.flags.volatile&&!a||(l?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&this.sendBuffer.splice(a,1);t.call(this,new Error("operation has timed out"))},i),o=(...a)=>{this.io.clearTimeoutFn(s),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((n,i)=>{const s=(o,a)=>o?i(o):n(a);s.withError=!0,t.push(s),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...s)=>n!==this._queue[0]?void 0:(i!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Be.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Be.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Be.EVENT:case Be.BINARY_EVENT:this.onevent(e);break;case Be.ACK:case Be.BINARY_ACK:this.onack(e);break;case Be.DISCONNECT:this.ondisconnect();break;case Be.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...i){n||(n=!0,t.packet({type:Be.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Be.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function mo(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}mo.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=Math.floor(e*10)&1?r+t:r-t}return Math.min(r,this.max)|0};mo.prototype.reset=function(){this.attempts=0};mo.prototype.setMin=function(r){this.ms=r};mo.prototype.setMax=function(r){this.max=r};mo.prototype.setJitter=function(r){this.jitter=r};class ph extends Dt{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,Bu(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new mo({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||vE;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new oE(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=xn(t,"open",function(){n.onopen(),e&&e()}),s=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=xn(t,"error",s);if(this._timeout!==!1){const a=this._timeout,l=this.setTimeoutFn(()=>{i(),s(new Error("timeout")),t.close()},a);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(xn(e,"ping",this.onping.bind(this)),xn(e,"data",this.ondata.bind(this)),xn(e,"error",this.onerror.bind(this)),xn(e,"close",this.onclose.bind(this)),xn(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){Pu(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Ew(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Do={};function ua(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};const t=aE(r,e.path||"/socket.io"),n=t.source,i=t.id,s=t.path,o=Do[i]&&s in Do[i].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let l;return a?l=new ph(n,e):(Do[i]||(Do[i]=new ph(n,e)),l=Do[i]),t.query&&!e.query&&(e.query=t.queryKey),l.socket(t.path,e)}Object.assign(ua,{Manager:ph,Socket:Ew,io:ua,connect:ua});var Mw=Object.defineProperty,CE=(r,e,t)=>e in r?Mw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,zf=(r,e)=>Mw(r,"name",{value:e,configurable:!0}),ut=(r,e,t)=>(CE(r,typeof e!="symbol"?e+"":e,t),t),Uw=class{constructor(e){if(ut(this,"socket",null),ut(this,"options"),ut(this,"_state",yt.Disconnected),ut(this,"pingTimestamp",0),ut(this,"latency",0),ut(this,"pingInterval",null),ut(this,"bridgeHandlers",new Map),ut(this,"bridgeSetup",!1),!e.url||typeof e.url!="string")throw new Error("SocketIOClient: Invalid URL - must be a non-empty string");try{if(!new globalThis.URL(e.url).protocol)throw new Error("Invalid protocol")}catch{throw new Error(`SocketIOClient: Invalid URL format - ${e.url}`)}if(e.reconnectDelay!==void 0&&(e.reconnectDelay<0||!Number.isFinite(e.reconnectDelay)))throw new Error(`SocketIOClient: Invalid reconnectDelay - must be a positive number (got ${e.reconnectDelay})`);if(e.maxReconnectAttempts!==void 0&&(!Number.isInteger(e.maxReconnectAttempts)||e.maxReconnectAttempts<0))throw new Error(`SocketIOClient: Invalid maxReconnectAttempts - must be a positive integer (got ${e.maxReconnectAttempts})`);if(e.timeout!==void 0&&(e.timeout<=0||!Number.isFinite(e.timeout)))throw new Error(`SocketIOClient: Invalid timeout - must be a positive number (got ${e.timeout})`);this.options={url:e.url,autoReconnect:e.autoReconnect??!0,reconnectDelay:e.reconnectDelay??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,timeout:e.timeout??5e3,auth:e.auth??{},iceServers:e.iceServers??[],path:e.path,debug:e.debug??!1,sessionId:e.sessionId},this.log("Client initialized",{url:this.options.url,autoReconnect:this.options.autoReconnect})}get state(){return this._state}isConnected(){var e;return this._state===yt.Connected&&((e=this.socket)==null?void 0:e.connected)===!0}async connect(){if(this.socket&&this.isConnected()){this.log("Already connected");return}return this.log(`Connecting to ${this.options.url}...`),this._state=yt.Connecting,this.bridgeSetup=!1,new Promise((e,t)=>{this.socket=ua(this.options.url,{path:this.options.path,auth:this.options.auth,reconnection:this.options.autoReconnect,reconnectionDelay:this.options.reconnectDelay,reconnectionAttempts:this.options.maxReconnectAttempts,timeout:this.options.timeout,transports:["websocket"]}),this.socket.on("connect",()=>{var n;this.log(`Connected with ID: ${(n=this.socket)==null?void 0:n.id}`),this._state=yt.Connected,this.startPingMonitor(),this.bridgeHandlers.size>0&&this.setupBridgeListener(),e()}),this.socket.on("connect_error",n=>{this.log(`Connection error: ${n.message}`),this._state=yt.Error,t(n)}),this.socket.on("disconnect",n=>{this.log(`Disconnected: ${n}`),this._state=yt.Disconnected,this.stopPingMonitor()}),this.socket.on("reconnect_attempt",n=>{this.log(`Reconnection attempt ${n}...`),this._state=yt.Reconnecting}),this.socket.on("reconnect",n=>{this.log(`Reconnected after ${n} attempts`),this._state=yt.Connected,this.startPingMonitor()}),this.socket.on("reconnect_failed",()=>{this.log("Reconnection failed"),this._state=yt.Error}),this.socket.on("pong",()=>{this.latency=Date.now()-this.pingTimestamp,this.log(`Ping: ${this.latency}ms`)})})}disconnect(){this.socket&&(this.log("Disconnecting..."),this.stopPingMonitor(),this.socket.disconnect(),this._state=yt.Disconnected)}send(e,t){if(!e||typeof e!="string"){this.log(`Cannot send: invalid event name (${typeof e})`);return}if(!this.isConnected()||!this.socket){this.log(`Cannot send '${e}': not connected`);return}try{this.socket.emit(e,t)}catch(n){this.log(`Error sending '${e}':`,n)}}sendVolatile(e,t){if(!(!e||typeof e!="string")&&!(!this.isConnected()||!this.socket))try{this.socket.volatile.emit(e,t)}catch(n){this.log(`Error sending volatile '${e}':`,n)}}on(e,t){if(!e||typeof e!="string")throw new Error(`Invalid event name: ${e}`);if(typeof t!="function")throw new Error(`Invalid handler for event '${e}': must be a function`);if(!this.socket){this.log(`Cannot listen to '${e}': socket not initialized`);return}this.socket.on(e,t),this.log(`Listening to '${e}'`)}off(e,t){this.socket&&(this.socket.off(e,t),this.log(`Stopped listening to '${e}'`))}removeAllListeners(e){this.socket&&(e?(this.socket.removeAllListeners(e),this.log(`Removed all listeners for '${e}'`)):(this.socket.removeAllListeners(),this.log("Removed all listeners")))}async request(e,t,n=5e3){if(!e||typeof e!="string")throw new Error(`Invalid event name: ${e}`);if(!Number.isFinite(n)||n<=0)throw new Error(`Invalid timeout: ${n} (must be a positive number)`);if(!this.isConnected())throw new Error("Cannot send request: not connected to server");return new Promise((i,s)=>{let o=`${e}_response`,a=setTimeout(()=>{this.off(o,l),s(new Error(`Request timeout after ${n}ms: ${e}`))},n),l=zf(u=>{clearTimeout(a),this.off(o,l),i(u)},"responseHandler");this.on(o,l),this.send(e,t),this.log(`Request sent: ${e} (timeout: ${n}ms)`)})}getPing(){return this.latency}sendBridge(e,t){if(!this.isConnected()||!this.socket){this.log(`Cannot send bridge '${e}': not connected`);return}try{let n={channel:e,data:JSON.stringify(t)};this.socket.emit("bridge",n),this.log(`Bridge sent on channel '${e}'`)}catch(n){this.log(`Error sending bridge: ${n}`)}}onBridge(e,t){this.bridgeHandlers.has(e)||this.bridgeHandlers.set(e,[]),this.bridgeHandlers.get(e).push(t),this.log(`Bridge handler registered for channel '${e}'`),this.setupBridgeListener()}offBridge(e,t){let n=this.bridgeHandlers.get(e);if(n){let i=n.indexOf(t);i!==-1&&(n.splice(i,1),this.log(`Bridge handler removed for channel '${e}'`))}}removeAllBridgeHandlers(e){e?(this.bridgeHandlers.delete(e),this.log(`All bridge handlers removed for channel '${e}'`)):(this.bridgeHandlers.clear(),this.log("All bridge handlers removed"))}setupBridgeListener(){this.bridgeSetup||!this.socket||(this.socket.on("bridge",e=>{this.handleBridgeMessage(e)}),this.bridgeSetup=!0,this.log("Bridge listener setup"))}handleBridgeMessage(e){try{let{channel:t,data:n}=e,i=JSON.parse(n),s=this.bridgeHandlers.get(t);s&&s.length>0?s.forEach(o=>{try{o(i)}catch(a){this.log(`Error in bridge handler for '${t}': ${a}`)}}):this.log(`No bridge handler for channel '${t}'`)}catch(t){this.log(`Error parsing bridge message: ${t}`)}}destroy(){this.log("Destroying client..."),this.stopPingMonitor(),this.bridgeHandlers.clear(),this.bridgeSetup=!1,this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null),this._state=yt.Disconnected,this.log("Client destroyed")}startPingMonitor(){this.pingInterval||(this.pingInterval=setInterval(()=>{this.isConnected()&&this.socket&&(this.pingTimestamp=Date.now(),this.socket.emit("ping"))},2e3),this.log("Ping monitor started"))}stopPingMonitor(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null,this.log("Ping monitor stopped"))}log(e,t){this.options.debug&&(t!==void 0?console.warn(`[SocketIOClient] ${e}`,t):console.warn(`[SocketIOClient] ${e}`))}};zf(Uw,"SocketIOClient");var bE=Uw,Aw=class{constructor(e){ut(this,"signalingSocket",null),ut(this,"peerConnection",null),ut(this,"reliableChannel",null),ut(this,"unreliableChannel",null),ut(this,"options"),ut(this,"_state",yt.Disconnected),ut(this,"p2pOnly",!0),ut(this,"eventHandlers",new Map),ut(this,"bridgeHandlers",new Map),ut(this,"chunkBuffers",new Map),ut(this,"remotePeerId",null),ut(this,"latency",0),ut(this,"retryCount",0),ut(this,"pingTimestamp",0),ut(this,"pingInterval",null),ut(this,"statsInterval",null),ut(this,"isReassembling",!1);let t=e.sessionId?"https://signal.utsp.dev":void 0,n=e.url||t;if(!n)throw new Error("WebRTCClient: URL required (or sessionId for public relay)");this.options={url:n,autoReconnect:e.autoReconnect??!0,reconnectDelay:e.reconnectDelay??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,timeout:e.timeout??5e3,auth:e.auth??{},iceServers:e.iceServers??[{urls:"stun:stun.l.google.com:19302"}],debug:e.debug??!1,signalingPath:e.signalingPath??(e.sessionId?"/socket.io":"/utsp-signal"),sessionId:e.sessionId,p2pOnly:e.p2pOnly??!0},this.p2pOnly=this.options.p2pOnly??!0,this.on("bridge",i=>{if(!i||!i.channel)return;let s=i.data;if(typeof s=="string")try{s=JSON.parse(s)}catch{}let o=this.bridgeHandlers.get(i.channel);o&&o.forEach(a=>a(s))})}get state(){return this._state}isConnected(){return this._state===yt.Connected}async connect(){if(!(this._state===yt.Connected||this._state===yt.Connecting))return this._state=yt.Connecting,this.log("Connecting via WebRTC..."),new Promise((e,t)=>{this.signalingSocket=ua(this.options.url,{path:this.options.signalingPath,auth:this.options.auth,reconnection:this.options.autoReconnect,reconnectionDelay:this.options.reconnectDelay,reconnectionAttempts:this.options.maxReconnectAttempts,transports:["websocket","polling"]}),this.options.sessionId?(this.log(`Connecting via Public Relay to session: ${this.options.sessionId}`),this.signalingSocket.on("connect",()=>{this.log("Connected to Relay"),this.signalingSocket.emit("join-session",this.options.sessionId)}),this.signalingSocket.on("disconnect",i=>{this.warn(`Relay signaled disconnect: ${i}`)}),this.signalingSocket.on("signal",({from:i,type:s,data:o})=>{this.remotePeerId=i,s==="rtc:offer"?(this.log("Received RTC Offer via Relay"),this.handleOffer(o)):s==="rtc:candidate"&&this.peerConnection&&(this.log("Received ICE Candidate via Relay"),this.peerConnection.addIceCandidate(o).catch(a=>this.error("ICE Error",a)))})):(this.signalingSocket.on("connect",()=>{this.log("Signaling connected")}),this.signalingSocket.on("rtc:offer",async i=>{this.log("Received RTC Offer"),await this.handleOffer(i)}),this.signalingSocket.on("rtc:candidate",i=>{var o;let s=this.parseCandidateType(i.candidate);if(this.p2pOnly&&s==="relay"){this.warn("Strict P2P: Dropping received RELAY candidate");return}this.log(`Received ICE Candidate (${s})`),(o=this.peerConnection)==null||o.addIceCandidate(new RTCIceCandidate(i))})),this.signalingSocket.on("connect_error",i=>{this.error("Signaling connection error",i),this.signalingSocket&&!this.signalingSocket.active&&(this._state=yt.Error,t(i))}),this.signalingSocket.on("disconnect",()=>{this.log("Signaling disconnected"),this._state===yt.Connecting&&this.disconnect()}),this.signalingSocket.onAny((i,...s)=>{i.startsWith("rtc:")||i==="signal"||this.handleEvent(i,s[0])});let n=setTimeout(()=>{this._state!==yt.Connected&&(this.disconnect(),t(new Error("Connection timeout")))},this.options.timeout);this._connectResolve=()=>{clearTimeout(n),e()}})}async handleOffer(e){var t,n;this.peerConnection&&this.peerConnection.close(),this.peerConnection=new RTCPeerConnection({iceServers:this.options.iceServers}),this.setupPeerEvents();try{let i=this.p2pOnly?this.stripRelayFromSDP(e.sdp||""):e.sdp;await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"offer",sdp:i}));let s=await this.peerConnection.createAnswer(),o=this.p2pOnly?this.stripRelayFromSDP(s.sdp||""):s.sdp||"";await this.peerConnection.setLocalDescription({type:"answer",sdp:o}),this.options.sessionId&&this.remotePeerId?(t=this.signalingSocket)==null||t.emit("signal",{target:this.remotePeerId,type:"rtc:answer",data:s}):(this.log("Sending RTC Answer"),(n=this.signalingSocket)==null||n.emit("rtc:answer",s))}catch(i){this.error("WebRTC Negotiation failed",i),this.disconnect()}}setupPeerEvents(){this.peerConnection&&(this.peerConnection.onicecandidate=e=>{var t,n;if(e.candidate)if(this.options.sessionId&&this.remotePeerId)(t=this.signalingSocket)==null||t.emit("signal",{target:this.remotePeerId,type:"rtc:candidate",data:e.candidate});else{let i=this.parseCandidateType(e.candidate.candidate);if(this.p2pOnly&&i==="relay"){this.warn("Strict P2P: Not sending RELAY candidate");return}this.log(`Sending ICE Candidate (${i})`),(n=this.signalingSocket)==null||n.emit("rtc:candidate",e.candidate)}},this.peerConnection.ondatachannel=e=>{let t=e.channel;this.log(`DataChannel received: ${t.label}`),t.label==="reliable"?(this.reliableChannel=t,this.setupChannel(t),t.onopen=()=>{this.log("Reliable Channel OPEN"),this._state=yt.Connected,this.startPingMonitor(),this.startStatsMonitor(),this._connectResolve&&this._connectResolve()}):t.label==="unreliable"&&(this.log("Unreliable Channel RECEIVED"),this.unreliableChannel=t,this.setupChannel(t))},this.peerConnection.onconnectionstatechange=()=>{var t,n;this.log(`Connection State: ${(t=this.peerConnection)==null?void 0:t.connectionState}`);let e=(n=this.peerConnection)==null?void 0:n.connectionState;e==="disconnected"||e==="failed"?this.options.autoReconnect&&this.retryCount<this.options.maxReconnectAttempts?(this.log(`WebRTC lost. Retrying in ${this.options.reconnectDelay}ms... (Attempt ${this.retryCount+1}/${this.options.maxReconnectAttempts})`),this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null),this.retryCount++,setTimeout(()=>{this._state=yt.Disconnected,this.connect().catch(i=>this.error("Reconnection failed",i))},this.options.reconnectDelay*Math.pow(1.5,this.retryCount))):this.disconnect():e==="connected"&&(this.retryCount=0)})}parsePayload(e){return JSON.parse(e,(t,n)=>{if(n&&typeof n=="object"&&n._b64){let i=atob(n._b64),s=new Uint8Array(i.length);for(let o=0;o<i.length;o++)s[o]=i.charCodeAt(o);return s}return n})}setupChannel(e){e.binaryType="arraybuffer",e.onmessage=t=>{let n=t.data;if(e.label,n instanceof ArrayBuffer){try{let i=new DataView(n),s=i.getUint8(0);if(s===255){let c=i.getUint8(1),d=new Uint8Array(n,2);this.handleEvent(c,d);return}let o=s,a=new Uint8Array(n,1,o),l=new TextDecoder("utf-8").decode(a),u=new Uint8Array(n,1+o);this.handleEvent(l,u)}catch(i){this.error("Failed to parse binary packet",i)}return}try{let[i,s]=this.parsePayload(n);this.handleEvent(i,s)}catch{}}}disconnect(){this.stopPingMonitor(),this.statsInterval&&clearInterval(this.statsInterval),this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null),this.signalingSocket&&(this.signalingSocket.disconnect(),this.signalingSocket=null),this.reliableChannel=null,this.unreliableChannel=null,this.chunkBuffers.clear(),this._state=yt.Disconnected}getChunks(e,t){let n=Math.ceil(e.length/t),i=new Array(n);for(let s=0,o=0;s<n;++s,o+=t)i[s]=e.substr(o,t);return i}preparePayload(e,t){return JSON.stringify([e,t],(n,i)=>{if(i&&typeof i=="object"){if(i instanceof Uint8Array||i instanceof Int8Array||i instanceof Uint16Array||i instanceof Int16Array||i instanceof Uint32Array||i instanceof Int32Array||i instanceof Float32Array||i instanceof Float64Array){let s=new Uint8Array(i.buffer,i.byteOffset,i.byteLength),o="",a=s.byteLength;for(let l=0;l<a;l++)o+=String.fromCharCode(s[l]);return{_b64:btoa(o)}}if(i instanceof ArrayBuffer){let s=new Uint8Array(i),o="",a=s.byteLength;for(let l=0;l<a;l++)o+=String.fromCharCode(s[l]);return{_b64:btoa(o)}}}return i})}send(e,t){var n;((n=this.reliableChannel)==null?void 0:n.readyState)==="open"&&this.transmit(this.reliableChannel,e,t,!0)}sendVolatile(e,t){var i;let n=((i=this.unreliableChannel)==null?void 0:i.readyState)==="open"?this.unreliableChannel:this.reliableChannel;(n==null?void 0:n.readyState)==="open"&&this.transmit(n,e,t,!1)}transmit(e,t,n,i){if(!i&&e.bufferedAmount>64*1024)return;let s=1200;if((n instanceof Uint8Array||n instanceof ArrayBuffer)&&typeof t=="number"&&n.byteLength<=s){let l=new Uint8Array(2);l[0]=255,l[1]=t;let u=n instanceof ArrayBuffer?new Uint8Array(n):n,c=new Uint8Array(l.length+u.length);c.set(l),c.set(u,l.length),e.send(c);return}let o=typeof t=="number"?String(t):t,a=this.preparePayload(o,n);if(a.length<=s)e.send(a);else{let l=Math.random().toString(36).substring(2,15),u=this.getChunks(a,s);e.send(JSON.stringify(["__ch:start",{id:l,count:u.length}]));for(let c=0;c<u.length;c++)e.send(JSON.stringify(["__ch:part",{id:l,idx:c,chunk:u[c]}]))}}request(e,t,n=5e3){return Promise.reject(new Error(`Request not implemented: ${e}`))}on(e,t){let n=String(e);this.eventHandlers.has(n)||this.eventHandlers.set(n,[]),this.eventHandlers.get(n).push(t)}off(e,t){let n=String(e),i=this.eventHandlers.get(n);if(i){let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}removeAllListeners(e){e?this.eventHandlers.delete(String(e)):this.eventHandlers.clear()}handleEvent(e,t){let n=String(e);if(n==="__ch:start"){if(this.isReassembling)return;let{id:s,count:o}=t;this.chunkBuffers.set(s,{count:o,parts:new Array(o),received:0});return}if(n==="__ch:part"){let{id:s,idx:o,chunk:a}=t,l=this.chunkBuffers.get(s);if(l&&(l.parts[o]=a,l.received++,l.received===l.count)){this.chunkBuffers.delete(s);try{this.isReassembling=!0;let u=l.parts.join(""),[c,d]=this.parsePayload(u);this.handleEvent(c,d)}catch(u){this.error("Failed to reassemble chunked payload",u)}finally{this.isReassembling=!1}}return}let i=this.eventHandlers.get(n);i&&i.forEach(s=>s(t)),n==="pong"&&(this.latency=Date.now()-this.pingTimestamp,this.log(`Ping: ${this.latency}ms`))}startPingMonitor(){this.stopPingMonitor(),this.pingInterval=setInterval(()=>{this.isConnected()&&(this.pingTimestamp=Date.now(),this.send("ping",null))},2e3)}stopPingMonitor(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}getPing(){return this.latency}startStatsMonitor(){this.stopStatsMonitor(),this.statsInterval=setInterval(async()=>{if(!(!this.peerConnection||this._state!==yt.Connected))try{let e=await this.peerConnection.getStats(),t=null;if(e.forEach(n=>{if(n.type==="transport"){let i=n.selectedCandidatePairId;t=e.get?e.get(i):e[i]}}),t){let n=e,i=n.get?n.get(t.localCandidateId):n[t.localCandidateId],s=n.get?n.get(t.remoteCandidateId):n[t.remoteCandidateId];this.options.debug&&this.log(`RTC Stats: Connection=${t.state} RTT=${t.currentRoundTripTime?Math.round(t.currentRoundTripTime*1e3):"N/A"}ms Path=${(i==null?void 0:i.candidateType)||"?"}<->${(s==null?void 0:s.candidateType)||"?"}`),this.p2pOnly&&((i==null?void 0:i.candidateType)==="relay"||(s==null?void 0:s.candidateType)==="relay")&&(this.error("STRICT P2P VIOLATION: Detected relay path in stats. DISCONNECTING."),this.disconnect())}}catch(e){this.error("Failed to get RTC stats",e)}},5e3)}stopStatsMonitor(){this.statsInterval&&(clearInterval(this.statsInterval),this.statsInterval=null)}stripRelayFromSDP(e){return e.split(`
|
|
256
256
|
`).filter(t=>!t.includes("typ relay")).join(`
|
|
257
|
-
`)}destroy(){this.disconnect(),this.removeAllListeners()}sendBridge(e,t){this.send("bridge",{channel:e,data:t})}onBridge(e,t){this.bridgeHandlers.has(e)||this.bridgeHandlers.set(e,[]),this.bridgeHandlers.get(e).push(t)}offBridge(e,t){let n=this.bridgeHandlers.get(e);if(n){let i=n.indexOf(t);i!==-1&&n.splice(i,1)}}removeAllBridgeHandlers(e){e?this.bridgeHandlers.delete(e):this.bridgeHandlers.clear()}log(e,...t){this.options.debug&&console.warn(`[WebRTC-Client] ${e}`,...t)}parseCandidateType(e){return e?e.includes("typ host")?"host":e.includes("typ srflx")?"srflx":e.includes("typ relay")?"relay":"unknown":"unknown"}warn(e,...t){this.options.debug&&console.warn(`[WebRTC-Client] ${e}`,...t)}error(e,...t){console.error(`[WebRTC-Client] ❌ ${e}`,...t)}};zf(Aw,"WebRTCClient");var SE=Aw,Tw=Object.defineProperty,xE=(r,e,t)=>e in r?Tw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Rw=(r,e)=>Tw(r,"name",{value:e,configurable:!0}),gr=(r,e,t)=>(xE(r,typeof e!="symbol"?e+"":e,t),t),Pw=class{constructor(e,t=!1){gr(this,"sounds",new Map),gr(this,"nameToId",new Map),gr(this,"audioContext"),this.audioContext=e,this.log("SoundBank created")}async loadFromData(e,t,n){this.log(`Loading sound from data: ${t} (${n.length} bytes)`);try{let i=await this.decodeAudio(n);this.store(e,t,i,{source:"file",originalSize:n.length,loadedAt:Date.now()}),this.log(`✓ Loaded: ${t} (${i.duration.toFixed(2)}s)`)}catch(i){throw console.error(`[SoundBank] Failed to decode sound "${t}":`,i),i}}async loadFromUrl(e,t,n,i){this.log(`Loading sound from URL: ${t} → ${n}`);try{let s=await fetch(n);if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);let o=s.headers.get("content-length"),a=o?parseInt(o,10):0,l;if(a>0&&i&&s.body){let c=s.body.getReader(),d=[],h=0;for(;;){let{done:m,value:S}=await c.read();if(m)break;d.push(S),h+=S.length,i(h,a)}let f=new Uint8Array(h),p=0;for(let m of d)f.set(m,p),p+=m.length;l=f.buffer}else l=await s.arrayBuffer();let u=await this.decodeAudio(new Uint8Array(l));this.store(e,t,u,{source:"external",originalSize:l.byteLength,originalUrl:n,loadedAt:Date.now()}),this.log(`✓ Loaded from URL: ${t} (${u.duration.toFixed(2)}s)`)}catch(s){throw console.error(`[SoundBank] Failed to load sound "${t}" from ${n}:`,s),s}}loadFromBuffer(e,t,n){this.log(`Loading sound from buffer: ${t}`),this.store(e,t,n,{source:"procedural",loadedAt:Date.now()}),this.log(`✓ Loaded from buffer: ${t} (${n.duration.toFixed(2)}s)`)}store(e,t,n,i){if(this.sounds.has(e)){let o=this.sounds.get(e);this.log(`Replacing sound ID ${e} (was: ${o.name}, now: ${t})`),this.nameToId.delete(o.name)}if(this.nameToId.has(t)){let o=this.nameToId.get(t);o!==e&&this.log(`Warning: Sound name "${t}" already exists with ID ${o}`)}let s={soundId:e,name:t,buffer:n,duration:n.duration,metadata:i};this.sounds.set(e,s),this.nameToId.set(t,e)}async decodeAudio(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),this.audioContext.decodeAudioData(t)}get(e){if(typeof e=="number")return this.sounds.get(e);let t=this.nameToId.get(e);return t!==void 0?this.sounds.get(t):void 0}has(e){return this.get(e)!==void 0}getAll(){return Array.from(this.sounds.values())}getNames(){return Array.from(this.nameToId.keys())}get size(){return this.sounds.size}remove(e){let t=this.get(e);return t?(this.sounds.delete(t.soundId),this.nameToId.delete(t.name),this.log(`Removed sound: ${t.name}`),!0):!1}clear(){let e=this.sounds.size;this.sounds.clear(),this.nameToId.clear(),this.log(`Cleared ${e} sounds`)}getStats(){let e=this.getAll(),t=0;for(let n of e){let{buffer:i}=n;t+=i.length*i.numberOfChannels*4}return{totalSounds:e.length,totalDuration:e.reduce((n,i)=>n+i.duration,0),estimatedMemory:t,bySource:{file:e.filter(n=>n.metadata.source==="file").length,external:e.filter(n=>n.metadata.source==="external").length,procedural:e.filter(n=>n.metadata.source==="procedural").length}}}log(e){}};Rw(Pw,"SoundBank");var IE=Pw,Bw=class{constructor(e={}){gr(this,"audioContext",null),gr(this,"masterGainNode",null),gr(this,"soundBank",null),gr(this,"options"),gr(this,"initialized",!1),gr(this,"nextInstanceId",1),gr(this,"instances",new Map),gr(this,"instancesBySound",new Map),gr(this,"activeSounds",new Set),gr(this,"spatialSounds",new Map),gr(this,"spatialConfig",{listenerX:0,listenerY:0,maxDistance:200,referenceDistance:20,rolloffFactor:1,panSpread:1}),gr(this,"reverbConvolver",null),gr(this,"reverbGain",null),this.options={debug:e.debug??!1,masterVolume:e.masterVolume??1},this.log("AudioManager created")}initialize(){if(this.initialized&&this.audioContext)return this.log("AudioContext already initialized"),!0;try{let e=window.AudioContext||window.webkitAudioContext;return e?(this.audioContext=new e,this.log(`AudioContext initialized (state: ${this.audioContext.state}, sampleRate: ${this.audioContext.sampleRate}Hz)`),this.masterGainNode=this.audioContext.createGain(),this.masterGainNode.gain.value=this.options.masterVolume,this.masterGainNode.connect(this.audioContext.destination),this.audioContext.state==="suspended"&&this.audioContext.resume().then(()=>{this.log("AudioContext resumed")}),this.soundBank=new IE(this.audioContext,this.options.debug),this.initialized=!0,!0):(console.warn("[AudioManager] Web Audio API not supported"),!1)}catch(e){return console.error("[AudioManager] Failed to initialize AudioContext:",e),!1}}isInitialized(){return this.initialized&&this.audioContext!==null}getContext(){return this.audioContext}getMasterGain(){return this.masterGainNode}setMasterVolume(e){this.options.masterVolume=Math.max(0,Math.min(1,e)),this.masterGainNode&&(this.masterGainNode.gain.value=this.options.masterVolume),this.log(`Master volume set to ${this.options.masterVolume}`)}getMasterVolume(){return this.options.masterVolume}playStartSound(){if(!this.audioContext||!this.masterGainNode){this.log("Cannot play sound: AudioContext not initialized");return}try{let e=this.audioContext,t=e.currentTime,n=[262,330,392,523],i=.06,s=.07;n.forEach((o,a)=>{let l=t+a*s,u=e.createOscillator();u.type="square",u.frequency.setValueAtTime(o,l);let c=e.createGain();c.gain.setValueAtTime(0,l),c.gain.linearRampToValueAtTime(.15,l+.005),c.gain.setValueAtTime(.15,l+i-.01),c.gain.linearRampToValueAtTime(0,l+i),u.connect(c),c.connect(this.masterGainNode),u.start(l),u.stop(l+i)}),this.log("Start sound played (retro arpeggio)")}catch(e){console.error("[AudioManager] Failed to play start sound:",e)}}playTone(e,t,n={}){if(!this.audioContext||!this.masterGainNode){this.log("Cannot play tone: AudioContext not initialized");return}let{type:i="sine",volume:s=.3,attack:o=.01,release:a=.1}=n;try{let l=this.audioContext,u=l.currentTime,c=l.createOscillator();c.type=i,c.frequency.setValueAtTime(e,u);let d=l.createGain();d.gain.setValueAtTime(0,u),d.gain.linearRampToValueAtTime(s,u+o),d.gain.setValueAtTime(s,u+t-a),d.gain.linearRampToValueAtTime(0,u+t),c.connect(d),d.connect(this.masterGainNode),c.start(u),c.stop(u+t),this.log(`Tone played: ${e}Hz for ${t}s`)}catch(l){console.error("[AudioManager] Failed to play tone:",l)}}playNote(e,t,n={}){let i=this.noteToFrequency(e);if(i===null){console.warn(`[AudioManager] Invalid note: ${e}`);return}this.playTone(i,t,n)}noteToFrequency(e){let t=/^([A-Ga-g])([#b]?)(\d)$/,n=e.match(t);if(!n)return null;let[,i,s,o]=n,a=parseInt(o,10),l={C:0,D:2,E:4,F:5,G:7,A:9,B:11}[i.toUpperCase()];if(l===void 0)return null;s==="#"?l+=1:s==="b"&&(l-=1);let u=l+(a+1)*12;return 440*Math.pow(2,(u-49)/12)}async resumeContext(){this.audioContext&&this.audioContext.state==="suspended"&&(await this.audioContext.resume(),this.log("AudioContext resumed"))}async suspendContext(){this.audioContext&&this.audioContext.state==="running"&&(await this.audioContext.suspend(),this.log("AudioContext suspended"))}getState(){var e;return((e=this.audioContext)==null?void 0:e.state)??null}getSoundBank(){return this.soundBank}play(e,t={}){if(!this.audioContext||!this.masterGainNode||!this.soundBank)return this.log("Cannot play: not initialized"),null;let n=this.soundBank.get(e);if(!n)return console.warn(`[AudioManager] Sound not found: ${e}`),null;try{let i=this.audioContext,s=t.instanceId??this.nextInstanceId++;t.instanceId!==void 0&&t.instanceId>=this.nextInstanceId&&(this.nextInstanceId=t.instanceId+1);let o=i.createBufferSource();o.buffer=n.buffer,o.loop=t.loop??!1,o.playbackRate.value=t.pitch??1;let a=i.createGain(),l=t.volume??1,u=t.fadeIn??0,c={source:o,gainNode:a,soundName:n.name,stopped:!1,baseVolume:l,targetVolume:l,fadingOut:!1,paused:!1,pausedAt:0,startedAt:i.currentTime,loop:t.loop??!1,playbackRate:t.pitch??1,buffer:n.buffer,outputNode:a},d=l,h=l;if(t.position){let{pan:m,distanceVolume:S}=this.calculateSpatialAudio(t.position.x,t.position.y),w=i.createStereoPanner();w.pan.value=m,d=u>0?0:l*S,h=l*S,a.gain.setValueAtTime(d,i.currentTime),u>0&&(a.gain.linearRampToValueAtTime(h,i.currentTime+u),this.log(`Fade in: ${n.name} [#${s}] over ${u}s`)),o.connect(a),a.connect(w),w.connect(this.masterGainNode),c.pannerNode=w,c.position={x:t.position.x,y:t.position.y},c.targetVolume=h,c.outputNode=w,this.spatialSounds.set(o,{gainNode:a,pannerNode:w,position:{x:t.position.x,y:t.position.y},baseVolume:l}),this.log(`Playing spatial: ${n.name} [#${s}] at (${t.position.x}, ${t.position.y}) pan=${m.toFixed(2)} vol=${S.toFixed(2)}`)}else d=u>0?0:l,h=l,a.gain.setValueAtTime(d,i.currentTime),u>0&&(a.gain.linearRampToValueAtTime(h,i.currentTime+u),this.log(`Fade in: ${n.name} [#${s}] over ${u}s`)),o.connect(a),a.connect(this.masterGainNode);this.instances.set(s,c),(t.lowpass||t.highpass||t.reverb)&&this.setEffects(s,t.lowpass,t.highpass,t.reverb),this.instancesBySound.has(n.name)||this.instancesBySound.set(n.name,new Set),this.instancesBySound.get(n.name).add(s),this.activeSounds.add(o),o.onended=()=>{c.paused||this.cleanupInstance(s)},o.start(0,t.offset??0),t.position||this.log(`Playing: ${n.name} [#${s}]`);let f=this.stop.bind(this),p=this.instances;return{instanceId:s,stop:()=>{f(s)},get playing(){let m=p.get(s);return m!==void 0&&!m.stopped},sound:n}}catch(i){return console.error(`[AudioManager] Failed to play sound "${e}":`,i),null}}stop(e){return e==="all"?this.stopAll():typeof e=="number"?this.stopInstance(e)?1:0:this.stopByName(e)}fadeOut(e,t){if(!this.audioContext)return 0;let n=Math.max(.01,t);return e==="all"?this.fadeOutAll(n):typeof e=="number"?this.fadeOutInstance(e,n)?1:0:this.fadeOutByName(e,n)}fadeOutInstance(e,t){let n=this.instances.get(e);if(!n||n.stopped||n.fadingOut||!this.audioContext)return!1;let i=this.audioContext;n.fadingOut=!0;let s=n.gainNode.gain.value;return n.gainNode.gain.cancelScheduledValues(i.currentTime),n.gainNode.gain.setValueAtTime(s,i.currentTime),n.gainNode.gain.linearRampToValueAtTime(0,i.currentTime+t),setTimeout(()=>{this.stopInstance(e)},t*1e3),this.log(`Fading out instance #${e} (${n.soundName}) over ${t}s`),!0}fadeOutByName(e,t){let n=this.instancesBySound.get(e);if(!n||n.size===0)return 0;let i=0;for(let s of Array.from(n))this.fadeOutInstance(s,t)&&i++;return this.log(`Fading out ${i} instances of "${e}" over ${t}s`),i}fadeOutAll(e){let t=0;for(let n of Array.from(this.instances.keys()))this.fadeOutInstance(n,e)&&t++;return this.log(`Fading out all sounds (${t} instances) over ${e}s`),t}pause(e){return e==="all"?this.pauseAll():typeof e=="number"?this.pauseInstance(e)?1:0:this.pauseByName(e)}pauseInstance(e){let t=this.instances.get(e);if(!t||t.stopped||t.paused||t.fadingOut||!this.audioContext)return!1;let n=(this.audioContext.currentTime-t.startedAt)*t.playbackRate;if(t.loop)t.pausedAt=n%t.buffer.duration;else if(t.pausedAt=n,t.pausedAt>=t.buffer.duration)return!1;try{t.source.stop()}catch{}return t.paused=!0,this.log(`Paused instance #${e} (${t.soundName}) at ${t.pausedAt.toFixed(2)}s`),!0}pauseByName(e){let t=this.instancesBySound.get(e);if(!t||t.size===0)return 0;let n=0;for(let i of Array.from(t))this.pauseInstance(i)&&n++;return this.log(`Paused ${n} instances of "${e}"`),n}pauseAll(){let e=0;for(let t of Array.from(this.instances.keys()))this.pauseInstance(t)&&e++;return this.log(`Paused all sounds (${e} instances)`),e}resume(e){return e==="all"?this.resumeAll():typeof e=="number"?this.resumeInstance(e)?1:0:this.resumeByName(e)}resumeInstance(e){let t=this.instances.get(e);if(!t||t.stopped||!t.paused||!this.audioContext||!this.masterGainNode)return!1;let n=this.audioContext,i=n.createBufferSource();return i.buffer=t.buffer,i.loop=t.loop,i.playbackRate.value=t.playbackRate,i.connect(t.gainNode),t.source=i,t.paused=!1,t.startedAt=n.currentTime-t.pausedAt/t.playbackRate,i.onended=()=>{t.paused||this.cleanupInstance(e)},i.start(0,t.pausedAt),this.log(`Resumed instance #${e} (${t.soundName}) from ${t.pausedAt.toFixed(2)}s`),!0}resumeByName(e){let t=this.instancesBySound.get(e);if(!t||t.size===0)return 0;let n=0;for(let i of Array.from(t))this.resumeInstance(i)&&n++;return this.log(`Resumed ${n} instances of "${e}"`),n}resumeAll(){let e=0;for(let t of Array.from(this.instances.keys()))this.resumeInstance(t)&&e++;return this.log(`Resumed all sounds (${e} instances)`),e}stopInstance(e){let t=this.instances.get(e);if(!t||t.stopped)return!1;try{t.source.stop(),t.stopped=!0,this.log(`Stopped instance #${e} (${t.soundName})`)}catch{}return this.cleanupInstance(e),!0}stopByName(e){let t=this.instancesBySound.get(e);if(!t||t.size===0)return 0;let n=0;for(let i of Array.from(t))this.stopInstance(i)&&n++;return this.log(`Stopped ${n} instances of "${e}"`),n}cleanupInstance(e){let t=this.instances.get(e);if(!t)return;this.instances.delete(e);let n=this.instancesBySound.get(t.soundName);n&&(n.delete(e),n.size===0&&this.instancesBySound.delete(t.soundName)),this.activeSounds.delete(t.source),this.spatialSounds.delete(t.source)}resolveSoundIdToName(e){var t;return this.soundBank?((t=this.soundBank.get(e))==null?void 0:t.name)??null:null}stopBySoundId(e){let t=this.resolveSoundIdToName(e);return t?this.stopByName(t):(this.log(`stopBySoundId: Unknown soundId ${e}`),0)}fadeOutBySoundId(e,t){let n=this.resolveSoundIdToName(e);return n?this.fadeOutByName(n,t):(this.log(`fadeOutBySoundId: Unknown soundId ${e}`),0)}pauseBySoundId(e){let t=this.resolveSoundIdToName(e);return t?this.pauseByName(t):(this.log(`pauseBySoundId: Unknown soundId ${e}`),0)}resumeBySoundId(e){let t=this.resolveSoundIdToName(e);return t?this.resumeByName(t):(this.log(`resumeBySoundId: Unknown soundId ${e}`),0)}setListenerPosition(e,t){e===this.spatialConfig.listenerX&&t===this.spatialConfig.listenerY||(this.spatialConfig.listenerX=e,this.spatialConfig.listenerY=t,this.spatialSounds.size>0&&this.updateAllSpatialSounds())}updateAllSpatialSounds(){for(let[e,t]of this.spatialSounds){if(!this.activeSounds.has(e)){this.spatialSounds.delete(e);continue}let{pan:n,distanceVolume:i}=this.calculateSpatialAudio(t.position.x,t.position.y);t.pannerNode.pan.value=n,t.gainNode.gain.value=t.baseVolume*i}}getListenerPosition(){return{x:this.spatialConfig.listenerX,y:this.spatialConfig.listenerY}}configureSpatial(e){this.log(`configureSpatial called with: ${JSON.stringify(e)}`),e.listenerX!==void 0&&(this.spatialConfig.listenerX=Math.max(0,Math.min(65535,e.listenerX))),e.listenerY!==void 0&&(this.spatialConfig.listenerY=Math.max(0,Math.min(65535,e.listenerY))),e.maxDistance!==void 0&&(this.spatialConfig.maxDistance=Math.max(1,e.maxDistance)),e.referenceDistance!==void 0&&(this.spatialConfig.referenceDistance=Math.max(1,e.referenceDistance)),e.rolloffFactor!==void 0&&(this.spatialConfig.rolloffFactor=Math.max(0,e.rolloffFactor)),e.panSpread!==void 0&&(this.spatialConfig.panSpread=Math.max(0,Math.min(1,e.panSpread))),this.log(`spatialConfig now: maxDistance=${this.spatialConfig.maxDistance}, refDist=${this.spatialConfig.referenceDistance}, panSpread=${this.spatialConfig.panSpread}`)}getSpatialConfig(){return{...this.spatialConfig}}setEffects(e,t,n,i){if(!this.audioContext||!this.masterGainNode)return;let s=this.instances.get(e);if(!s||s.stopped){this.log(`setEffects: instance ${e} not found or stopped`);return}let o=this.audioContext;t!==void 0&&(t>0?(s.lowpassNode||(s.lowpassNode=o.createBiquadFilter(),s.lowpassNode.type="lowpass",s.lowpassNode.Q.value=1,this.insertFilterNode(s,s.lowpassNode)),s.lowpassNode.frequency.setValueAtTime(t,o.currentTime),this.log(`setEffects: instance ${e} lowpass=${t}Hz`)):s.lowpassNode&&(this.removeFilterNode(s,s.lowpassNode),s.lowpassNode=void 0,this.log(`setEffects: instance ${e} lowpass disabled`))),n!==void 0&&(n>0?(s.highpassNode||(s.highpassNode=o.createBiquadFilter(),s.highpassNode.type="highpass",s.highpassNode.Q.value=1,this.insertFilterNode(s,s.highpassNode)),s.highpassNode.frequency.setValueAtTime(n,o.currentTime),this.log(`setEffects: instance ${e} highpass=${n}Hz`)):s.highpassNode&&(this.removeFilterNode(s,s.highpassNode),s.highpassNode=void 0,this.log(`setEffects: instance ${e} highpass disabled`))),i!==void 0&&(i>0?(this.ensureReverbInitialized(),!s.reverbSendNode&&this.reverbConvolver&&(s.reverbSendNode=o.createGain(),s.reverbSendNode.gain.value=0,s.outputNode.connect(s.reverbSendNode),s.reverbSendNode.connect(this.reverbConvolver)),s.reverbSendNode&&(s.reverbSendNode.gain.setValueAtTime(i,o.currentTime),this.log(`setEffects: instance ${e} reverb=${i.toFixed(2)}`))):s.reverbSendNode&&(s.reverbSendNode.gain.setValueAtTime(0,o.currentTime),this.log(`setEffects: instance ${e} reverb disabled`)))}ensureReverbInitialized(){if(this.reverbConvolver||!this.audioContext||!this.masterGainNode)return;let e=this.audioContext,t=e.sampleRate,n=Math.floor(t*.5),i=e.createBuffer(1,n,t),s=i.getChannelData(0);for(let o=0;o<n;o++){let a=o/t,l=Math.exp(-a*6);s[o]=(Math.random()*2-1)*l}this.reverbConvolver=e.createConvolver(),this.reverbConvolver.buffer=i,this.reverbGain=e.createGain(),this.reverbGain.gain.value=.5,this.reverbConvolver.connect(this.reverbGain),this.reverbGain.connect(this.masterGainNode),this.log("Shared reverb initialized")}insertFilterNode(e,t){if(this.masterGainNode){try{e.outputNode.disconnect(this.masterGainNode)}catch{}e.outputNode.connect(t),t.connect(this.masterGainNode)}}removeFilterNode(e,t){if(this.masterGainNode){try{t.disconnect()}catch{}try{e.outputNode.disconnect(t)}catch{}e.outputNode.connect(this.masterGainNode)}}calculateSpatialAudio(e,t){let{listenerX:n,listenerY:i,maxDistance:s,referenceDistance:o,panSpread:a}=this.spatialConfig,l=e-n,u=t-i,c=Math.sqrt(l*l+u*u),d;c<=o?d=1:c>=s?d=0:d=1-(c-o)/(s-o);let h=0;return s>0&&a>0&&(h=l/s*a,h=Math.max(-1,Math.min(1,h))),{pan:h,distanceVolume:d}}stopAll(){let e=this.instances.size;for(let[,t]of this.instances)if(!t.stopped)try{t.source.stop(),t.stopped=!0}catch{}return this.instances.clear(),this.instancesBySound.clear(),this.activeSounds.clear(),this.spatialSounds.clear(),this.log(`Stopped all sounds (${e} instances)`),e}getPlayingCount(){return this.instances.size}getActiveInstances(){return Array.from(this.instances.keys())}isPlaying(e){let t=this.instances.get(e);return t!==void 0&&!t.stopped}destroy(){this.stopAll(),this.soundBank&&(this.soundBank.clear(),this.soundBank=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.masterGainNode=null,this.initialized=!1,this.log("AudioManager destroyed")}log(e){}};Rw(Bw,"AudioManager");var zw=Bw,Dw=Object.defineProperty,kE=(r,e,t)=>e in r?Dw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ar=(r,e)=>Dw(r,"name",{value:e,configurable:!0}),se=(r,e,t)=>(kE(r,typeof e!="symbol"?e+"":e,t),t),Df=(r=>(r.TerminalGL="webgl",r.Terminal2D="terminal2d",r))(Df||{}),Ow=class{constructor(e=60){if(se(this,"frameCount",0),se(this,"fps",0),se(this,"fpsUpdateTime",0),se(this,"lastCoreTime",0),se(this,"lastRenderTime",0),se(this,"lastTotalTime",0),se(this,"coreTimeSamples",[]),se(this,"renderTimeSamples",[]),se(this,"totalTimeSamples",[]),se(this,"maxSamples"),e<=0)throw new Error("maxSamples must be positive");this.maxSamples=e}startTracking(e){this.fpsUpdateTime=e,this.frameCount=0,this.fps=0}updateFPS(e){this.frameCount++,e-this.fpsUpdateTime>=1e3&&(this.fps=Math.round(this.frameCount*1e3/(e-this.fpsUpdateTime)),this.frameCount=0,this.fpsUpdateTime=e)}recordFrameTiming(e,t){let n=e+t;this.lastCoreTime=e,this.lastRenderTime=t,this.lastTotalTime=n,this.coreTimeSamples.push(e),this.renderTimeSamples.push(t),this.totalTimeSamples.push(n),this.coreTimeSamples.length>this.maxSamples&&(this.coreTimeSamples.shift(),this.renderTimeSamples.shift(),this.totalTimeSamples.shift())}getFPS(){return this.fps}getLastFrameTiming(){if(!(this.lastCoreTime===0&&this.lastRenderTime===0))return{coreTime:this.lastCoreTime,renderTime:this.lastRenderTime,totalTime:this.lastTotalTime}}getAverageFrameTiming(){if(this.coreTimeSamples.length!==0)return{coreTime:this.average(this.coreTimeSamples),renderTime:this.average(this.renderTimeSamples),totalTime:this.average(this.totalTimeSamples)}}getStats(){return{fps:this.fps,lastFrame:this.getLastFrameTiming(),avgFrame:this.getAverageFrameTiming(),sampleCount:this.coreTimeSamples.length,maxSamples:this.maxSamples}}reset(){this.frameCount=0,this.fps=0,this.fpsUpdateTime=0,this.lastCoreTime=0,this.lastRenderTime=0,this.lastTotalTime=0,this.coreTimeSamples=[],this.renderTimeSamples=[],this.totalTimeSamples=[]}average(e){return e.length===0?0:e.reduce((t,n)=>t+n,0)/e.length}};Ar(Ow,"PerformanceMonitor");var EE=Ow,ME="iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAR8ElEQVR4Ae3BC3JbW5AkwUgOFy6uPCe6rcas5tgFBFDQ74nu4R9XcUfEHRV3RPzB3nlQxRKxVCwRo0JRhSIOVcSFihFxoYr4CSqWiCViqThULBGjYom4oUIRqlCEKhRVEapQhKo3HlChDFQxKg4VqhgVo2KpUMWhYqk4VKjihg5uyOBQ5VAxoh4iDhEXKpSBKi5U3FBxiCoOVfTGH6BiqVgiloilYqk4VIyKQ8SI+AkqFPGTVByiilFF6I2fLOJCxIhYIpYKRajiL9LBEjEi1IEifoHwoIolYqlYIpaKEXGhirihirihirihQhGjYkSoYkSoYolQhSKWiiVCFYo4VChiqThELBVLxKiiCkVV/ge/UBXxCRUj4lAxIh5UcUfEHRV3RBVLxFJxIUIVS8SFCkWMKkIVilAV/nEVd0TcUXFHxIMqFPGLhL9ExSHiyw8JSxVxRxVxoUIRS4UiVKEIVdwQVShiVCjiQRWKuFChiCdVKOKOCkU8qYp4oTdGxYMqDhWj4kEVihgRS4Q6UAYPqhgVh4pRMfodqGJU3FAxKg4dXKj4jg5u6GB5QxVPqhgVh4oXqVCEKp5QcagYFYeKB1QcKg4Vh4oHVIweGBWj4kHvKKp4QsSIUIUiHhR18EkVFyIUoQpFjIobqqjiQlTxk0UVijhUHKoIVSwVyv9gqSLuqCKWigsRT6hQVKEIVYyIpeJChCouRBV3RKhiiRgVS8SFiiVCFRcilirihgpFHCqWCIUXqVgiRoUiVKGIpUJRxRKhCkWMigsRo2KJeFKFIg4VirijQhEvVqGICxWKGOGFKhTxQhVLxCdUKOLL/3rnCRWKWCoUdUQsFYoqFHGoUMQh4oaKEfFJFYpYKhTxH/LGH6KD0cGFDkaFIlTxCRWKOESo4tDB6ODQwW/Wgd74BSpGxahQhSKUBWWgCkW8UIUibohQxRKhDhTxB6pQhMITKhTxpApFFYoYFYeIpUIRh4oR8aQKRdxRoQhV3BFVXIh4QMWFiCdUKGKEJ1Qo4gkVN0QsVVShCFUo4lChqEJRFfGACkXcUaGIpWKJOFQo4herUMQSfpEKRRWKUMWFCFUoQhWKUIUiVKGIJ1Qo4kKFIpYKRahCEUuFIi5UKOITKhSxVCjiEJ5QoYgnVSiqUMRSoYg7KhQxKkZUoYgnVChiqVDET1KhiE+oUMSXv0sHv1gYFUvEoUIRh4olYqlYIi5UKGJUXIhYKkbEqLgQMSqWiKViifgJKhTxhApFXKhYIhRUoQhVKGJUjIilQhGqUIQqFKEKRSwVI2JUKOKGCkV8R4UiVKEIVShCFYpQhSJeqEIRn1ChiKVCEapQ9M6h4kJUcSHijojvqPiOihExKhTxHRWKeLEKRVyoUMShQhGHigsRS9QRMSJGhSIUVHEhYqlQxA0VijhUjIhRoahCETdUKEIVh4hDhSIOFUvEUnGIWCoUcaFCEUuFIl6gQhFLhSJGUMWIKhSxVCjiQoUi7qhQhCouRFyoUIQqFKEKRYwKRRwqFKEKRVyoUMSLVCjiUHEh4lChiEOFIsY7S8QnVSjiUKGICxGjQhGjQhG/WYUiDhWKuFChiEPUEbFEPKBCERciDmFULBGj4kKEKi5EjIol4kKFIpaKJWKpWCKWCkVcqFgilooRcaFCERcqFHFDhSKeUKGIGyoU8eXX6uAPE0bFErFULBGj4hCxVCwRo2KJWCouRKjiQsSoWCJGhSJUoQhVXIgYFYcIVShCFYpQhSIuVChiVCiqUIQqFDEqlgi9oQploIpRoQxUcchAFaNCGajiEKGKCzlwyIFRoQxU8aAMRgZLBiPiQoUinlShiidUKANV6I1DxU+WwYUIVfwkGfxiFYr4pIobKp70zoWo4lBxR8WIeLGKEXGoGBEXKkbEUvGTRXxSVEUVFyqe8MaFigsZ3JCBKl4sCxeycEPEDRn8RBU/IOKGiCe9ccjCT9LBhQpF/CU6+I4IVfwkEU94R1EHI+JJFSNiRB2MiEOFIi5ULBEPiDoYEQ+qWCoUoagDRdwQdUQsFUvEC0QdjIgvX4IqDhFLxRIxKg4RS8USMSouRKhCEapQhCoUoQpFqEIRo0JRhSJUoQhVKEIVilDFhYhRsUQ8oWKJOFQo4kFvLBmoYlQoA1UcMlDFqFAGqhgZjAz+EjlwRwZLB3dkcEPFqHjQG79BBn+ICHWgiE+oUMSDIlTxCRXKQBUPeGPpQBFP6kARI0Jd+E0qLkSMiCVCHSjiUKGIJ0Wo4kkZjAwe8MaShRuqiAsRN2RBFb9YhSoOFaPiEDEiDhWK+KQIVfwib3xCFXEhQhWjg58kQh0o4kLEoUIZqOJBFYr4QRGq+AXeeUDUEXVEPCDqYEQ8KOpgRCxRhSIuRCiqeLGKJeJQoYgbIg4Vn1Dx5cstYVQo4kkViniBCkU8oWJEPKhCEXdUKOKGCkWMCkXcUDEifpE3RoQq/kIVilDFi2VwRwZPivgN3lmijoilYok4VIyIpWKJWCruqFgibog4VBwilooRsVSMiAsVI+KGCkU8oEIRqlCEKg4RS8USoTcOGRyyoIpDBqoYFcpAFaNCGRwqlIEqRsXoYKlQBjdkoIol4jsivqNCEU/qYFQsGahiVCgDVeidB1W8SMQnVFyIKhTxh6pQxCdEVVTxAu88oEIRqvgBFYp4QsQnRB38RlFHxB/gjQdEqIMbOlDEiFAHihgR6uAQoS48KQufUDEqlg4eEKGKpWJU3BDxpAh1oAiFf0TFEvFCFSPiLxH+EBWK+A+rGBFLhSKWihFxoUIRo4q4440vv0yFMnhQBqo4VCiqUMWhg+UdVRwilopDhCoUVShiqThEqGJUKGJUKEIVilCFIlShCFUoYlQoqlCEKhShCkWoQhGquBDxi0QoqlDEqBhVhN5YMlDFqFAGN1QRqhgVyoERMTL4SSoOEepAEQ/KwogYHSjikyLUwYhYMhgVhwq98UIRymBEqAt/mIgR8QkVilgyUMUnVSiDF3hnqRgRI+rgkyJGR8SFCkU8IOpgRBwqVHGoGFXEiDq4oUIRf5gIVShiBFUo4gEVilCFIi5UHCIOFSNiqThELBWKOFQoqlCEKhShCkVcqFCEKi5EHCpGxFKhiKViRHxCxRKhoApFPKBCEf+IiiXiPyCMiiViVChCFYo4VCjiUKGIpUIRqlDEqFDEDRWK+IQKRSwVilCFIkaFIg4VilCFIpYKRRwqFHGoUIQqFLFUKGLrYHTwpA4OHYwOntTBhYpR8YQORgdP6uBJHYwODh18QsWoGEEVirhQoQhVKGJULBFLxRKxVCwRS8USsVQsEUvFErFULBFLxRKxVCwRhwpFvFjFErFULBH/Twc3dDA6GB2MDm7o4IYObujghg5GBzd0MDoYHYwORgejg0MHN3RwQweHDkYHo4PRgd65UKGIJ1TcUHFHxR0Vd1T8oIo7Ku6o+I0q7qg4vKOogxHxpIgLFYpQxVKhCFUsFYpQxVKhCFUsUQcj4hBxR8QdEb9RhCouRKhivDEiRsQSoQ4OEerCEqEODhHq4BChDg4R6uBCxIhYItSFJUJdWCLUhb9NB/9RHXz5/7wzIlShiCdUXIgYFYpYKhShCkWMCkXcUKGIJ1QoQhWKUIUiVKEIVShCFYp4QsWIGBWKUIUiVHGIuFAx8j9YKhTxhApFFYoYFYpQhSKeUKGIpUIRqlDEUqGI36BCEYcKRRWKUIUiVKEIVShCFYpYKhRVKKjiQoQqFFWMCFUoqlDEUrFELBVLxFKxRLxIhSJUoYhRsUSMCkWoQhGj4hAxKhRxoWKJGBWHiEOFIsb/Qd+Eoo+F8TEqFH0bH/om9E2Mb+NDFYo+9G18CFUo+tC38SFUoehD38aHUPVNH0LVN30IVd/0IVR904fQN6EPoW9CH0IVij70bXwIfRP6EPom9CFUoehjYVSMb+NDjIrDN30IfROKPkb1IUbF+KYPoXeWihExKpaKC1GFIv4SUQe/QVShiEOEKhRxR8UhqlDEeGeJOFQoqlDEf0zEqHihqIMl4gEVS4UiDhWjirgjqOJChCpGVDGiCkUVS4QqloilYolYKpaIpeIQMSoOEaNiiVgqloilYok4VChiqbgQsVQoYqlQhCoUVSiqUMQIX/6TKhRVjIglHCoUcaFCERcqFHGhQhFLhaIKRYwKRRWKWCpGxKFiRBwqFPFCFYq4UKGIOyoU8SJhqVDEhQpFXKhQxIUKRSwViioUMSoUVSjihgpFjApFFYr4ySpGxKFiRPxib4yKUXEhgwsVo+JCBocMlMENEao4dPBJHbxQxIUKRVyoOHRwoQN1oA7UwfLOiBgdEUuFIpYKRagjQhWKUIUiVHGIOFQRFyoUVTypQhFLxQ1RxQ0RFyruqHhChaIKRSjqiDoi9M6o+M0i1BFxqLgQdXAh6kARo0IRN0RciDhU3FChiAsVilgqRhWhCkUViliijqgjekcVilDFHyiquCHijogHVCjiBSJUoYglQhWKeFDUEXVEjApFFYpQGBWHiKVCEYeKJWKpOESoQhGqUIQqFKEKRYyKQ8SoOESMiiXihSoUcaHiELFUKOJQoahCUYWiCkWM8OWnq1BUMSIuVCjiV6lYKlSxVCwVqlCFKg4d3NDBDR1c6EAdvFAH6mDpQB08oQN1sHSgDg4dPOGtQhGqUIQiVKEIVSiqoiqqooovf7S3CFUoQhWqUIQqFKEqqqIqqiK+/NHeqwxUZaAIVRmoyqiiKqqiKuKOijsqDlWEKu6ouCGquBChiqVCEQ+ouBChiqVCEaq4oeJCFaGKQ8SpYqlQxVKxVKhCFao4dHBDBzd04dCBOlg6UAeHLhw6UAdLB+pg6UAd/GIdLG8VilCFIhShCkWoQlEVVVEVVfwEET9RxD/iLUIVilCFKhShCkWoiqqoiqqIL3+0twpFqEIRilCFIlShqIqqqIoqvvzR3iNGxQ1RhTIYEYpQhCKeEPFJUUfEkyoUVShiRIyIJ0WMiEOFogpFPKhCUYUivuONL/+0N/6DunBHxT8uLBUvFjEqXixiVBwiVKGoYkSo4kKEKn6CCFX8Bu8sET+gQhF3RHxChSLuiHhAxIh4QFShiAdVKKpQxCGqUMSDKhRVKOI73vnyR6u4I+KOijve+fJHi/gBEXe88eWfFkaFogpFvFCFIg4ViioU8UIVijhUKKpQxFKhiAdV3BFxR8UScUfFE9748k9748s/7b1iqRgVPyjiUDEiloobKg4RqjhEFYeKGypGxRMq/jLhRSoUVSjiF6lQVKGIpUIRhwpFFYp4QoUiRsULRdxRsUTc8c53VNwR8aCKQ8SDKg4Rd1QcKkbEP+yd74gYFYr4hIgXiHhQxKhQxJf/9caXf1p4QMUhYlRciHhAxYWIX6hCEYeKJWKpWCIOFSPikyoUsVQsEaNiiVB4QIUiVKEIVShCFYp4QIUifoOKCxGqUIQqFKEKRahCEaNCET+gQhFLhSIOFYpQhaJ3VLFEFYp4UsRScUNGR8SFigtRhSJUoQhVXIgqFFUo6oh4gagjYqlQVDEiVHGoIlShiCe9VSgDVVzoQBEPihgRI2JEqOJQoQxGxAMyGBk8qYNPqBgVo0JRhSLUgSJGhCqWHnjAO0+IUEfEi1Qo4g8VoYol6mBEjApFqCPihSKe9BahDhTxC1Uo4gd0oIgHRKhiVCjiARXKQBUPiFCFogploIpRoQhFqOJJ7yjiEHGhQhEvVrFEKOpgRBwiPiFCFYpYog5GxIOiDkbEiFgiLkTcEHUwIhSxRDyjgz9UB/9BHfwk4QkVijhUKOKOCkVcqBgRS4UiXqxiRPwkFUtUoahCEaNiiXiRoIoLEUuFIi5UKOJChSIuVCiqUMSoUMSFCkUsFSOqUIQqFFUo4ieoUMRSoahCEYcKRbzAO4q4o2KpUMQSdUQsFYr4SSIOFYo6UMRfpkIRh4ol4gHvqOJChCJUoYgLFYo4RB0R3xHxoIoLGYyIC1EHirhQoYhfrEIRL/SOIn5QhSJuiDoiXiTijooRVShiRPygCkWMihHxCRWjQhEvEFRxIeIXqlDEqFBUoYgLFYoYFYoqRsQvUqGoQhEvVLFEPCA8oOJChCouRKjiQsRSoYhRoahCEX+ZiiXiDxD+IBWKWCpGxF+qYkT8Af4vDu0nt4v6zWEAAAAASUVORK5CYII=",Fo={glyphWidth:8,glyphHeight:8,cellWidth:8,cellHeight:8,atlasBlocks:1};function Fw(){if(typeof atob=="function"){let r=atob(ME),e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}throw new Error("[UTSP] decodeDefaultAtlas: atob() is not available in this environment")}Ar(Fw,"decodeDefaultAtlas");var Lw=class{constructor(e,t={}){se(this,"renderer"),se(this,"options"),se(this,"layerFilter",null),this.renderer=e,this.options={debug:t.debug??!1,useImageDataRendering:t.useImageDataRendering??!1}}setLayerFilter(e){this.layerFilter=e}getLayerFilter(){return this.layerFilter}async initialize(e){if("setImageDataRendering"in this.renderer&&this.options.useImageDataRendering&&(this.renderer.setImageDataRendering(!0),this.log("ImageData rendering enabled")),"setImageFont"in this.renderer&&typeof this.renderer.setImageFont=="function"){this.log("Loading default 8x8 font atlas...");let t=Fw();await this.renderer.setImageFont(t,Fo.glyphWidth,Fo.glyphHeight,Fo.cellWidth,Fo.cellHeight,Fo.atlasBlocks),this.log("Default 8x8 font atlas loaded")}await this.waitForReady(),this.log("Initialized and ready")}async waitForReady(e=100,t=50){this.log("Waiting for renderer to be ready");let n=0;return new Promise((i,s)=>{let o=Ar(()=>{if(n++,this.renderer.isReady())this.log(`Renderer ready after ${n*t}ms`),i();else if(n>=e){let a=`Renderer failed to be ready after ${e*t}ms`;this.log(a),s(new Error(a))}else setTimeout(o,t)},"check");o()})}async loadDefaultFont(e){console.warn("[RendererManager] loadDefaultFont() is deprecated. Use ImageFont instead.")}renderDisplay(e){return!this.renderer.isReady()||!e?!1:(this.renderer.renderDisplayData(e),!0)}render(e,t){let n=this.layerFilter?e.getRenderState(t,this.layerFilter):e.getRenderState(t);return!n||n.displays.length===0?!1:this.renderDisplay(n.displays[0])}getRenderer(){return this.renderer}getCanvas(){return this.renderer.getCanvas()}getAvailableSize(){if(this.renderer.getAvailableSize)return this.renderer.getAvailableSize();let e=this.getCanvas();return{width:(e==null?void 0:e.clientWidth)||(e==null?void 0:e.width)||0,height:(e==null?void 0:e.clientHeight)||(e==null?void 0:e.height)||0}}isReady(){return this.renderer.isReady()}destroy(){this.log("Destroying renderer"),this.renderer.destroy()}log(e){}};Ar(Lw,"RendererManager");var cm=Lw,_w=class{constructor(e){if(se(this,"core"),se(this,"rendererManagers",new Map),se(this,"rendererInitPromises",new Map),se(this,"rendererManager"),se(this,"rendererType"),se(this,"primaryDisplayId",0),se(this,"displayConfigs"),se(this,"options"),se(this,"running",!1),se(this,"startTime",0),se(this,"lastTimestamp",0),se(this,"userId",""),se(this,"visibilityChangeHandler"),se(this,"tickRate",30),se(this,"accumulatedTime",0),se(this,"FRAME_TIME_MIN",1e3/60),se(this,"lastRenderTimestamp",0),se(this,"rafId",0),se(this,"firstTickDone",!1),se(this,"performanceMonitor"),se(this,"renderMode","continuous"),se(this,"renderRequested",!1),this.options={application:e.application,container:e.container,displayContainers:e.displayContainers,debug:e.debug??!1,renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,renderMode:e.renderMode??"continuous"},this.log("Initializing BaseClientRuntime"),this.core=new Nv({mode:"client",maxUsers:1}),this.core.onPaletteChanged(t=>{this.onCorePaletteChanged(t)}),this.core.onFontAllocated(()=>{this.onCoreImageFontAllocated(0)}),this.core.onFontBlockAdded(t=>{this.onCoreImageFontBlockAdded(0,t)}),this.core.onImageFontChanged(t=>{this.onCoreImageFontChanged(t)}),this.visibilityChangeHandler=()=>{!document.hidden&&this.running&&(this.lastTimestamp=performance.now(),this.accumulatedTime=0,this.log("Tab visible: Reset timing"))},document.addEventListener("visibilitychange",this.visibilityChangeHandler),this.rendererType=this.options.renderer,this.options.displayContainers&&this.options.displayContainers.length>0){this.displayConfigs=new Map([[0,{container:this.options.container,renderer:this.options.renderer}]]);for(let t of this.options.displayContainers){let n=t.renderer;this.displayConfigs.set(t.id,{container:t.container,renderer:n})}this.primaryDisplayId=0}else this.displayConfigs=new Map([[0,{container:this.options.container,renderer:this.options.renderer}]]),this.primaryDisplayId=0;this.createRendererManagers(),this.performanceMonitor=new EE(60),this.tickRate=20,this.renderMode=e.renderMode??"continuous",this.log(`Configured: tickRate=${this.tickRate}, renderMode=${this.renderMode}`),this.log("BaseClientRuntime initialized")}getMode(){return"client"}createRenderer(e,t){if(t==="terminal2d"){this.log("Creating Terminal 2D renderer");let s=new uk(e,{fixedCols:80,fixedRows:25,cellAspectRatio:1});return this.log("Canvas 2D renderer created successfully"),s}this.log("Creating TerminalGL renderer");let n=document.createElement("canvas").getContext("webgl");if(!n)throw new Error("WebGL not supported. TerminalGL requires WebGL 1.0.");if(!n.getExtension("OES_element_index_uint"))throw new Error("OES_element_index_uint extension not supported. TerminalGL requires this extension for large terminals (256x256).");if(!(e instanceof HTMLDivElement))throw new Error(`TerminalGL requires container to be an HTMLDivElement. Received: ${e.tagName}`);let i=new lk(e,{cols:80,rows:25,charWidth:8,charHeight:8});return this.log("TerminalGL created successfully"),i}createRendererManagers(){let e=this.displayConfigs.size>=3;this.rendererManagers.clear();for(let[n,i]of this.displayConfigs.entries()){let s=e?"terminal2d":i.renderer??this.options.renderer,o=this.createRenderer(i.container,s??"webgl"),a=new cm(o,{debug:this.options.debug,useImageDataRendering:this.options.useImageDataRendering});this.rendererManagers.set(n,a)}let t=this.rendererManagers.get(this.primaryDisplayId);if(!t)throw new Error(`Primary display ${this.primaryDisplayId} has no renderer. Check displayContainers configuration.`);this.rendererManager=t}ensureRendererManager(e){var a;let t=this.rendererManagers.get(e);if(t)return t;let n=document.createElement("div");n.dataset.displayId=String(e),n.style.cssText="position:relative;display:inline-block;margin:4px;background:#000;overflow:hidden;",(((a=this.options.container)==null?void 0:a.parentElement)??document.body).appendChild(n),this.displayConfigs.set(e,{container:n});let i=this.displayConfigs.size>=3?"terminal2d":this.options.renderer??"webgl",s=this.createRenderer(n,i),o=new cm(s,{debug:this.options.debug,useImageDataRendering:this.options.useImageDataRendering});if(this.rendererManagers.set(e,o),!this.rendererInitPromises.has(e)){let l=o.initialize(this.core).then(()=>{this.onCorePaletteChanged(this.core.getPalette());let u=this.core.getImageFontIds,c=typeof u=="function"?u.call(this.core):[];c.length>0&&this.onCoreImageFontChanged(c[0]);let d=this.rebuildPostProcessOverlays;typeof d=="function"&&d.call(this)}).catch(u=>{console.warn(`[BaseClientRuntime] Failed to init renderer for display ${e}:`,u)});this.rendererInitPromises.set(e,l)}return o}getRendererType(){return this.rendererType}disconnectUser(e,t="Disconnected"){return this.log(`disconnectUser called for ${e} (Reason: ${t}) - No-op in BaseClientRuntime`),!1}isRunning(){return this.running}setTickRate(e){if(e<0||e>1e3)throw new Error(`Invalid tick rate: ${e}. Must be between 0 and 1000.`);if(this.tickRate=e,this.userId){let t=this.core.getUser(this.userId);t&&t.setBytesTickRate(e>0?e:20)}e===0&&this.renderMode==="continuous"?(this.renderMode="on-demand",this.log("Tick rate set to 0, switched to on-demand render mode")):this.log(`Tick rate set to ${e} TPS`)}setRenderMode(e){this.renderMode=e,this.log(`Render mode set to ${e}`)}setMaxFPS(e){if(e<=0||e>240)throw new Error(`Invalid FPS: ${e}. Must be between 1 and 240.`);this.FRAME_TIME_MIN=1e3/e,this.log(`Max FPS set to ${e}`)}getTickRate(){return this.tickRate}requestRender(){this.renderMode==="on-demand"&&(this.renderRequested=!0,this.log("Render requested"))}async start(){if(this.running){this.log("Already running");return}this.log("Starting BaseClientRuntime"),await this.onBeforeStart();for(let[e,t]of this.rendererManagers.entries())await t.initialize(this.core),this.log(`Renderer for display ${e} is ready`);this.onCorePaletteChanged(this.core.getPalette()),this.log("Initial palette sent to renderers"),this.options.application&&(this.log("Calling application.init()"),await this.options.application.init(this,this.core)),await this.onAfterInit(),await this.createLocalUser(),this.running=!0,this.startTime=performance.now(),this.lastTimestamp=this.startTime,this.lastRenderTimestamp=this.startTime,this.accumulatedTime=0,this.firstTickDone=!1,this.performanceMonitor.reset(),this.performanceMonitor.startTracking(this.startTime),this.log("Starting main loop"),this.mainLoop(this.lastTimestamp)}async onBeforeStart(){}async onAfterInit(){}async stop(){var t;if(!this.running)return;this.log("Stopping BaseClientRuntime"),this.running=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0),await this.onStop();let e=this.core.getUser(this.userId);e&&((t=this.options.application)!=null&&t.destroyUser)&&this.options.application.destroyUser(this,this.core,e,"Runtime stopped"),this.log("BaseClientRuntime stopped")}async onStop(){}getStats(){let e=this.performanceMonitor.getStats();return{running:this.running,userCount:this.core.getUsers().length,fps:e.fps,uptime:this.running?performance.now()-this.startTime:0,totalFrames:0,lastFrameTiming:e.lastFrame,avgFrameTiming:e.avgFrame}}getTotalBytesReceived(){var e;return((e=this.core.getUser(this.userId))==null?void 0:e.getTotalBytesReceived())??0}getBytesReceivedPerSecond(){var e;return((e=this.core.getUser(this.userId))==null?void 0:e.getBytesReceivedPerSecond())??0}resetBytesReceived(){let e=this.core.getUser(this.userId);e&&e.resetByteCounters()}async destroy(){var e;await this.stop(),this.log("Destroying BaseClientRuntime"),this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=void 0),await this.onDestroy();for(let t of this.rendererManagers.values()){let n=t.getRenderer();n&&"clearOnResizeCallback"in n&&n.clearOnResizeCallback()}(e=this.options.application)!=null&&e.destroy&&this.options.application.destroy(this);for(let t of this.rendererManagers.values())t.destroy();this.log("BaseClientRuntime destroyed")}async onDestroy(){}async createLocalUser(){var s;this.userId="local",this.log(`Creating local user: ${this.userId}`);let e=this.core.createUser(this.userId,"User");e.setBytesTickRate(this.tickRate>0?this.tickRate:20),this.onUserCreated(e),(s=this.options.application)!=null&&s.initUser&&(this.log("Calling application.initUser()"),this.options.application.initUser(this,this.core,e,{username:"User"})),this.processInitialOrders(e);let t=this.core.generateAllLoadPackets();t.forEach(o=>{e.recordBytesReceived(o.length)});let n=this.core.generateMacroLoadPackets(this.userId);n.forEach(o=>{e.recordBytesReceived(o.length)});let i=e.getInputBindingsLoadPacket();i&&e.recordBytesReceived(i.length),this.log(`Simulated ${t.length} load packets, ${n.length} macro packets for byte counting`),this.log("Performing initial render"),this.core.endTick().forEach(({static:o,dynamic:a},l)=>{let u=this.core.getUser(l);u&&(o&&u.recordBytesReceived(o.length),a&&u.recordBytesReceived(a.length))})}processInitialOrders(e){if(e.hasPendingMacroOrders()){this.log("Applying macro orders from initUser()");let t=e.flushMacroOrders();e.applyMacroOrders(t)}}onUserCreated(e){}mainLoop(e){var u,c,d,h;if(!this.running){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0);return}if(this.renderMode==="on-demand"){this.renderRequested&&(this.renderRequested=!1,this.performanceMonitor.updateFPS(e),this.render()),this.rafId=requestAnimationFrame(f=>this.mainLoop(f));return}let t=e-this.lastRenderTimestamp;if(this.lastRenderTimestamp>0&&t<this.FRAME_TIME_MIN-1){this.rafId=requestAnimationFrame(f=>this.mainLoop(f));return}this.lastRenderTimestamp=e;let n=(e-this.lastTimestamp)/1e3,i=Math.min(n,.1);this.lastTimestamp=e,this.performanceMonitor.updateFPS(e);let s=this.core.getUser(this.userId);if(!s){this.rafId=requestAnimationFrame(f=>this.mainLoop(f));return}if(this.tickRate===0){let f=performance.now();this.render();let p=performance.now()-f;this.performanceMonitor.recordFrameTiming(0,p),this.rafId=requestAnimationFrame(m=>this.mainLoop(m));return}if(!this.firstTickDone){this.firstTickDone=!0,this.lastTimestamp=e,this.accumulatedTime=0,this.rafId=requestAnimationFrame(f=>this.mainLoop(f));return}this.accumulatedTime+=i;let o=1/this.tickRate;this.accumulatedTime>.5&&(this.accumulatedTime=o);let a=0,l=0;for(;this.accumulatedTime>=o&&a<5;){let f=performance.now();this.collectAndApplyInput(s),this.options.application&&((c=(u=this.options.application).update)==null||c.call(u,this,this.core,o),(h=(d=this.options.application).updateUser)==null||h.call(d,this,this.core,s,o)),this.processTickOrders(s);let p=s.updateMacros();s.processMacroEvents(p),this.core.endTick().forEach(({static:m,dynamic:S})=>{let w=((m==null?void 0:m.length)??0)+((S==null?void 0:S.length)??0);s.recordBytesReceived(w)}),l+=performance.now()-f,this.accumulatedTime-=o,a++}if(a>0){let f=performance.now();this.render();let p=performance.now()-f;this.performanceMonitor.recordFrameTiming(l,p)}this.rafId=requestAnimationFrame(f=>this.mainLoop(f))}collectAndApplyInput(e){}processTickOrders(e){if(e.clearTextInputs(),e.hasPendingMacroOrders()){let t=e.flushMacroOrders();e.applyMacroOrders(t)}}render(){let e=this.core.getUser(this.userId);if(e){let n=e.getMacroRenderOrders();for(let[i,s]of n){let o=e.getLayerById(i);o&&s.length>0&&o.addTemporaryOrders(s)}}let t=this.core.getRenderState(this.userId);if(!(!t||t.displays.length===0))for(let n of t.displays){let i=this.rendererManagers.get(n.id)??this.ensureRendererManager(n.id);if(!i)continue;let s=i.getLayerFilter(),o=s?this.core.getRenderState(this.userId,s):t;if(!o){this.options.debug&&this.log(`Render state unavailable for display ${n.id} with filter`);continue}let a=o.displays.find(u=>u.id===n.id);if(!a){this.options.debug&&this.log(`Render state missing display ${n.id} after filtering`);continue}if(!i.isReady()){this.options.debug&&this.log(`Renderer for display ${n.id} not ready yet`);continue}let l=i.getRenderer();(l.getCols()!==a.width||l.getRows()!==a.height)&&(this.options.debug&&this.log(`Resizing renderer ${n.id}: ${l.getCols()}x${l.getRows()} → ${a.width}x${a.height}`),l.resize(a.width,a.height)),i.renderDisplay(a)}}onCorePaletteChanged(e){this.log(`Palette changed, updating renderer (${e.size} colors)`);let t=[];for(let s=0;s<256;s++){let o=e.get(s);o?t.push({r:o.r,g:o.g,b:o.b,a:o.a}):t.push({r:0,g:0,b:0,a:0})}let n=Ar(s=>{s&&"setPalette"in s&&typeof s.setPalette=="function"&&s.setPalette(t)},"applyPalette"),i=0;for(let s of this.rendererManagers.values()){let o=s.getRenderer();o&&(n(o),i++)}i===0||this.log(`✓ Palette updated on ${i} renderer(s)`)}onCoreImageFontAllocated(e){let t=this.core.getImageFont(e);if(!t)return;this.log(`Allocating image font ${e} structure: blocks=${t.getAtlasBlocks()}, size=${t.getGlyphWidth()}x${t.getGlyphHeight()}`);let n=Ar(i=>{i&&typeof i.setImageFontStructure=="function"&&i.setImageFontStructure(t.getGlyphWidth(),t.getGlyphHeight(),t.getCellWidth(),t.getCellHeight(),t.getAtlasBlocks())},"applyStruct");for(let i of this.rendererManagers.values()){let s=i.getRenderer();s&&n(s)}}onCoreImageFontBlockAdded(e,t){let n=this.core.getImageFont(e);if(!n)return;let i=n.getBlock(t);if(!i)return;let s=Ar(o=>{o&&typeof o.setImageFontBlock=="function"&&o.setImageFontBlock(t,i)},"applyBlock");for(let o of this.rendererManagers.values()){let a=o.getRenderer();a&&s(a)}}onCoreImageFontChanged(e){this.log(`Image font ${e} changed (legacy event), updating renderer`),this.onCoreImageFontAllocated(e);let t=this.core.getImageFont(e);if(!t)return;let n=t.getAtlasBlocks();for(let i=0;i<n;i++)t.getBlock(i)&&this.onCoreImageFontBlockAdded(e,i);for(let[i,s]of this.rendererManagers.entries()){let o=s.getRenderer();o&&this.onFontChanged(o,i)}}onFontChanged(e,t){}log(e){}getCore(){return this.core}getRendererManager(e=this.primaryDisplayId){let t=this.rendererManagers.get(e);if(!t)throw new Error(`Renderer manager for display ${e} not found`);return t}setDisplayContainers(e){this.displayConfigs=new Map(e.map(n=>[n.id,{container:n.container}]));let t=Array.from(this.displayConfigs.keys());this.primaryDisplayId=t.length>0?Math.min(...t):0;for(let n of this.rendererManagers.values())n.destroy();this.rendererManagers.clear(),this.createRendererManagers()}getUserId(){return this.userId}};Ar(_w,"BaseClientRuntime");var UE=_w,Gn=1e3,$w=class{constructor(e,t,n,i,s,o){se(this,"network"),se(this,"core"),se(this,"rendererManagers"),se(this,"primaryDisplayId"),se(this,"performanceMonitor"),se(this,"options"),se(this,"layerTraffic",new Map),se(this,"miscTraffic",new Map),se(this,"displayTraffic",new Map),se(this,"audioManager",null),se(this,"postProcessCallback",null),se(this,"soundHandlersSetup",!1),se(this,"userId",""),se(this,"lastReceivedTick",-1),se(this,"connected",!1),se(this,"totalBytesReceived",0),se(this,"lastSentViewports",new Map),se(this,"lastCollectedTouches",[]),se(this,"touchZonesCallback",null),se(this,"onUpdateReceived",null),se(this,"audioLoadingState",{totalExpected:0,loadedSounds:new Set,errors:new Map}),this.network=e,this.core=t,this.rendererManagers=n,this.primaryDisplayId=o,this.performanceMonitor=i,this.options={serverUrl:s.serverUrl,username:s.username,token:s.token??"",debug:s.debug??!1,autoReconnect:s.autoReconnect??!0,canvasWidth:s.canvasWidth,canvasHeight:s.canvasHeight}}getPrimaryRendererManager(){return this.rendererManagers.get(this.primaryDisplayId)??Array.from(this.rendererManagers.values())[0]}async connect(){this.log(`Connecting to ${this.options.serverUrl}`),await this.network.connect(),this.connected=!0,this.log("Connected to server"),this.setupNetworkHandlers()}async joinGame(e,t){return new Promise((n,i)=>{this.network.send("join",{username:this.options.username,token:this.options.token}),this.network.on("join_response",s=>{if(s.success){this.userId=s.userId,this.log(`Joined game as ${this.userId}`);let o=this.core.createUser(this.userId,this.options.username);o.setBytesTickRate(20),this.audioManager&&o.setAudioProcessor(this.audioManager),t!=null&&t.initUser&&t.initUser(e,this.core,o,{username:this.options.username,token:this.options.token}),n(this.userId)}else i(new Error(s.error||"Failed to join game"))}),setTimeout(()=>i(new Error("Join timeout")),5e3)})}sendInput(e){var C,x,I;let t=this.core.getUser(this.userId);if(!t)return;let n=this.getPrimaryRendererManager(),i=n==null?void 0:n.getCanvas();if(i){let E=t.getDisplays(),A=((C=E.find(V=>V.getId&&V.getId()===this.primaryDisplayId)??E[0])==null?void 0:C.getSize())??{x:this.options.canvasWidth,y:this.options.canvasHeight},R=A.x,F=A.y,z=(I=(x=n==null?void 0:n.getRenderer())==null?void 0:x.getOffsets)==null?void 0:I.call(x),P={offsetX:(z==null?void 0:z.offsetX)??0,offsetY:(z==null?void 0:z.offsetY)??0},O=Er.collectMousePosition(e,i,R,F,P);t.setMousePosition(O.x,O.y,O.over),t.updateMacroMouse(O.x,O.y,O.isLeftDown);let L=Er.collectTouchPositions(e,i,R,F,10,P);L.forEach(V=>{t.setTouchPosition(V.id,V.x,V.y,V.over)}),this.lastCollectedTouches=L}else this.lastCollectedTouches=[];let s=t.getInputBindingRegistry(),o=s.getAllAxes(),a=s.getAllButtons(),l=Er.collectAxisSources(o,e),u=Er.collectButtonSources(a,e),c=Er.collectTextInputs(e);c.length>0&&t.setTextInputs(c);let d=o.sort((E,A)=>E.bindingId-A.bindingId),h=new Map;for(let E of d){let A=s.evaluateAxis(E.bindingId,l);h.set(E.bindingId,A),t.setAxis(E.name,A)}let f=a.sort((E,A)=>E.bindingId-A.bindingId),p=new Map;for(let E of f){let A=s.evaluateButton(E.bindingId,u);p.set(E.bindingId,A),t.setButton(E.name,A)}let m=t.getMouseDisplayInfo(),S=t.getIsMouseOnADisplay(),w=this.collectChangedViewports(),g=this.lastCollectedTouches.map(E=>({id:E.id,x:E.x,y:E.y,over:E.over})),y=Hv(BigInt(this.core.currentTick),h,p,(m==null?void 0:m.displayId)??0,(m==null?void 0:m.localX)??0,(m==null?void 0:m.localY)??0,S,c,[],w,g,document.hidden);this.network.send("input",y)}collectChangedViewports(){let e=[];for(let[t,n]of this.rendererManagers.entries()){let{width:i,height:s}=n.getAvailableSize();if(i===0||s===0)continue;let o=this.lastSentViewports.get(t);(!o||o.pixelWidth!==i||o.pixelHeight!==s)&&(e.push({displayId:t,pixelWidth:i,pixelHeight:s}),this.lastSentViewports.set(t,{pixelWidth:i,pixelHeight:s}),this.log(`Viewport changed: display ${t} = ${i}x${s}px`))}return e}disconnect(){this.connected&&(this.network.send("leave",{}),this.network.disconnect(),this.connected=!1,this.soundHandlersSetup=!1,this.log("Disconnected from server"))}getUserId(){return this.userId}isConnected(){return this.connected}getTotalBytesReceived(){return this.totalBytesReceived}getPing(){return this.network.getPing()}getAudioLoadingState(){let e=this.audioLoadingState.loadedSounds.size,t=this.audioLoadingState.totalExpected,n=this.audioLoadingState.errors.size,i=t>0&&e>=t,s=Array.from(this.audioLoadingState.errors.keys());return{loadedCount:e,totalExpected:t,errorCount:n,isComplete:i,errors:s}}destroy(){this.disconnect(),this.network.destroy(),this.log("NetworkSync destroyed")}setupNetworkHandlers(){this.network.on("update",e=>{var t;try{let n=this.convertToUint8Array(e,"update");if(!n)return;this.recordBytesReceived(n.length);let i=this.core.applyUpdatePacketBuffer(this.userId,n);i?(this.postProcessCallback&&i.postProcessOrders&&i.postProcessOrders.length>0&&this.postProcessCallback(i.postProcessOrders),(t=this.onUpdateReceived)==null||t.call(this)):this.log("Failed to apply update packet")}catch(n){this.log(`Error applying update packet: ${n}`)}}),this.network.on("update-static",e=>{this.handleUpdatePacket(e,"update-static")}),this.network.on("update-dynamic",e=>{this.handleUpdatePacket(e,"update-dynamic")}),this.network.on("load",e=>{try{let t=this.convertToUint8Array(e,"load");if(!t)return;this.recordBytesReceived(t.length),this.core.applyLoadPacket(t)?this.log("Load packet applied successfully"):this.log("Failed to apply load packet")}catch(t){this.log(`Error applying load packet: ${t}`)}}),this.network.on("input-bindings",e=>{var t;if(this.recordBytesReceived(e.length),this.core.applyInputBindingsLoadPacket(this.userId,e)){this.log("Input bindings configured");try{let n=JSON.parse(e);if(this.log(`Touch zones in packet: ${((t=n.touchZones)==null?void 0:t.length)??0}, callback defined: ${!!this.touchZonesCallback}`),n.touchZones&&n.touchZones.length>0&&this.touchZonesCallback){let i=n.touchZones.map(s=>({id:s.zoneId,x:s.x,y:s.y,width:s.width,height:s.height}));this.touchZonesCallback(i),this.log(`Touch zones configured: ${i.length} zones`)}}catch{}}else this.log("Failed to apply input bindings")}),this.audioManager&&this.setupSoundHandlers(),this.network.on("disconnect",()=>{this.connected=!1,this.soundHandlersSetup=!1,this.log("Disconnected from server")})}handleUpdatePacket(e,t){var n;try{let i=this.convertToUint8Array(e,t);if(!i)return;this.recordBytesReceived(i.length);let s=new DataView(i.buffer,i.byteOffset,i.byteLength),o=Number(s.getBigUint64(0,!1));if(t==="update-dynamic"&&o<this.lastReceivedTick)return;o>this.lastReceivedTick&&(this.lastReceivedTick=o);let a=this.core.applyUpdatePacketBuffer(this.userId,i);if(a){let l=performance.now(),u=Ar((g,y)=>{if(y<=0)return;let C=this.miscTraffic.get(g)??{total:0,windowSum:0,samples:[]};C.total+=y,C.windowSum+=y,C.samples.push({time:l,bytes:y}),this.miscTraffic.set(g,C)},"recordMisc"),c=Ar(g=>{try{return JSON.stringify(g).length}catch{return 0}},"safeLen"),d=a.__byteSizes,h=d==null?void 0:d.audioOrders;typeof h=="number"?u("update.audioOrders",h):a.audioOrders&&a.audioOrders.length&&u("update.audioOrders",c(a.audioOrders));let f=d==null?void 0:d.vibrationOrders;typeof f=="number"?u("update.vibrationOrders",f):a.vibrationOrders&&a.vibrationOrders.length&&u("update.vibrationOrders",c(a.vibrationOrders));let p=d==null?void 0:d.macroOrders;typeof p=="number"?u("update.macroOrders",p):a.macroOrders&&a.macroOrders.length&&u("update.macroOrders",c(a.macroOrders));let m=d==null?void 0:d.postProcessOrders;if(typeof m=="number"?u("update.postProcessOrders",m):a.postProcessOrders&&a.postProcessOrders.length&&u("update.postProcessOrders",c(a.postProcessOrders)),a.displays&&a.displays.length)for(let g of a.displays){let y=g.id;if(typeof y!="number")continue;let C=this.displayTraffic.get(y)??{total:0,windowSum:0,samples:[]},x=7;C.total+=x,C.windowSum+=x,C.samples.push({time:l,bytes:x}),this.displayTraffic.set(y,C)}for(let g of a.layers){let y=g.byteSize??0,C=this.layerTraffic.get(g.id)??{total:0,windowSum:0,samples:[]};C.total+=y,C.windowSum+=y,C.samples.push({time:l,bytes:y});let x=l-Gn;for(;C.samples.length&&C.samples[0].time<x;){let I=C.samples.shift();I&&(C.windowSum-=I.bytes)}this.layerTraffic.set(g.id,C)}{let g=l-Gn;this.miscTraffic.forEach((y,C)=>{for(;y.samples.length&&y.samples[0].time<g;){let x=y.samples.shift();x&&(y.windowSum-=x.bytes)}y.windowSum<0&&(y.windowSum=0),this.miscTraffic.set(C,y)})}{let g=l-Gn;this.displayTraffic.forEach((y,C)=>{for(;y.samples.length&&y.samples[0].time<g;){let x=y.samples.shift();x&&(y.windowSum-=x.bytes)}y.windowSum<0&&(y.windowSum=0),this.displayTraffic.set(C,y)})}this.postProcessCallback&&a.postProcessOrders&&a.postProcessOrders.length>0&&this.postProcessCallback(a.postProcessOrders),this.options.debug&&this.debugRenderState();let S=performance.now();(n=this.onUpdateReceived)==null||n.call(this);let w=performance.now()-S;this.performanceMonitor.recordFrameTiming(0,w),this.options.debug&&this.log(`render() completed for ${t} (${w.toFixed(2)}ms)`)}else this.options.debug&&this.log(`Failed to apply ${t} packet (tick ${o})`)}catch(i){this.log(`Error applying ${t} update packet: ${i}`),console.error(i)}}convertToUint8Array(e,t){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):e.data&&Array.isArray(e.data)?new Uint8Array(e.data):typeof e=="object"&&e.type==="Buffer"?new Uint8Array(e.data):(this.log(`Unknown data type for ${t} packet: ${typeof e}`),null)}debugRenderState(){var n;let e=this.core.getUser(this.userId);if(e){let i=e.getLayers();this.log(`User has ${i.length} layers`),i.forEach((s,o)=>{let a=s.getOrders(),l=s.getMustBeReliable();(a.length>0||l)&&this.log(` Layer ${o}: ${a.length} orders, reliable=${l}, z=${s.getZOrder()}`)})}let t=((n=this.getPrimaryRendererManager())==null?void 0:n.isReady())??!1;this.log(`Renderer ready: ${t}`)}log(e){}recordBytesReceived(e){this.totalBytesReceived+=e;let t=this.core.getUser(this.userId);t&&t.recordBytesReceived(e)}getLayerTrafficStats(){let e={},t=performance.now()-Gn;return this.layerTraffic.forEach((n,i)=>{for(;n.samples.length&&n.samples[0].time<t;){let s=n.samples.shift();s&&(n.windowSum-=s.bytes)}n.windowSum<0&&(n.windowSum=0),e[i]={total:n.total,bytesPerSec1s:n.windowSum/(Gn/1e3)}}),e}getMiscTrafficStats(){let e={},t=performance.now()-Gn;return this.miscTraffic.forEach((n,i)=>{for(;n.samples.length&&n.samples[0].time<t;){let s=n.samples.shift();s&&(n.windowSum-=s.bytes)}n.windowSum<0&&(n.windowSum=0),e[i]={total:n.total,bytesPerSec1s:n.windowSum/(Gn/1e3)}}),e}getDisplayTrafficStats(){let e={},t=performance.now()-Gn;return this.displayTraffic.forEach((n,i)=>{for(;n.samples.length&&n.samples[0].time<t;){let s=n.samples.shift();s&&(n.windowSum-=s.bytes)}n.windowSum<0&&(n.windowSum=0),e[i]={total:n.total,bytesPerSec1s:n.windowSum/(Gn/1e3)}}),e}getSoundPacketSize(e){return e.mode==="file"?e.sounds.reduce((t,n)=>t+this.getSoundDataLength(n.data)+n.name.length+10,0):e.sounds.reduce((t,n)=>t+n.url.length+n.name.length+10,0)}getSoundDataLength(e){if(e instanceof Uint8Array)return e.length;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;let t=globalThis.Buffer;return t&&e instanceof t?e.length:e&&typeof e=="object"&&Array.isArray(e.data)?e.data.length:Array.isArray(e)?e.length:0}setAudioManager(e){if(this.audioManager=e,e&&this.userId){let t=this.core.getUser(this.userId);t&&t.setAudioProcessor(e)}this.connected&&e&&this.setupSoundHandlers()}setPostProcessCallback(e){this.postProcessCallback=e}setTouchZonesCallback(e){this.touchZonesCallback=e}setupSoundHandlers(){if(this.audioManager){if(this.soundHandlersSetup){this.log("Sound handlers already registered, skipping");return}this.soundHandlersSetup=!0,this.network.on("sound-load",async e=>{this.recordBytesReceived(this.getSoundPacketSize(e)),e.totalSounds!==void 0&&e.totalSounds>this.audioLoadingState.totalExpected&&(this.audioLoadingState.totalExpected=e.totalSounds,this.log(`Audio loading: expecting ${e.totalSounds} total sounds`)),e.mode==="file"?await this.handleSoundLoad(e):e.mode==="external"&&await this.handleSoundExternalLoad(e)}),this.log("Sound handlers registered")}}async handleSoundLoad(e){if(!this.audioManager){this.log("Cannot load sounds: AudioManager not initialized");return}let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load sounds: SoundBank not initialized");return}for(let n of e.sounds)try{let i=this.normalizeSoundData(n.data);await t.loadFromData(n.soundId,n.name,i),this.log(`Loaded sound: ${n.name} (${i.length} bytes)`),this.audioLoadingState.loadedSounds.add(n.name),this.audioLoadingState.errors.delete(n.name),this.sendAudioAck({type:"sound-loaded",soundId:n.soundId,name:n.name})}catch(i){console.error(`[NetworkSync] Failed to load sound "${n.name}":`,i),this.audioLoadingState.errors.set(n.name,String(i)),this.sendAudioAck({type:"sound-error",soundId:n.soundId,name:n.name,error:String(i)})}}normalizeSoundData(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));let t=globalThis.Buffer;if(t&&e instanceof t)return new Uint8Array(e);if(e&&typeof e=="object"&&Array.isArray(e.data))return new Uint8Array(e.data);if(Array.isArray(e))return new Uint8Array(e);if(typeof e=="string")try{let n=atob(e),i=n.length,s=new Uint8Array(i);for(let o=0;o<i;o++)s[o]=n.charCodeAt(o);return s}catch{}throw new Error("Invalid sound data payload")}async handleSoundExternalLoad(e){if(!this.audioManager){this.log("Cannot load external sounds: AudioManager not initialized");return}let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load external sounds: SoundBank not initialized");return}for(let n of e.sounds)try{await t.loadFromUrl(n.soundId,n.name,n.url),this.log(`Loaded external sound: ${n.name} from ${n.url}`),this.audioLoadingState.loadedSounds.add(n.name),this.audioLoadingState.errors.delete(n.name),this.sendAudioAck({type:"sound-loaded",soundId:n.soundId,name:n.name})}catch(i){console.error(`[NetworkSync] Failed to load external sound "${n.name}":`,i),this.audioLoadingState.errors.set(n.name,String(i)),this.sendAudioAck({type:"sound-error",soundId:n.soundId,name:n.name,error:String(i)})}}sendAudioAck(e){this.network.send("audio-ack",e),this.log(`Sent audio-ack: ${e.type}`)}sendBridge(e,t){var n,i;(i=(n=this.network).sendBridge)==null||i.call(n,e,t),this.log(`Bridge sent on channel '${e}'`)}onBridge(e,t){var n,i;(i=(n=this.network).onBridge)==null||i.call(n,e,t),this.log(`Bridge handler registered for channel '${e}'`)}offBridge(e,t){var n,i;(i=(n=this.network).offBridge)==null||i.call(n,e,t),this.log(`Bridge handler removed for channel '${e}'`)}removeAllBridgeHandlers(e){var t,n;(n=(t=this.network).removeAllBridgeHandlers)==null||n.call(t,e),this.log(e?`All bridge handlers removed for '${e}'`:"All bridge handlers removed")}};Ar($w,"NetworkSync");var AE=$w,Nw=class extends UE{constructor(e){let t=e.mode;if(t!=="standalone"&&t!=="socketio"&&t!=="webrtc")throw new Error(`Invalid ClientRuntime mode: "${t}". Expected 'standalone', 'socketio', or 'webrtc'.`);let n;if(e.mode==="standalone"&&(n=e.standalone.application),!n&&e.mode==="standalone")throw new Error("Application instance required for standalone mode");super({application:n,container:e.container,displayContainers:e.displayContainers,debug:e.debug,renderer:e.renderer,useImageDataRendering:e.useImageDataRendering,renderMode:e.renderMode}),se(this,"input",null),se(this,"networkSync",null),se(this,"mode"),se(this,"localOptions",null),se(this,"autoplayOverlay",null),se(this,"autoplay",!0),se(this,"audioManager",null),se(this,"mobileVibration",null),se(this,"postProcessOverlay",null),se(this,"postProcessOverlays",new Map),se(this,"postProcessOrderCollector",new Mf),se(this,"pendingPaletteSlotByDisplay",new Map),se(this,"localBridgeHandlers",new Map),se(this,"localBridgeWildcardHandlers",new Set),se(this,"visibilityHandler",null),this.mode=e.mode,this.autoplay=e.autoplay??!0,e.mode==="standalone"?(this.localOptions=e,this.userId=e.standalone.userId??"local"):this.localOptions=null,this.mode==="standalone"?(this.log("Initializing in STANDALONE mode"),this.initLocalMode()):(this.log(`Initializing in ${this.mode.toUpperCase()} mode`),this.initConnectedMode(e))}initLocalMode(){let e=this.localOptions;e&&(this.log("Initializing ClientRuntime (standalone mode)"),e.inputEnabled??!0?this.initInput(e):this.log("Input disabled (inputEnabled: false)"))}initConnectedMode(e){this.log(`Initializing ClientRuntime (${this.mode} mode)`),this.core=new Nv({mode:"client",maxUsers:100}),this.core.onPaletteChanged(i=>{this.onCorePaletteChanged(i),this.retryPendingPaletteSelections()}),this.visibilityHandler=()=>{this.networkSync&&this.input&&this.networkSync.sendInput(this.input)},document.addEventListener("visibilitychange",this.visibilityHandler),this.core.onImageFontChanged(i=>{this.onCoreImageFontChanged(i)});let t;if(e.mode==="webrtc"){let i=e.webrtc;t=new SE({url:i.signalUrl??"",sessionId:i.sessionId,signalingPath:i.signalingPath,iceServers:i.iceServers,autoReconnect:i.autoReconnect,auth:i.auth??{username:i.username},debug:e.debug})}else{let i=e.socketio;if(!i)throw new Error(`SocketIO configuration missing. Mode is '${e.mode}' but 'socketio' options are undefined.`);t=new bE({url:i.url??"",path:i.path,autoReconnect:i.autoReconnect,auth:i.auth??{username:i.username},debug:e.debug})}let n=e.mode==="socketio"?e.socketio:e.webrtc;this.networkSync=new AE(t,this.core,this.rendererManagers,this.performanceMonitor,{serverUrl:e.mode==="socketio"?e.socketio.url:e.webrtc.signalUrl||"WebRTC",username:n.username??"User",debug:e.debug,autoReconnect:n.autoReconnect,canvasWidth:80,canvasHeight:25},this.primaryDisplayId),this.networkSync&&(this.networkSync.onUpdateReceived=()=>{this.renderRequested=!0}),(e.inputEnabled??!0)&&(this.input||this.initInput(e))}initInput(e){var t,n,i,s,o,a,l,u,c,d;this.input=new hw({enableKeyboardMouse:!0,enableGamepad:!0,enableMobile:!0,targetElement:window,mobileTargetElement:((t=e.touchZones)==null?void 0:t.targetElement)??void 0,debug:e.debug,keyboardConfig:{preventDefault:e.captureInput??!1,stopPropagation:e.captureInput??!1},mouseConfig:{preventDefault:e.captureInput??!1,stopPropagation:e.captureInput??!1},mobileConfig:{preventDefault:((n=e.mobileInputConfig)==null?void 0:n.preventDefault)??!1,passive:((i=e.mobileInputConfig)==null?void 0:i.passive)??!0,maxTouches:((s=e.mobileInputConfig)==null?void 0:s.maxTouches)??10},enableTouchZones:((o=e.touchZones)==null?void 0:o.enable)??!1,touchZoneConfig:{targetElement:(a=e.touchZones)==null?void 0:a.targetElement,gridWidth:((l=e.touchZones)==null?void 0:l.gridWidth)??0,gridHeight:((u=e.touchZones)==null?void 0:u.gridHeight)??0,rendererOffsets:(c=e.touchZones)==null?void 0:c.rendererOffsets,zones:(d=e.touchZones)==null?void 0:d.zones}})}rebuildPostProcessOverlays(){for(let e of this.postProcessOverlays.values())e.destroy();this.postProcessOverlays.clear(),this.postProcessOverlay=null;for(let[e,t]of this.displayConfigs.entries()){let n=new Jv(t.container);this.postProcessOverlays.set(e,n),e===this.primaryDisplayId&&(this.postProcessOverlay=n)}!this.postProcessOverlay&&this.postProcessOverlays.size>0&&(this.postProcessOverlay=Array.from(this.postProcessOverlays.values())[0]??null)}getMode(){return this.mode}setTickRate(e){if(this.mode!=="standalone"){this.log("setTickRate() has no effect in connected mode");return}super.setTickRate(e)}async onBeforeStart(){this.audioManager=new zw({debug:this.options.debug}),this.mobileVibration=new Uf({debug:this.options.debug}),this.autoplay?(this.log("Autoplay enabled, initializing AudioManager..."),this.audioManager.initialize()):(this.log("Autoplay disabled, showing overlay..."),await new Promise(e=>{var t;this.autoplayOverlay=new ck(this.options.container,{...(t=this.localOptions)==null?void 0:t.autoplayOptions,onStart:()=>{this.log("User clicked start button"),this.audioManager&&(this.audioManager.initialize(),this.audioManager.playStartSound()),this.mobileVibration&&this.mobileVibration.vibrate(50),this.autoplayOverlay&&(this.autoplayOverlay.destroy(),this.autoplayOverlay=null),e()}})}),this.log("Autoplay overlay dismissed, continuing startup..."))}async start(){if(this.running){this.log("Already running");return}this.log("Starting ClientRuntime"),await this.onBeforeStart();for(let[n,i]of this.rendererManagers.entries())await i.initialize(this.core),this.log(`Renderer for display ${n} is ready`);this.rebuildPostProcessOverlays(),this.log("PostProcessOverlays created"),this.onCorePaletteChanged(this.core.getPalette()),this.log("Initial palette sent to renderer"),this.options.application&&(this.log("Calling application.init()"),await this.options.application.init(this,this.core));let e=this.rendererManager.getCanvas();if(e&&this.input&&this.input.setMobileTarget(e),this.mode!=="standalone"&&this.networkSync){if(this.audioManager&&this.networkSync.setAudioManager(this.audioManager),this.networkSync.setPostProcessCallback(i=>{this.applyPostProcessOrders(i)}),this.input){let i=this.input,s=this.rendererManager;this.networkSync.setTouchZonesCallback(o=>{this.log(`[start] Touch zones callback called with ${o.length} zones`);let a=s.getCanvas();if(this.log(`[start] Canvas available: ${!!a}`),a){let l=o.reduce((d,h)=>Math.max(d,h.x+h.width),0),u=o.reduce((d,h)=>Math.max(d,h.y+h.height),0);this.log(`[start] Grid from zones: ${l}x${u}`);let c=i.enableTouchZonesDevice(a,l,u,o);this.log(`[start] enableTouchZonesDevice returned: ${c}`),c&&this.log(`Touch zones configured from server: ${o.length} zones`)}})}await this.networkSync.connect(),this.userId=await this.networkSync.joinGame(this,this.options.application);let n=this.core.getUser(this.userId);n&&this.configureUserProcessors(n)}else await this.createLocalUser();let t=this.core.getUser(this.userId);if(t){let n=t.getDisplays();if(n.length>0){let i=n[0].getSize(),s=i.x,o=i.y,a=this.rendererManager.getRenderer(),l,u;if(this.rendererType==="webgl"){let c=a.getGridSize();l=c.cols,u=c.rows}else{let c=a;l=c.getCols(),u=c.getRows()}(l!==s||u!==o)&&(this.log(`Adjusting renderer from ${l}×${u} to match display ${s}×${o}`),a.resize(s,o))}}this.input&&this.input.start(),this.running=!0,this.startTime=performance.now(),this.lastTimestamp=this.startTime,this.lastRenderTimestamp=this.startTime,this.accumulatedTime=0,this.firstTickDone=!1,this.performanceMonitor.reset(),this.performanceMonitor.startTracking(this.startTime),this.log("Starting main loop"),this.mainLoop(this.lastTimestamp)}async onStop(){this.audioManager&&this.audioManager.stopAll(),this.input&&this.input.stop(),this.mode!=="standalone"&&this.networkSync&&this.networkSync.disconnect()}getStats(){var s;let e=super.getStats(),t=this.core.getUser(this.userId),n=t==null?void 0:t.getTotalBytesReceived(),i=t==null?void 0:t.getBytesReceivedPerSecond();return{...e,mode:this.mode,latency:((s=this.networkSync)==null?void 0:s.getPing())??0,totalBytesReceived:n,bytesReceivedPerSec:i}}getAudioLoadingState(){if(this.mode!=="standalone"&&this.networkSync)return this.networkSync.getAudioLoadingState();if(this.audioManager){let e=this.audioManager.getSoundBank();if(e){let t=e.getStats();return{loadedCount:t.totalSounds,totalExpected:t.totalSounds,errorCount:0,isComplete:!0,errors:[]}}}return{loadedCount:0,totalExpected:0,errorCount:0,isComplete:!0,errors:[]}}configureUserProcessors(e){if(this.audioManager&&e.setAudioProcessor(this.audioManager),this.mobileVibration&&e.setMobileVibrationProcessor(this.mobileVibration),this.input){let t=this.input.getGamepad();t&&e.setGamepadVibrationProcessor(t)}}async createLocalUser(){var o;let e=this.localOptions;this.userId=(e==null?void 0:e.standalone.userId)??"local",this.log(`Creating local user: ${this.userId}`);let t=this.core.createUser(this.userId,(e==null?void 0:e.standalone.username)??"User");if(t.setBytesTickRate(this.tickRate>0?this.tickRate:20),this.configureUserProcessors(t),(o=this.options.application)!=null&&o.initUser&&(this.log("Calling application.initUser()"),this.options.application.initUser(this,this.core,t,{username:(e==null?void 0:e.standalone.username)??"User"})),t.hasAudioConfigCommands()&&(this.log("Applying audio config commands from initUser()"),t.applyAudioConfigCommands(t.flushAudioConfigCommands())),t.hasPendingMacroOrders()){this.log("Applying macro orders from initUser()");let a=t.flushMacroOrders();t.applyMacroOrders(a)}if(t.hasPostProcessCommands()){this.log("Applying post-process commands from initUser()");let a=t.flushPostProcessCommands(),l=this.postProcessOrderCollector.convertCommands(a);this.applyPostProcessOrders(l)}t.needsSendSounds()&&(await this.loadSoundsFromRegistry(),t.clearSendSounds());let n=this.core.generateAllLoadPackets();n.forEach(a=>{t.recordBytesReceived(a.length)});let i=this.core.generateMacroLoadPackets(this.userId);i.forEach(a=>{t.recordBytesReceived(a.length)});let s=t.getInputBindingsLoadPacket();if(s&&(t.recordBytesReceived(s.length),this.input)){let a=t.getInputBindingRegistry().getAllTouchZones();if(a.length>0){let l=this.rendererManager.getCanvas();if(l){let u=t.getDisplays(),c=u.length>0?u[0].getSize():{x:80,y:25},d=a.map(h=>({id:h.zoneId,x:h.x,y:h.y,width:h.width,height:h.height}));this.input.enableTouchZonesDevice(l,c.x,c.y,d)?this.log(`Touch zones synchronized from registry: ${a.length} zones`):this.log("Failed to enable touch zones - mobile input may not be initialized")}}}this.log(`Simulated ${n.length} load packets, ${i.length} macro packets for byte counting`),this.log("Performing initial render"),this.core.endTick().forEach(({static:a,dynamic:l},u)=>{let c=this.core.getUser(u);c&&(a&&c.recordBytesReceived(a.length),l&&c.recordBytesReceived(l.length))}),this.render(),this.log("Initial render complete")}async loadSoundsFromRegistry(){if(!this.audioManager){this.log("Cannot load sounds: AudioManager not initialized");return}let e=this.audioManager.getSoundBank();if(!e){this.log("Cannot load sounds: SoundBank not initialized");return}let t=this.core.getSoundRegistry().getAll();if(t.length===0){this.log("No sounds to load from registry");return}this.log(`Loading ${t.length} sounds from Core registry into AudioManager...`);let n=this.core.getUser(this.userId),i=0;for(let s of t)try{if(s.loadType==="file"&&s.data){await e.loadFromData(s.soundId,s.name,s.data);let o=s.data.length+s.name.length+10;i+=o,this.log(`🔊 Loaded sound: ${s.name} (${s.data.length} bytes)`)}else if(s.loadType==="external"&&s.url){await e.loadFromUrl(s.soundId,s.name,s.url);let o=s.url.length+s.name.length+10;i+=o,this.log(`🔊 Loaded external sound: ${s.name} from ${s.url}`)}}catch(o){console.error(`[ClientRuntime] Failed to load sound "${s.name}":`,o)}n&&i>0&&(n.recordBytesReceived(i),this.log(`Simulated ${i} bytes for ${t.length} sound(s)`)),this.log(`✓ ${e.size} sounds loaded into AudioManager`)}mainLoop(e){var o,a,l,u;if(!this.running){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0);return}if(this.renderMode==="on-demand"){this.renderRequested&&(this.renderRequested=!1,this.performanceMonitor.updateFPS(e),this.render()),this.rafId=requestAnimationFrame(c=>this.mainLoop(c));return}let t=e-this.lastRenderTimestamp;if(this.lastRenderTimestamp>0&&t<this.FRAME_TIME_MIN-1){this.rafId=requestAnimationFrame(c=>this.mainLoop(c));return}this.lastRenderTimestamp=e;let n=(e-this.lastTimestamp)/1e3,i=Math.min(n,.1);this.lastTimestamp=e,this.performanceMonitor.updateFPS(e);let s=this.core.getUser(this.userId);if(!s){this.rafId=requestAnimationFrame(c=>this.mainLoop(c));return}if(this.mode==="standalone"){if(this.tickRate===0){let f=performance.now();this.render();let p=performance.now()-f;this.performanceMonitor.recordFrameTiming(0,p),this.rafId=requestAnimationFrame(m=>this.mainLoop(m));return}if(!this.firstTickDone){this.firstTickDone=!0,this.lastTimestamp=e,this.accumulatedTime=0,this.rafId=requestAnimationFrame(f=>this.mainLoop(f));return}this.accumulatedTime+=i;let c=1/this.tickRate;this.accumulatedTime>.5&&(this.accumulatedTime=c);let d=0,h=0;for(;this.accumulatedTime>=c&&d<5;){let f=performance.now();if(this.collectAndApplyInput(s),this.options.application&&((a=(o=this.options.application).update)==null||a.call(o,this,this.core,c),(u=(l=this.options.application).updateUser)==null||u.call(l,this,this.core,s,c)),s.clearTextInputs(),s.hasAudioConfigCommands()&&s.applyAudioConfigCommands(s.flushAudioConfigCommands()),s.hasSoundCommands()&&s.applyAudioCommands(s.flushSoundCommands()),s.hasMobileVibrationCommands()&&s.applyMobileVibrationCommands(s.flushMobileVibrationCommands()),s.hasGamepadVibrationCommands()&&s.applyGamepadVibrationCommands(s.flushGamepadVibrationCommands()),s.hasPostProcessCommands()){let m=s.flushPostProcessCommands(),S=this.postProcessOrderCollector.convertCommands(m);this.applyPostProcessOrders(S)}if(s.hasPendingMacroOrders()){let m=s.flushMacroOrders();s.applyMacroOrders(m)}let p=s.updateMacros();if(s.processMacroEvents(p),s.hasBridgeMessages()){let m=s.getBridgeMessages();this.dispatchLocalBridgeMessages(m)}this.core.endTick().forEach(({static:m,dynamic:S})=>{let w=((m==null?void 0:m.length)??0)+((S==null?void 0:S.length)??0);s.recordBytesReceived(w)}),h+=performance.now()-f,this.accumulatedTime-=c,d++}if(d>0){let f=performance.now();this.render();let p=performance.now()-f;this.performanceMonitor.recordFrameTiming(h,p)}}else{let c=s.updateMacros();s.processMacroEvents(c),this.collectAndSendInput(),this.accumulatedTime+=i;let d=1/(this.tickRate>0?this.tickRate:20);for(this.accumulatedTime>.5&&(this.accumulatedTime=d);this.accumulatedTime>=d;)s.endTickBytes(),this.accumulatedTime-=d;(this.renderRequested||this.renderMode==="continuous")&&(this.renderRequested=!1,this.render())}this.rafId=requestAnimationFrame(c=>this.mainLoop(c))}collectAndApplyInput(e){var a,l,u,c,d,h;if(!this.input)return;let t=this.rendererManager.getCanvas();if(t){let f=e.getDisplays(),p=((a=f.find(x=>x.getId&&x.getId()===this.primaryDisplayId)??f[0])==null?void 0:a.getSize())??{x:80,y:25},m=p.x,S=p.y,w=(u=(l=this.rendererManager.getRenderer())==null?void 0:l.getOffsets)==null?void 0:u.call(l),g={offsetX:(w==null?void 0:w.offsetX)??0,offsetY:(w==null?void 0:w.offsetY)??0};this.input.updateTouchZoneLayout(m,S,g);let y=Er.collectMousePosition(this.input,t,m,S,g);e.setMousePosition(y.x,y.y,y.over),e.updateMacroMouse(y.x,y.y,y.isLeftDown),Er.collectTouchPositions(this.input,t,m,S,10,g).forEach(x=>{e.setTouchPosition(x.id,x.x,x.y,x.over)});let C=(c=this.rendererManagers.get(this.primaryDisplayId))==null?void 0:c.getAvailableSize();C&&e.setDisplayViewport(this.primaryDisplayId,C.width,C.height)}let n=Er.collectTextInputs(this.input);n.length>0&&e.setTextInputs(n);let i=e.getInputBindingRegistry(),s=i.getAllAxes(),o=i.getAllButtons();if(s.length>0||o.length>0){let f=Er.collectAxisSources(s,this.input),p=Er.collectButtonSourcesWithTransitions(o,this.input);s.forEach(m=>{let S=i.evaluateAxis(m.bindingId,f);e.setAxis(m.name,S)}),o.forEach(m=>{let S=new Map,w=new Map,g=new Map;for(let[I,E]of p)S.set(I,E.pressed),w.set(I,E.justPressed),g.set(I,E.justReleased);let y=i.evaluateButton(m.bindingId,S),C=i.evaluateButton(m.bindingId,w),x=i.evaluateButton(m.bindingId,g);e.setButton(m.name,y),e.setButton(`${m.name}_justPressed`,C),e.setButton(`${m.name}_justReleased`,x)})}(h=(d=this.input).poll)==null||h.call(d)}collectAndSendInput(){!this.networkSync||!this.input||this.networkSync.sendInput(this.input)}render(){let e=this.core.getUser(this.userId);if(e){let t=e.getDisplays();for(let n of t){let i=n.getId(),s=this.rendererManagers.get(i);if(!s){console.warn(`[ClientRuntime] No renderer for display ${i}, skipping resize`);continue}let o=s.getRenderer();if(!o)continue;let a=n.getSize(),l,u,c,d,h=null;if("getGridSize"in o){let p=o,m=p.getGridSize();l=m.cols,u=m.rows,c=p.getCellWidth(),d=p.getCellHeight(),h=p.getScalingMode()}else if("getCols"in o){let p=o;l=p.getCols(),u=p.getRows(),c=p.getCellWidth(),d=p.getCellHeight(),h=p.getScalingMode()}else continue;if(h===Vt.Responsive){let p=s.getAvailableSize(),m=256*256;"getMaxCells"in o&&(m=Math.min(m,o.getMaxCells()));let S=Math.floor(p.width/c),w=Math.floor(p.height/d);if(S=Math.min(256,Math.max(1,S)),w=Math.min(256,Math.max(1,w)),S*w>m){let g=Math.sqrt(m/(S*w));S=Math.max(1,Math.floor(S*g)),w=Math.max(1,Math.floor(w*g)),this.log(`⚠️ [Display ${i}] Device limit: max ${m} cells, clamping to ${S}×${w}`)}(a.x!==S||a.y!==w)&&(this.log(`📐 [Display ${i}] Resizing display from ${a.x}×${a.y} to ${S}×${w} (available: ${p.width}×${p.height}px, cell: ${c}×${d}px)`),n.setSize(new Yt(S,w)))}let f=n.getSize();(l!==f.x||u!==f.y)&&(this.log(`📐 [Display ${i}] Resizing renderer from ${l}×${u} to ${f.x}×${f.y}`),o.resize(f.x,f.y))}}super.render()}onFontChanged(e,t){let n=t??this.primaryDisplayId,i=this.postProcessOverlays.get(n)??this.postProcessOverlay;i&&"syncWithRenderer"in i&&"getCellWidth"in e&&"getCellHeight"in e&&"getCurrentScale"in e&&"getGridSize"in e&&(i.syncWithRenderer(e),this.log(`✓ PostProcessOverlay synced with renderer dimensions (display ${n})`))}getAudioManager(){return this.audioManager}getLayerTrafficStats(){var e;return((e=this.networkSync)==null?void 0:e.getLayerTrafficStats())??{}}getMiscTrafficStats(){var e,t;return((t=(e=this.networkSync)==null?void 0:e.getMiscTrafficStats)==null?void 0:t.call(e))??{}}getDisplayTrafficStats(){var e,t;return((t=(e=this.networkSync)==null?void 0:e.getDisplayTrafficStats)==null?void 0:t.call(e))??{}}getAudioContext(){var e;return((e=this.audioManager)==null?void 0:e.getContext())??null}getPostProcessOverlay(){return this.postProcessOverlay}applyAmbientEffectConfig(e,t){var i;let n=(i=this.rendererManagers.get(e))==null?void 0:i.getRenderer();n&&"setAmbientEffect"in n&&(t.enabled?n.setAmbientEffect({blur:t.blur,scale:t.scale}):n.setAmbientEffect(!1),this.log(`[Display ${e}] Ambient effect ${t.enabled?"enabled":"disabled"}`))}applyPostProcessOrders(e){var t;for(let n of e){let i=n.displayId??this.primaryDisplayId,s=this.postProcessOverlays.get(i)??this.postProcessOverlay,o=(t=this.rendererManagers.get(i))==null?void 0:t.getRenderer();switch(n.type){case Xr.SetConfig:{if(!s){console.warn(`[ClientRuntime] No PostProcessOverlay for display ${i}`);break}let a={};n.scanlines&&(a.scanlines={enabled:n.scanlines.enabled,opacity:n.scanlines.opacity,pattern:this.patternFromType(n.scanlines.pattern),color:{r:n.scanlines.colorR,g:n.scanlines.colorG,b:n.scanlines.colorB}}),n.ambientEffect&&(a.ambientEffect={enabled:n.ambientEffect.enabled,blur:n.ambientEffect.blur,scale:n.ambientEffect.scale}),s.setConfig(Object.keys(a).length>0?a:null),a.ambientEffect&&o&&this.applyAmbientEffectConfig(i,a.ambientEffect),this.log(`[Display ${i}] SetConfig applied`);break}case Xr.SetScanlines:{if(!s){console.warn(`[ClientRuntime] No PostProcessOverlay for display ${i}`);break}s.setScanlines({enabled:n.enabled,opacity:n.opacity,pattern:this.patternFromType(n.pattern),color:{r:n.colorR,g:n.colorG,b:n.colorB}}),this.log(`[Display ${i}] Scanlines ${n.enabled?"enabled":"disabled"}`);break}case Xr.SetAmbientEffect:{this.applyAmbientEffectConfig(i,{enabled:n.enabled,blur:n.blur,scale:n.scale}),this.log(`[Display ${i}] Ambient effect ${n.enabled?"enabled":"disabled"}`);break}case Xr.SetScalingMode:{this.applyScalingMode(i,n.mode);break}case Xr.SetGrid:{this.applyGridConfig(i,n);break}case Xr.SwitchPalette:{this.applySwitchPalette(i,n);break}case Xr.SetCellSize:{this.applyCellSize(i,n.cellWidth,n.cellHeight);break}}}}applyScalingMode(e,t){var i;let n=(i=this.rendererManagers.get(e))==null?void 0:i.getRenderer();if(n&&"setScalingMode"in n){let s=If(t);n.setScalingMode(s),this.log(`[Display ${e}] Scaling mode set to ${s}`)}}applyGridConfig(e,t){var i;let n=(i=this.rendererManagers.get(e))==null?void 0:i.getRenderer();if(n&&"setGrid"in n){let s=t.colorA/255;n.setGrid({enabled:t.enabled,color:`rgba(${t.colorR},${t.colorG},${t.colorB},${s})`,lineWidth:t.lineWidth}),this.log(`[Display ${e}] Grid ${t.enabled?"enabled":"disabled"}`)}}applySwitchPalette(e,t){var o;let n=this.core.getPaletteFromSlot(t.slotId);if(!n){this.pendingPaletteSlotByDisplay.set(e,t.slotId),console.warn(`[ClientRuntime] Palette slot ${t.slotId} not found (display ${e}); will retry when available`);return}let i=[];for(let a=0;a<256;a++){let l=n.get(a);l?i.push({r:l.r,g:l.g,b:l.b,a:l.a}):i.push({r:0,g:0,b:0,a:0})}let s=(o=this.rendererManagers.get(e))==null?void 0:o.getRenderer();s&&"setPalette"in s&&(s.setPalette(i),this.log(`[Display ${e}] Switched to palette slot ${t.slotId}`)),this.pendingPaletteSlotByDisplay.get(e)===t.slotId&&this.pendingPaletteSlotByDisplay.delete(e)}retryPendingPaletteSelections(){var e;if(this.pendingPaletteSlotByDisplay.size!==0)for(let[t,n]of this.pendingPaletteSlotByDisplay.entries()){let i=this.core.getPaletteFromSlot(n);if(!i)continue;let s=[];for(let a=0;a<256;a++){let l=i.get(a);l?s.push({r:l.r,g:l.g,b:l.b,a:l.a}):s.push({r:0,g:0,b:0,a:0})}let o=(e=this.rendererManagers.get(t))==null?void 0:e.getRenderer();o&&"setPalette"in o&&(o.setPalette(s),this.log(`[Display ${t}] Applied pending palette slot ${n}`),this.pendingPaletteSlotByDisplay.delete(t))}}applyCellSize(e,t,n){var s;let i=(s=this.rendererManagers.get(e))==null?void 0:s.getRenderer();i&&"setCellSize"in i&&(i.setCellSize(t,n),this.log(`[Display ${e}] Cell size set to ${t}×${n}px`))}patternFromType(e){switch(e){case 0:return"horizontal";case 1:return"vertical";case 2:return"grid";default:return"horizontal"}}dispatchLocalBridgeMessages(e){for(let t of e){let{channel:n,data:i}=t,s=this.localBridgeHandlers.get(n);if(s)for(let o of s)try{o(i)}catch(a){console.error(`[ClientRuntime] Bridge handler error on '${n}':`,a)}for(let o of this.localBridgeWildcardHandlers)try{o(n,i)}catch(a){console.error("[ClientRuntime] Bridge wildcard handler error:",a)}this.log(`Bridge message dispatched on channel '${n}'`)}}sendBridge(e,t){var n;if(this.mode!=="standalone"&&this.networkSync)this.networkSync.sendBridge(e,t);else if(this.mode==="standalone"){let i=this.core.getUser(this.userId);i&&((n=this.options.application)!=null&&n.onBridgeMessage)&&(this.options.application.onBridgeMessage(this,this.core,i,e,t),this.log(`Bridge message sent to application on channel '${e}'`))}}onBridge(e,t){this.mode!=="standalone"&&this.networkSync?this.networkSync.onBridge(e,t):this.mode==="standalone"&&(e==="*"?this.localBridgeWildcardHandlers.add(t):(this.localBridgeHandlers.has(e)||this.localBridgeHandlers.set(e,new Set),this.localBridgeHandlers.get(e).add(t)),this.log(`Bridge handler registered for channel '${e}'`))}offBridge(e,t){var n;this.mode!=="standalone"&&this.networkSync?this.networkSync.offBridge(e,t):this.mode==="standalone"&&(e==="*"?this.localBridgeWildcardHandlers.delete(t):(n=this.localBridgeHandlers.get(e))==null||n.delete(t))}removeAllBridgeHandlers(e){this.mode!=="standalone"&&this.networkSync?this.networkSync.removeAllBridgeHandlers(e):this.mode==="standalone"&&(e===void 0?(this.localBridgeHandlers.clear(),this.localBridgeWildcardHandlers.clear()):e==="*"?this.localBridgeWildcardHandlers.clear():this.localBridgeHandlers.delete(e))}log(e){}async onDestroy(){this.log("Destroying ClientRuntime resources..."),this.networkSync&&(this.networkSync.disconnect(),this.networkSync=null),this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.input&&(this.input.destroy(),this.input=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null),this.mobileVibration=null,this.autoplayOverlay=null,this.postProcessOverlays.clear(),this.postProcessOverlay=null,this.log("ClientRuntime resources destroyed")}};Ar(Nw,"ClientRuntime");var TE=Nw,RE=class{constructor(e={}){var t,n,i;se(this,"input"),se(this,"mobileVibration"),this.input=new hw({enableKeyboardMouse:!0,enableGamepad:!0,enableMobile:!0,targetElement:window,mobileTargetElement:void 0,debug:e.debug,keyboardConfig:{preventDefault:e.captureInput??!1,stopPropagation:e.captureInput??!1},mouseConfig:{preventDefault:e.captureInput??!1,stopPropagation:e.captureInput??!1},mobileConfig:{preventDefault:((t=e.mobileInputConfig)==null?void 0:t.preventDefault)??!1,passive:((n=e.mobileInputConfig)==null?void 0:n.passive)??!0,maxTouches:((i=e.mobileInputConfig)==null?void 0:i.maxTouches)??10}}),this.mobileVibration=new Uf({debug:e.debug})}setMobileTarget(e){this.input.setMobileTarget(e)}start(){this.input.start()}stop(){this.input.stop()}destroy(){this.input.destroy()}getRouter(){return this.input}getGamepad(){return this.input.getGamepad()}getMobileVibration(){return this.mobileVibration}collectAndApply(e,t,n,i,s){var c,d;if(t){let h=Er.collectMousePosition(this.input,t,n,i,s);e.setMousePosition(h.x,h.y,h.over),e.updateMacroMouse(h.x,h.y,h.isLeftDown),Er.collectTouchPositions(this.input,t,n,i,10,s).forEach(f=>{e.setTouchPosition(f.id,f.x,f.y,f.over)})}let o=Er.collectTextInputs(this.input);o.length>0&&e.setTextInputs(o);let a=e.getInputBindingRegistry(),l=a.getAllAxes(),u=a.getAllButtons();if(l.length>0||u.length>0){let h=Er.collectAxisSources(l,this.input),f=Er.collectButtonSourcesWithTransitions(u,this.input);l.forEach(p=>{let m=a.evaluateAxis(p.bindingId,h);e.setAxis(p.name,m)}),u.forEach(p=>{let m=new Map,S=new Map,w=new Map;for(let[x,I]of f)m.set(x,I.pressed),S.set(x,I.justPressed),w.set(x,I.justReleased);let g=a.evaluateButton(p.bindingId,m),y=a.evaluateButton(p.bindingId,S),C=a.evaluateButton(p.bindingId,w);e.setButton(p.name,g),e.setButton(`${p.name}_justPressed`,y),e.setButton(`${p.name}_justReleased`,C)})}(d=(c=this.input).poll)==null||d.call(c)}processVibrationCommands(e){e.hasMobileVibrationCommands()&&e.applyMobileVibrationCommands(e.flushMobileVibrationCommands()),e.hasGamepadVibrationCommands()&&e.applyGamepadVibrationCommands(e.flushGamepadVibrationCommands())}};Ar(RE,"InputFeature");var PE=class{constructor(e={}){se(this,"audioManager"),se(this,"debug"),this.debug=e.debug??!1,this.audioManager=new zw({debug:e.debug})}initialize(){this.audioManager.initialize()}playStartSound(){this.audioManager.playStartSound()}stopAll(){this.audioManager.stopAll()}destroy(){this.audioManager.destroy()}getManager(){return this.audioManager}getContext(){return this.audioManager.getContext()}injectIntoUser(e){e.setAudioProcessor(this.audioManager)}processAudioCommands(e){e.hasAudioConfigCommands()&&e.applyAudioConfigCommands(e.flushAudioConfigCommands()),e.hasSoundCommands()&&e.applyAudioCommands(e.flushSoundCommands())}async loadSoundsFromRegistry(e){let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load sounds: SoundBank not initialized");return}let n=e.getSoundRegistry().getAll();if(n.length===0){this.log("No sounds to load from registry");return}this.log(`Loading ${n.length} sounds from Core registry...`);for(let i of n)try{i.loadType==="file"&&i.data?(await t.loadFromData(i.soundId,i.name,i.data),this.log(`Loaded sound: ${i.name} (${i.data.length} bytes)`)):i.loadType==="external"&&i.url&&(await t.loadFromUrl(i.soundId,i.name,i.url),this.log(`Loaded external sound: ${i.name} from ${i.url}`))}catch(s){console.error(`[AudioFeature] Failed to load sound "${i.name}":`,s)}this.log(`${t.size} sounds loaded`)}log(e){this.debug&&console.warn(`[AudioFeature] ${e}`)}};Ar(PE,"AudioFeature");var BE=class{constructor(e,t={}){se(this,"overlay"),se(this,"orderCollector"),se(this,"debug"),this.debug=t.debug??!1,this.overlay=new Jv(e),this.orderCollector=new Mf}destroy(){this.overlay.destroy()}getOverlay(){return this.overlay}syncWithRenderer(e){this.overlay.syncWithRenderer(e),this.log("Overlay synced with renderer dimensions")}processCommands(e,t){if(!e.hasPostProcessCommands())return;let n=e.flushPostProcessCommands(),i=this.orderCollector.convertCommands(n);this.applyOrders(i,t)}applyOrders(e,t){for(let n of e){let i=n.displayId;switch(n.type){case Xr.SetConfig:{let s={};n.scanlines&&(s.scanlines={enabled:n.scanlines.enabled,opacity:n.scanlines.opacity,pattern:this.patternFromType(n.scanlines.pattern),color:{r:n.scanlines.colorR,g:n.scanlines.colorG,b:n.scanlines.colorB}}),n.ambientEffect&&(s.ambientEffect={enabled:n.ambientEffect.enabled,blur:n.ambientEffect.blur,scale:n.ambientEffect.scale}),this.overlay.setConfig(Object.keys(s).length>0?s:null),s.ambientEffect&&this.applyAmbientEffect(t,s.ambientEffect),this.log(`[Display ${i}] SetConfig applied`);break}case Xr.SetScanlines:{this.overlay.setScanlines({enabled:n.enabled,opacity:n.opacity,pattern:this.patternFromType(n.pattern),color:{r:n.colorR,g:n.colorG,b:n.colorB}}),this.log(`[Display ${i}] Scanlines ${n.enabled?"enabled":"disabled"}`);break}case Xr.SetAmbientEffect:{this.applyAmbientEffect(t,{enabled:n.enabled,blur:n.blur,scale:n.scale}),this.log(`[Display ${i}] Ambient effect ${n.enabled?"enabled":"disabled"}`);break}case Xr.SetScalingMode:{this.applyScalingMode(t,i,n.mode);break}case Xr.SetGrid:{this.applyGridConfig(t,i,n);break}}}}applyAmbientEffect(e,t){e&&"setAmbientEffect"in e&&(t.enabled?e.setAmbientEffect({blur:t.blur,scale:t.scale}):e.setAmbientEffect(!1))}applyScalingMode(e,t,n){if(e&&"setScalingMode"in e){let i=If(n);e.setScalingMode(i),this.log(`[Display ${t}] Scaling mode set to ${i}`)}}applyGridConfig(e,t,n){if(e&&"setGrid"in e){let i=n.colorA/255;e.setGrid({enabled:n.enabled,color:`rgba(${n.colorR},${n.colorG},${n.colorB},${i})`,lineWidth:n.lineWidth}),this.log(`[Display ${t}] Grid ${n.enabled?"enabled":"disabled"}`)}}patternFromType(e){switch(e){case 0:return"horizontal";case 1:return"vertical";case 2:return"grid";default:return"horizontal"}}log(e){this.debug&&console.warn(`[PostProcessFeature] ${e}`)}};Ar(BE,"PostProcessFeature");const zE={},dm=r=>{let e;const t=new Set,n=(c,d)=>{const h=typeof c=="function"?c(e):c;if(!Object.is(h,e)){const f=e;e=d??(typeof h!="object"||h===null)?h:Object.assign({},e,h),t.forEach(p=>p(e,f))}},i=()=>e,l={setState:n,getState:i,getInitialState:()=>u,subscribe:c=>(t.add(c),()=>t.delete(c)),destroy:()=>{(zE?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),t.clear()}},u=e=r(n,i,l);return l},DE=r=>r?dm(r):dm;var Vw={exports:{}},Hw={},jw={exports:{}},Yw={};/**
|
|
257
|
+
`)}destroy(){this.disconnect(),this.removeAllListeners()}sendBridge(e,t){this.send("bridge",{channel:e,data:t})}onBridge(e,t){this.bridgeHandlers.has(e)||this.bridgeHandlers.set(e,[]),this.bridgeHandlers.get(e).push(t)}offBridge(e,t){let n=this.bridgeHandlers.get(e);if(n){let i=n.indexOf(t);i!==-1&&n.splice(i,1)}}removeAllBridgeHandlers(e){e?this.bridgeHandlers.delete(e):this.bridgeHandlers.clear()}log(e,...t){this.options.debug&&console.warn(`[WebRTC-Client] ${e}`,...t)}parseCandidateType(e){return e?e.includes("typ host")?"host":e.includes("typ srflx")?"srflx":e.includes("typ relay")?"relay":"unknown":"unknown"}warn(e,...t){this.options.debug&&console.warn(`[WebRTC-Client] ${e}`,...t)}error(e,...t){console.error(`[WebRTC-Client] ❌ ${e}`,...t)}};zf(Aw,"WebRTCClient");var SE=Aw,Tw=Object.defineProperty,xE=(r,e,t)=>e in r?Tw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Rw=(r,e)=>Tw(r,"name",{value:e,configurable:!0}),gr=(r,e,t)=>(xE(r,typeof e!="symbol"?e+"":e,t),t),Pw=class{constructor(e,t=!1){gr(this,"sounds",new Map),gr(this,"nameToId",new Map),gr(this,"audioContext"),this.audioContext=e,this.log("SoundBank created")}async loadFromData(e,t,n){this.log(`Loading sound from data: ${t} (${n.length} bytes)`);try{let i=await this.decodeAudio(n);this.store(e,t,i,{source:"file",originalSize:n.length,loadedAt:Date.now()}),this.log(`✓ Loaded: ${t} (${i.duration.toFixed(2)}s)`)}catch(i){throw console.error(`[SoundBank] Failed to decode sound "${t}":`,i),i}}async loadFromUrl(e,t,n,i){this.log(`Loading sound from URL: ${t} → ${n}`);try{let s=await fetch(n);if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);let o=s.headers.get("content-length"),a=o?parseInt(o,10):0,l;if(a>0&&i&&s.body){let c=s.body.getReader(),d=[],h=0;for(;;){let{done:m,value:S}=await c.read();if(m)break;d.push(S),h+=S.length,i(h,a)}let f=new Uint8Array(h),p=0;for(let m of d)f.set(m,p),p+=m.length;l=f.buffer}else l=await s.arrayBuffer();let u=await this.decodeAudio(new Uint8Array(l));this.store(e,t,u,{source:"external",originalSize:l.byteLength,originalUrl:n,loadedAt:Date.now()}),this.log(`✓ Loaded from URL: ${t} (${u.duration.toFixed(2)}s)`)}catch(s){throw console.error(`[SoundBank] Failed to load sound "${t}" from ${n}:`,s),s}}loadFromBuffer(e,t,n){this.log(`Loading sound from buffer: ${t}`),this.store(e,t,n,{source:"procedural",loadedAt:Date.now()}),this.log(`✓ Loaded from buffer: ${t} (${n.duration.toFixed(2)}s)`)}store(e,t,n,i){if(this.sounds.has(e)){let o=this.sounds.get(e);this.log(`Replacing sound ID ${e} (was: ${o.name}, now: ${t})`),this.nameToId.delete(o.name)}if(this.nameToId.has(t)){let o=this.nameToId.get(t);o!==e&&this.log(`Warning: Sound name "${t}" already exists with ID ${o}`)}let s={soundId:e,name:t,buffer:n,duration:n.duration,metadata:i};this.sounds.set(e,s),this.nameToId.set(t,e)}async decodeAudio(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),this.audioContext.decodeAudioData(t)}get(e){if(typeof e=="number")return this.sounds.get(e);let t=this.nameToId.get(e);return t!==void 0?this.sounds.get(t):void 0}has(e){return this.get(e)!==void 0}getAll(){return Array.from(this.sounds.values())}getNames(){return Array.from(this.nameToId.keys())}get size(){return this.sounds.size}remove(e){let t=this.get(e);return t?(this.sounds.delete(t.soundId),this.nameToId.delete(t.name),this.log(`Removed sound: ${t.name}`),!0):!1}clear(){let e=this.sounds.size;this.sounds.clear(),this.nameToId.clear(),this.log(`Cleared ${e} sounds`)}getStats(){let e=this.getAll(),t=0;for(let n of e){let{buffer:i}=n;t+=i.length*i.numberOfChannels*4}return{totalSounds:e.length,totalDuration:e.reduce((n,i)=>n+i.duration,0),estimatedMemory:t,bySource:{file:e.filter(n=>n.metadata.source==="file").length,external:e.filter(n=>n.metadata.source==="external").length,procedural:e.filter(n=>n.metadata.source==="procedural").length}}}log(e){}};Rw(Pw,"SoundBank");var IE=Pw,Bw=class{constructor(e={}){gr(this,"audioContext",null),gr(this,"masterGainNode",null),gr(this,"soundBank",null),gr(this,"options"),gr(this,"initialized",!1),gr(this,"nextInstanceId",1),gr(this,"instances",new Map),gr(this,"instancesBySound",new Map),gr(this,"activeSounds",new Set),gr(this,"spatialSounds",new Map),gr(this,"spatialConfig",{listenerX:0,listenerY:0,maxDistance:200,referenceDistance:20,rolloffFactor:1,panSpread:1}),gr(this,"reverbConvolver",null),gr(this,"reverbGain",null),this.options={debug:e.debug??!1,masterVolume:e.masterVolume??1},this.log("AudioManager created")}initialize(){if(this.initialized&&this.audioContext)return this.log("AudioContext already initialized"),!0;try{let e=window.AudioContext||window.webkitAudioContext;return e?(this.audioContext=new e,this.log(`AudioContext initialized (state: ${this.audioContext.state}, sampleRate: ${this.audioContext.sampleRate}Hz)`),this.masterGainNode=this.audioContext.createGain(),this.masterGainNode.gain.value=this.options.masterVolume,this.masterGainNode.connect(this.audioContext.destination),this.audioContext.state==="suspended"&&this.audioContext.resume().then(()=>{this.log("AudioContext resumed")}),this.soundBank=new IE(this.audioContext,this.options.debug),this.initialized=!0,!0):(console.warn("[AudioManager] Web Audio API not supported"),!1)}catch(e){return console.error("[AudioManager] Failed to initialize AudioContext:",e),!1}}isInitialized(){return this.initialized&&this.audioContext!==null}getContext(){return this.audioContext}getMasterGain(){return this.masterGainNode}setMasterVolume(e){this.options.masterVolume=Math.max(0,Math.min(1,e)),this.masterGainNode&&(this.masterGainNode.gain.value=this.options.masterVolume),this.log(`Master volume set to ${this.options.masterVolume}`)}getMasterVolume(){return this.options.masterVolume}playStartSound(){if(!this.audioContext||!this.masterGainNode){this.log("Cannot play sound: AudioContext not initialized");return}try{let e=this.audioContext,t=e.currentTime,n=[262,330,392,523],i=.06,s=.07;n.forEach((o,a)=>{let l=t+a*s,u=e.createOscillator();u.type="square",u.frequency.setValueAtTime(o,l);let c=e.createGain();c.gain.setValueAtTime(0,l),c.gain.linearRampToValueAtTime(.15,l+.005),c.gain.setValueAtTime(.15,l+i-.01),c.gain.linearRampToValueAtTime(0,l+i),u.connect(c),c.connect(this.masterGainNode),u.start(l),u.stop(l+i)}),this.log("Start sound played (retro arpeggio)")}catch(e){console.error("[AudioManager] Failed to play start sound:",e)}}playTone(e,t,n={}){if(!this.audioContext||!this.masterGainNode){this.log("Cannot play tone: AudioContext not initialized");return}let{type:i="sine",volume:s=.3,attack:o=.01,release:a=.1}=n;try{let l=this.audioContext,u=l.currentTime,c=l.createOscillator();c.type=i,c.frequency.setValueAtTime(e,u);let d=l.createGain();d.gain.setValueAtTime(0,u),d.gain.linearRampToValueAtTime(s,u+o),d.gain.setValueAtTime(s,u+t-a),d.gain.linearRampToValueAtTime(0,u+t),c.connect(d),d.connect(this.masterGainNode),c.start(u),c.stop(u+t),this.log(`Tone played: ${e}Hz for ${t}s`)}catch(l){console.error("[AudioManager] Failed to play tone:",l)}}playNote(e,t,n={}){let i=this.noteToFrequency(e);if(i===null){console.warn(`[AudioManager] Invalid note: ${e}`);return}this.playTone(i,t,n)}noteToFrequency(e){let t=/^([A-Ga-g])([#b]?)(\d)$/,n=e.match(t);if(!n)return null;let[,i,s,o]=n,a=parseInt(o,10),l={C:0,D:2,E:4,F:5,G:7,A:9,B:11}[i.toUpperCase()];if(l===void 0)return null;s==="#"?l+=1:s==="b"&&(l-=1);let u=l+(a+1)*12;return 440*Math.pow(2,(u-49)/12)}async resumeContext(){this.audioContext&&this.audioContext.state==="suspended"&&(await this.audioContext.resume(),this.log("AudioContext resumed"))}async suspendContext(){this.audioContext&&this.audioContext.state==="running"&&(await this.audioContext.suspend(),this.log("AudioContext suspended"))}getState(){var e;return((e=this.audioContext)==null?void 0:e.state)??null}getSoundBank(){return this.soundBank}play(e,t={}){if(!this.audioContext||!this.masterGainNode||!this.soundBank)return this.log("Cannot play: not initialized"),null;let n=this.soundBank.get(e);if(!n)return console.warn(`[AudioManager] Sound not found: ${e}`),null;try{let i=this.audioContext,s=t.instanceId??this.nextInstanceId++;t.instanceId!==void 0&&t.instanceId>=this.nextInstanceId&&(this.nextInstanceId=t.instanceId+1);let o=i.createBufferSource();o.buffer=n.buffer,o.loop=t.loop??!1,o.playbackRate.value=t.pitch??1;let a=i.createGain(),l=t.volume??1,u=t.fadeIn??0,c={source:o,gainNode:a,soundName:n.name,stopped:!1,baseVolume:l,targetVolume:l,fadingOut:!1,paused:!1,pausedAt:0,startedAt:i.currentTime,loop:t.loop??!1,playbackRate:t.pitch??1,buffer:n.buffer,outputNode:a},d=l,h=l;if(t.position){let{pan:m,distanceVolume:S}=this.calculateSpatialAudio(t.position.x,t.position.y),w=i.createStereoPanner();w.pan.value=m,d=u>0?0:l*S,h=l*S,a.gain.setValueAtTime(d,i.currentTime),u>0&&(a.gain.linearRampToValueAtTime(h,i.currentTime+u),this.log(`Fade in: ${n.name} [#${s}] over ${u}s`)),o.connect(a),a.connect(w),w.connect(this.masterGainNode),c.pannerNode=w,c.position={x:t.position.x,y:t.position.y},c.targetVolume=h,c.outputNode=w,this.spatialSounds.set(o,{gainNode:a,pannerNode:w,position:{x:t.position.x,y:t.position.y},baseVolume:l}),this.log(`Playing spatial: ${n.name} [#${s}] at (${t.position.x}, ${t.position.y}) pan=${m.toFixed(2)} vol=${S.toFixed(2)}`)}else d=u>0?0:l,h=l,a.gain.setValueAtTime(d,i.currentTime),u>0&&(a.gain.linearRampToValueAtTime(h,i.currentTime+u),this.log(`Fade in: ${n.name} [#${s}] over ${u}s`)),o.connect(a),a.connect(this.masterGainNode);this.instances.set(s,c),(t.lowpass||t.highpass||t.reverb)&&this.setEffects(s,t.lowpass,t.highpass,t.reverb),this.instancesBySound.has(n.name)||this.instancesBySound.set(n.name,new Set),this.instancesBySound.get(n.name).add(s),this.activeSounds.add(o),o.onended=()=>{c.paused||this.cleanupInstance(s)},o.start(0,t.offset??0),t.position||this.log(`Playing: ${n.name} [#${s}]`);let f=this.stop.bind(this),p=this.instances;return{instanceId:s,stop:()=>{f(s)},get playing(){let m=p.get(s);return m!==void 0&&!m.stopped},sound:n}}catch(i){return console.error(`[AudioManager] Failed to play sound "${e}":`,i),null}}stop(e){return e==="all"?this.stopAll():typeof e=="number"?this.stopInstance(e)?1:0:this.stopByName(e)}fadeOut(e,t){if(!this.audioContext)return 0;let n=Math.max(.01,t);return e==="all"?this.fadeOutAll(n):typeof e=="number"?this.fadeOutInstance(e,n)?1:0:this.fadeOutByName(e,n)}fadeOutInstance(e,t){let n=this.instances.get(e);if(!n||n.stopped||n.fadingOut||!this.audioContext)return!1;let i=this.audioContext;n.fadingOut=!0;let s=n.gainNode.gain.value;return n.gainNode.gain.cancelScheduledValues(i.currentTime),n.gainNode.gain.setValueAtTime(s,i.currentTime),n.gainNode.gain.linearRampToValueAtTime(0,i.currentTime+t),setTimeout(()=>{this.stopInstance(e)},t*1e3),this.log(`Fading out instance #${e} (${n.soundName}) over ${t}s`),!0}fadeOutByName(e,t){let n=this.instancesBySound.get(e);if(!n||n.size===0)return 0;let i=0;for(let s of Array.from(n))this.fadeOutInstance(s,t)&&i++;return this.log(`Fading out ${i} instances of "${e}" over ${t}s`),i}fadeOutAll(e){let t=0;for(let n of Array.from(this.instances.keys()))this.fadeOutInstance(n,e)&&t++;return this.log(`Fading out all sounds (${t} instances) over ${e}s`),t}pause(e){return e==="all"?this.pauseAll():typeof e=="number"?this.pauseInstance(e)?1:0:this.pauseByName(e)}pauseInstance(e){let t=this.instances.get(e);if(!t||t.stopped||t.paused||t.fadingOut||!this.audioContext)return!1;let n=(this.audioContext.currentTime-t.startedAt)*t.playbackRate;if(t.loop)t.pausedAt=n%t.buffer.duration;else if(t.pausedAt=n,t.pausedAt>=t.buffer.duration)return!1;try{t.source.stop()}catch{}return t.paused=!0,this.log(`Paused instance #${e} (${t.soundName}) at ${t.pausedAt.toFixed(2)}s`),!0}pauseByName(e){let t=this.instancesBySound.get(e);if(!t||t.size===0)return 0;let n=0;for(let i of Array.from(t))this.pauseInstance(i)&&n++;return this.log(`Paused ${n} instances of "${e}"`),n}pauseAll(){let e=0;for(let t of Array.from(this.instances.keys()))this.pauseInstance(t)&&e++;return this.log(`Paused all sounds (${e} instances)`),e}resume(e){return e==="all"?this.resumeAll():typeof e=="number"?this.resumeInstance(e)?1:0:this.resumeByName(e)}resumeInstance(e){let t=this.instances.get(e);if(!t||t.stopped||!t.paused||!this.audioContext||!this.masterGainNode)return!1;let n=this.audioContext,i=n.createBufferSource();return i.buffer=t.buffer,i.loop=t.loop,i.playbackRate.value=t.playbackRate,i.connect(t.gainNode),t.source=i,t.paused=!1,t.startedAt=n.currentTime-t.pausedAt/t.playbackRate,i.onended=()=>{t.paused||this.cleanupInstance(e)},i.start(0,t.pausedAt),this.log(`Resumed instance #${e} (${t.soundName}) from ${t.pausedAt.toFixed(2)}s`),!0}resumeByName(e){let t=this.instancesBySound.get(e);if(!t||t.size===0)return 0;let n=0;for(let i of Array.from(t))this.resumeInstance(i)&&n++;return this.log(`Resumed ${n} instances of "${e}"`),n}resumeAll(){let e=0;for(let t of Array.from(this.instances.keys()))this.resumeInstance(t)&&e++;return this.log(`Resumed all sounds (${e} instances)`),e}stopInstance(e){let t=this.instances.get(e);if(!t||t.stopped)return!1;try{t.source.stop(),t.stopped=!0,this.log(`Stopped instance #${e} (${t.soundName})`)}catch{}return this.cleanupInstance(e),!0}stopByName(e){let t=this.instancesBySound.get(e);if(!t||t.size===0)return 0;let n=0;for(let i of Array.from(t))this.stopInstance(i)&&n++;return this.log(`Stopped ${n} instances of "${e}"`),n}cleanupInstance(e){let t=this.instances.get(e);if(!t)return;this.instances.delete(e);let n=this.instancesBySound.get(t.soundName);n&&(n.delete(e),n.size===0&&this.instancesBySound.delete(t.soundName)),this.activeSounds.delete(t.source),this.spatialSounds.delete(t.source)}resolveSoundIdToName(e){var t;return this.soundBank?((t=this.soundBank.get(e))==null?void 0:t.name)??null:null}stopBySoundId(e){let t=this.resolveSoundIdToName(e);return t?this.stopByName(t):(this.log(`stopBySoundId: Unknown soundId ${e}`),0)}fadeOutBySoundId(e,t){let n=this.resolveSoundIdToName(e);return n?this.fadeOutByName(n,t):(this.log(`fadeOutBySoundId: Unknown soundId ${e}`),0)}pauseBySoundId(e){let t=this.resolveSoundIdToName(e);return t?this.pauseByName(t):(this.log(`pauseBySoundId: Unknown soundId ${e}`),0)}resumeBySoundId(e){let t=this.resolveSoundIdToName(e);return t?this.resumeByName(t):(this.log(`resumeBySoundId: Unknown soundId ${e}`),0)}setListenerPosition(e,t){e===this.spatialConfig.listenerX&&t===this.spatialConfig.listenerY||(this.spatialConfig.listenerX=e,this.spatialConfig.listenerY=t,this.spatialSounds.size>0&&this.updateAllSpatialSounds())}updateAllSpatialSounds(){for(let[e,t]of this.spatialSounds){if(!this.activeSounds.has(e)){this.spatialSounds.delete(e);continue}let{pan:n,distanceVolume:i}=this.calculateSpatialAudio(t.position.x,t.position.y);t.pannerNode.pan.value=n,t.gainNode.gain.value=t.baseVolume*i}}getListenerPosition(){return{x:this.spatialConfig.listenerX,y:this.spatialConfig.listenerY}}configureSpatial(e){this.log(`configureSpatial called with: ${JSON.stringify(e)}`),e.listenerX!==void 0&&(this.spatialConfig.listenerX=Math.max(0,Math.min(65535,e.listenerX))),e.listenerY!==void 0&&(this.spatialConfig.listenerY=Math.max(0,Math.min(65535,e.listenerY))),e.maxDistance!==void 0&&(this.spatialConfig.maxDistance=Math.max(1,e.maxDistance)),e.referenceDistance!==void 0&&(this.spatialConfig.referenceDistance=Math.max(1,e.referenceDistance)),e.rolloffFactor!==void 0&&(this.spatialConfig.rolloffFactor=Math.max(0,e.rolloffFactor)),e.panSpread!==void 0&&(this.spatialConfig.panSpread=Math.max(0,Math.min(1,e.panSpread))),this.log(`spatialConfig now: maxDistance=${this.spatialConfig.maxDistance}, refDist=${this.spatialConfig.referenceDistance}, panSpread=${this.spatialConfig.panSpread}`)}getSpatialConfig(){return{...this.spatialConfig}}setEffects(e,t,n,i){if(!this.audioContext||!this.masterGainNode)return;let s=this.instances.get(e);if(!s||s.stopped){this.log(`setEffects: instance ${e} not found or stopped`);return}let o=this.audioContext;t!==void 0&&(t>0?(s.lowpassNode||(s.lowpassNode=o.createBiquadFilter(),s.lowpassNode.type="lowpass",s.lowpassNode.Q.value=1,this.insertFilterNode(s,s.lowpassNode)),s.lowpassNode.frequency.setValueAtTime(t,o.currentTime),this.log(`setEffects: instance ${e} lowpass=${t}Hz`)):s.lowpassNode&&(this.removeFilterNode(s,s.lowpassNode),s.lowpassNode=void 0,this.log(`setEffects: instance ${e} lowpass disabled`))),n!==void 0&&(n>0?(s.highpassNode||(s.highpassNode=o.createBiquadFilter(),s.highpassNode.type="highpass",s.highpassNode.Q.value=1,this.insertFilterNode(s,s.highpassNode)),s.highpassNode.frequency.setValueAtTime(n,o.currentTime),this.log(`setEffects: instance ${e} highpass=${n}Hz`)):s.highpassNode&&(this.removeFilterNode(s,s.highpassNode),s.highpassNode=void 0,this.log(`setEffects: instance ${e} highpass disabled`))),i!==void 0&&(i>0?(this.ensureReverbInitialized(),!s.reverbSendNode&&this.reverbConvolver&&(s.reverbSendNode=o.createGain(),s.reverbSendNode.gain.value=0,s.outputNode.connect(s.reverbSendNode),s.reverbSendNode.connect(this.reverbConvolver)),s.reverbSendNode&&(s.reverbSendNode.gain.setValueAtTime(i,o.currentTime),this.log(`setEffects: instance ${e} reverb=${i.toFixed(2)}`))):s.reverbSendNode&&(s.reverbSendNode.gain.setValueAtTime(0,o.currentTime),this.log(`setEffects: instance ${e} reverb disabled`)))}ensureReverbInitialized(){if(this.reverbConvolver||!this.audioContext||!this.masterGainNode)return;let e=this.audioContext,t=e.sampleRate,n=Math.floor(t*.5),i=e.createBuffer(1,n,t),s=i.getChannelData(0);for(let o=0;o<n;o++){let a=o/t,l=Math.exp(-a*6);s[o]=(Math.random()*2-1)*l}this.reverbConvolver=e.createConvolver(),this.reverbConvolver.buffer=i,this.reverbGain=e.createGain(),this.reverbGain.gain.value=.5,this.reverbConvolver.connect(this.reverbGain),this.reverbGain.connect(this.masterGainNode),this.log("Shared reverb initialized")}insertFilterNode(e,t){if(this.masterGainNode){try{e.outputNode.disconnect(this.masterGainNode)}catch{}e.outputNode.connect(t),t.connect(this.masterGainNode)}}removeFilterNode(e,t){if(this.masterGainNode){try{t.disconnect()}catch{}try{e.outputNode.disconnect(t)}catch{}e.outputNode.connect(this.masterGainNode)}}calculateSpatialAudio(e,t){let{listenerX:n,listenerY:i,maxDistance:s,referenceDistance:o,panSpread:a}=this.spatialConfig,l=e-n,u=t-i,c=Math.sqrt(l*l+u*u),d;c<=o?d=1:c>=s?d=0:d=1-(c-o)/(s-o);let h=0;return s>0&&a>0&&(h=l/s*a,h=Math.max(-1,Math.min(1,h))),{pan:h,distanceVolume:d}}stopAll(){let e=this.instances.size;for(let[,t]of this.instances)if(!t.stopped)try{t.source.stop(),t.stopped=!0}catch{}return this.instances.clear(),this.instancesBySound.clear(),this.activeSounds.clear(),this.spatialSounds.clear(),this.log(`Stopped all sounds (${e} instances)`),e}getPlayingCount(){return this.instances.size}getActiveInstances(){return Array.from(this.instances.keys())}isPlaying(e){let t=this.instances.get(e);return t!==void 0&&!t.stopped}destroy(){this.stopAll(),this.soundBank&&(this.soundBank.clear(),this.soundBank=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.masterGainNode=null,this.initialized=!1,this.log("AudioManager destroyed")}log(e){}};Rw(Bw,"AudioManager");var zw=Bw,Ow=Object.defineProperty,kE=(r,e,t)=>e in r?Ow(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ar=(r,e)=>Ow(r,"name",{value:e,configurable:!0}),se=(r,e,t)=>(kE(r,typeof e!="symbol"?e+"":e,t),t),Of=(r=>(r.TerminalGL="webgl",r.Terminal2D="terminal2d",r))(Of||{}),Dw=class{constructor(e=60){if(se(this,"frameCount",0),se(this,"fps",0),se(this,"fpsUpdateTime",0),se(this,"lastCoreTime",0),se(this,"lastRenderTime",0),se(this,"lastTotalTime",0),se(this,"coreTimeSamples",[]),se(this,"renderTimeSamples",[]),se(this,"totalTimeSamples",[]),se(this,"maxSamples"),e<=0)throw new Error("maxSamples must be positive");this.maxSamples=e}startTracking(e){this.fpsUpdateTime=e,this.frameCount=0,this.fps=0}updateFPS(e){this.frameCount++,e-this.fpsUpdateTime>=1e3&&(this.fps=Math.round(this.frameCount*1e3/(e-this.fpsUpdateTime)),this.frameCount=0,this.fpsUpdateTime=e)}recordFrameTiming(e,t){let n=e+t;this.lastCoreTime=e,this.lastRenderTime=t,this.lastTotalTime=n,this.coreTimeSamples.push(e),this.renderTimeSamples.push(t),this.totalTimeSamples.push(n),this.coreTimeSamples.length>this.maxSamples&&(this.coreTimeSamples.shift(),this.renderTimeSamples.shift(),this.totalTimeSamples.shift())}getFPS(){return this.fps}getLastFrameTiming(){if(!(this.lastCoreTime===0&&this.lastRenderTime===0))return{coreTime:this.lastCoreTime,renderTime:this.lastRenderTime,totalTime:this.lastTotalTime}}getAverageFrameTiming(){if(this.coreTimeSamples.length!==0)return{coreTime:this.average(this.coreTimeSamples),renderTime:this.average(this.renderTimeSamples),totalTime:this.average(this.totalTimeSamples)}}getStats(){return{fps:this.fps,lastFrame:this.getLastFrameTiming(),avgFrame:this.getAverageFrameTiming(),sampleCount:this.coreTimeSamples.length,maxSamples:this.maxSamples}}reset(){this.frameCount=0,this.fps=0,this.fpsUpdateTime=0,this.lastCoreTime=0,this.lastRenderTime=0,this.lastTotalTime=0,this.coreTimeSamples=[],this.renderTimeSamples=[],this.totalTimeSamples=[]}average(e){return e.length===0?0:e.reduce((t,n)=>t+n,0)/e.length}};Ar(Dw,"PerformanceMonitor");var EE=Dw,ME="iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAR8ElEQVR4Ae3BC3JbW5AkwUgOFy6uPCe6rcas5tgFBFDQ74nu4R9XcUfEHRV3RPzB3nlQxRKxVCwRo0JRhSIOVcSFihFxoYr4CSqWiCViqThULBGjYom4oUIRqlCEKhRVEapQhKo3HlChDFQxKg4VqhgVo2KpUMWhYqk4VKjihg5uyOBQ5VAxoh4iDhEXKpSBKi5U3FBxiCoOVfTGH6BiqVgiloilYqk4VIyKQ8SI+AkqFPGTVByiilFF6I2fLOJCxIhYIpYKRajiL9LBEjEi1IEifoHwoIolYqlYIpaKEXGhirihirihirihQhGjYkSoYkSoYolQhSKWiiVCFYo4VChiqThELBVLxKiiCkVV/ge/UBXxCRUj4lAxIh5UcUfEHRV3RBVLxFJxIUIVS8SFCkWMKkIVilAV/nEVd0TcUXFHxIMqFPGLhL9ExSHiyw8JSxVxRxVxoUIRS4UiVKEIVdwQVShiVCjiQRWKuFChiCdVKOKOCkU8qYp4oTdGxYMqDhWj4kEVihgRS4Q6UAYPqhgVh4pRMfodqGJU3FAxKg4dXKj4jg5u6GB5QxVPqhgVh4oXqVCEKp5QcagYFYeKB1QcKg4Vh4oHVIweGBWj4kHvKKp4QsSIUIUiHhR18EkVFyIUoQpFjIobqqjiQlTxk0UVijhUHKoIVSwVyv9gqSLuqCKWigsRT6hQVKEIVYyIpeJChCouRBV3RKhiiRgVS8SFiiVCFRcilirihgpFHCqWCIUXqVgiRoUiVKGIpUJRxRKhCkWMigsRo2KJeFKFIg4VirijQhEvVqGICxWKGOGFKhTxQhVLxCdUKOLL/3rnCRWKWCoUdUQsFYoqFHGoUMQh4oaKEfFJFYpYKhTxH/LGH6KD0cGFDkaFIlTxCRWKOESo4tDB6ODQwW/Wgd74BSpGxahQhSKUBWWgCkW8UIUibohQxRKhDhTxB6pQhMITKhTxpApFFYoYFYeIpUIRh4oR8aQKRdxRoQhV3BFVXIh4QMWFiCdUKGKEJ1Qo4gkVN0QsVVShCFUo4lChqEJRFfGACkXcUaGIpWKJOFQo4herUMQSfpEKRRWKUMWFCFUoQhWKUIUiVKGIJ1Qo4kKFIpYKRahCEUuFIi5UKOITKhSxVCjiEJ5QoYgnVSiqUMRSoYg7KhQxKkZUoYgnVChiqVDET1KhiE+oUMSXv0sHv1gYFUvEoUIRh4olYqlYIi5UKGJUXIhYKkbEqLgQMSqWiKViifgJKhTxhApFXKhYIhRUoQhVKGJUjIilQhGqUIQqFKEKRSwVI2JUKOKGCkV8R4UiVKEIVShCFYpQhSJeqEIRn1ChiKVCEapQ9M6h4kJUcSHijojvqPiOihExKhTxHRWKeLEKRVyoUMShQhGHigsRS9QRMSJGhSIUVHEhYqlQxA0VijhUjIhRoahCETdUKEIVh4hDhSIOFUvEUnGIWCoUcaFCEUuFIl6gQhFLhSJGUMWIKhSxVCjiQoUi7qhQhCouRFyoUIQqFKEKRYwKRRwqFKEKRVyoUMSLVCjiUHEh4lChiEOFIsY7S8QnVSjiUKGICxGjQhGjQhG/WYUiDhWKuFChiEPUEbFEPKBCERciDmFULBGj4kKEKi5EjIol4kKFIpaKJWKpWCKWCkVcqFgilooRcaFCERcqFHFDhSKeUKGIGyoU8eXX6uAPE0bFErFULBGj4hCxVCwRo2KJWCouRKjiQsSoWCJGhSJUoQhVXIgYFYcIVShCFYpQhSIuVChiVCiqUIQqFDEqlgi9oQploIpRoQxUcchAFaNCGajiEKGKCzlwyIFRoQxU8aAMRgZLBiPiQoUinlShiidUKANV6I1DxU+WwYUIVfwkGfxiFYr4pIobKp70zoWo4lBxR8WIeLGKEXGoGBEXKkbEUvGTRXxSVEUVFyqe8MaFigsZ3JCBKl4sCxeycEPEDRn8RBU/IOKGiCe9ccjCT9LBhQpF/CU6+I4IVfwkEU94R1EHI+JJFSNiRB2MiEOFIi5ULBEPiDoYEQ+qWCoUoagDRdwQdUQsFUvEC0QdjIgvX4IqDhFLxRIxKg4RS8USMSouRKhCEapQhCoUoQpFqEIRo0JRhSJUoQhVKEIVilDFhYhRsUQ8oWKJOFQo4kFvLBmoYlQoA1UcMlDFqFAGqhgZjAz+EjlwRwZLB3dkcEPFqHjQG79BBn+ICHWgiE+oUMSDIlTxCRXKQBUPeGPpQBFP6kARI0Jd+E0qLkSMiCVCHSjiUKGIJ0Wo4kkZjAwe8MaShRuqiAsRN2RBFb9YhSoOFaPiEDEiDhWK+KQIVfwib3xCFXEhQhWjg58kQh0o4kLEoUIZqOJBFYr4QRGq+AXeeUDUEXVEPCDqYEQ8KOpgRCxRhSIuRCiqeLGKJeJQoYgbIg4Vn1Dx5cstYVQo4kkViniBCkU8oWJEPKhCEXdUKOKGCkWMCkXcUDEifpE3RoQq/kIVilDFi2VwRwZPivgN3lmijoilYok4VIyIpWKJWCruqFgibog4VBwilooRsVSMiAsVI+KGCkU8oEIRqlCEKg4RS8USoTcOGRyyoIpDBqoYFcpAFaNCGRwqlIEqRsXoYKlQBjdkoIol4jsivqNCEU/qYFQsGahiVCgDVeidB1W8SMQnVFyIKhTxh6pQxCdEVVTxAu88oEIRqvgBFYp4QsQnRB38RlFHxB/gjQdEqIMbOlDEiFAHihgR6uAQoS48KQufUDEqlg4eEKGKpWJU3BDxpAh1oAiFf0TFEvFCFSPiLxH+EBWK+A+rGBFLhSKWihFxoUIRo4q4440vv0yFMnhQBqo4VCiqUMWhg+UdVRwilopDhCoUVShiqThEqGJUKGJUKEIVilCFIlShCFUoYlQoqlCEKhShCkWoQhGquBDxi0QoqlDEqBhVhN5YMlDFqFAGN1QRqhgVyoERMTL4SSoOEepAEQ/KwogYHSjikyLUwYhYMhgVhwq98UIRymBEqAt/mIgR8QkVilgyUMUnVSiDF3hnqRgRI+rgkyJGR8SFCkU8IOpgRBwqVHGoGFXEiDq4oUIRf5gIVShiBFUo4gEVilCFIi5UHCIOFSNiqThELBWKOFQoqlCEKhShCkVcqFCEKi5EHCpGxFKhiKViRHxCxRKhoApFPKBCEf+IiiXiPyCMiiViVChCFYo4VCjiUKGIpUIRqlDEqFDEDRWK+IQKRSwVilCFIkaFIg4VilCFIpYKRRwqFHGoUIQqFLFUKGLrYHTwpA4OHYwOntTBhYpR8YQORgdP6uBJHYwODh18QsWoGEEVirhQoQhVKGJULBFLxRKxVCwRS8USsVQsEUvFErFULBFLxRKxVCwRhwpFvFjFErFULBH/Twc3dDA6GB2MDm7o4IYObujghg5GBzd0MDoYHYwORgejg0MHN3RwQweHDkYHo4PRgd65UKGIJ1TcUHFHxR0Vd1T8oIo7Ku6o+I0q7qg4vKOogxHxpIgLFYpQxVKhCFUsFYpQxVKhCFUsUQcj4hBxR8QdEb9RhCouRKhivDEiRsQSoQ4OEerCEqEODhHq4BChDg4R6uBCxIhYItSFJUJdWCLUhb9NB/9RHXz5/7wzIlShiCdUXIgYFYpYKhShCkWMCkXcUKGIJ1QoQhWKUIUiVKEIVShCFYp4QsWIGBWKUIUiVHGIuFAx8j9YKhTxhApFFYoYFYpQhSKeUKGIpUIRqlDEUqGI36BCEYcKRRWKUIUiVKEIVShCFYpYKhRVKKjiQoQqFFWMCFUoqlDEUrFELBVLxFKxRLxIhSJUoYhRsUSMCkWoQhGj4hAxKhRxoWKJGBWHiEOFIsb/Qd+Eoo+F8TEqFH0bH/om9E2Mb+NDFYo+9G18CFUo+tC38SFUoehD38aHUPVNH0LVN30IVd/0IVR904fQN6EPoW9CH0IVij70bXwIfRP6EPom9CFUoehjYVSMb+NDjIrDN30IfROKPkb1IUbF+KYPoXeWihExKpaKC1GFIv4SUQe/QVShiEOEKhRxR8UhqlDEeGeJOFQoqlDEf0zEqHihqIMl4gEVS4UiDhWjirgjqOJChCpGVDGiCkUVS4QqloilYolYKpaIpeIQMSoOEaNiiVgqloilYok4VChiqbgQsVQoYqlQhCoUVSiqUMQIX/6TKhRVjIglHCoUcaFCERcqFHGhQhFLhaIKRYwKRRWKWCpGxKFiRBwqFPFCFYq4UKGIOyoU8SJhqVDEhQpFXKhQxIUKRSwViioUMSoUVSjihgpFjApFFYr4ySpGxKFiRPxib4yKUXEhgwsVo+JCBocMlMENEao4dPBJHbxQxIUKRVyoOHRwoQN1oA7UwfLOiBgdEUuFIpYKRagjQhWKUIUiVHGIOFQRFyoUVTypQhFLxQ1RxQ0RFyruqHhChaIKRSjqiDoi9M6o+M0i1BFxqLgQdXAh6kARo0IRN0RciDhU3FChiAsVilgqRhWhCkUViliijqgjekcVilDFHyiquCHijogHVCjiBSJUoYglQhWKeFDUEXVEjApFFYpQGBWHiKVCEYeKJWKpOESoQhGqUIQqFKEKRYyKQ8SoOESMiiXihSoUcaHiELFUKOJQoahCUYWiCkWM8OWnq1BUMSIuVCjiV6lYKlSxVCwVqlCFKg4d3NDBDR1c6EAdvFAH6mDpQB08oQN1sHSgDg4dPOGtQhGqUIQiVKEIVSiqoiqqooovf7S3CFUoQhWqUIQqFKEqqqIqqiK+/NHeqwxUZaAIVRmoyqiiKqqiKuKOijsqDlWEKu6ouCGquBChiqVCEQ+ouBChiqVCEaq4oeJCFaGKQ8SpYqlQxVKxVKhCFao4dHBDBzd04dCBOlg6UAeHLhw6UAdLB+pg6UAd/GIdLG8VilCFIhShCkWoQlEVVVEVVfwEET9RxD/iLUIVilCFKhShCkWoiqqoiqqIL3+0twpFqEIRilCFIlShqIqqqIoqvvzR3iNGxQ1RhTIYEYpQhCKeEPFJUUfEkyoUVShiRIyIJ0WMiEOFogpFPKhCUYUivuONL/+0N/6DunBHxT8uLBUvFjEqXixiVBwiVKGoYkSo4kKEKn6CCFX8Bu8sET+gQhF3RHxChSLuiHhAxIh4QFShiAdVKKpQxCGqUMSDKhRVKOI73vnyR6u4I+KOijve+fJHi/gBEXe88eWfFkaFogpFvFCFIg4ViioU8UIVijhUKKpQxFKhiAdV3BFxR8UScUfFE9748k9748s/7b1iqRgVPyjiUDEiloobKg4RqjhEFYeKGypGxRMq/jLhRSoUVSjiF6lQVKGIpUIRhwpFFYp4QoUiRsULRdxRsUTc8c53VNwR8aCKQ8SDKg4Rd1QcKkbEP+yd74gYFYr4hIgXiHhQxKhQxJf/9caXf1p4QMUhYlRciHhAxYWIX6hCEYeKJWKpWCIOFSPikyoUsVQsEaNiiVB4QIUiVKEIVShCFYp4QIUifoOKCxGqUIQqFKEKRahCEaNCET+gQhFLhSIOFYpQhaJ3VLFEFYp4UsRScUNGR8SFigtRhSJUoQhVXIgqFFUo6oh4gagjYqlQVDEiVHGoIlShiCe9VSgDVVzoQBEPihgRI2JEqOJQoQxGxAMyGBk8qYNPqBgVo0JRhSLUgSJGhCqWHnjAO0+IUEfEi1Qo4g8VoYol6mBEjApFqCPihSKe9BahDhTxC1Uo4gd0oIgHRKhiVCjiARXKQBUPiFCFogploIpRoQhFqOJJ7yjiEHGhQhEvVrFEKOpgRBwiPiFCFYpYog5GxIOiDkbEiFgiLkTcEHUwIhSxRDyjgz9UB/9BHfwk4QkVijhUKOKOCkVcqBgRS4UiXqxiRPwkFUtUoahCEaNiiXiRoIoLEUuFIi5UKOJChSIuVCiqUMSoUMSFCkUsFSOqUIQqFFUo4ieoUMRSoahCEYcKRbzAO4q4o2KpUMQSdUQsFYr4SSIOFYo6UMRfpkIRh4ol4gHvqOJChCJUoYgLFYo4RB0R3xHxoIoLGYyIC1EHirhQoYhfrEIRL/SOIn5QhSJuiDoiXiTijooRVShiRPygCkWMihHxCRWjQhEvEFRxIeIXqlDEqFBUoYgLFYoYFYoqRsQvUqGoQhEvVLFEPCA8oOJChCouRKjiQsRSoYhRoahCEX+ZiiXiDxD+IBWKWCpGxF+qYkT8Af4vDu0nt4v6zWEAAAAASUVORK5CYII=",Fo={glyphWidth:8,glyphHeight:8,cellWidth:8,cellHeight:8,atlasBlocks:1};function Fw(){if(typeof atob=="function"){let r=atob(ME),e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}throw new Error("[UTSP] decodeDefaultAtlas: atob() is not available in this environment")}Ar(Fw,"decodeDefaultAtlas");var Lw=class{constructor(e,t={}){se(this,"renderer"),se(this,"options"),se(this,"layerFilter",null),this.renderer=e,this.options={debug:t.debug??!1,useImageDataRendering:t.useImageDataRendering??!1}}setLayerFilter(e){this.layerFilter=e}getLayerFilter(){return this.layerFilter}async initialize(e){if("setImageDataRendering"in this.renderer&&this.options.useImageDataRendering&&(this.renderer.setImageDataRendering(!0),this.log("ImageData rendering enabled")),"setImageFont"in this.renderer&&typeof this.renderer.setImageFont=="function"){this.log("Loading default 8x8 font atlas...");let t=Fw();await this.renderer.setImageFont(t,Fo.glyphWidth,Fo.glyphHeight,Fo.cellWidth,Fo.cellHeight,Fo.atlasBlocks),this.log("Default 8x8 font atlas loaded")}await this.waitForReady(),this.log("Initialized and ready")}async waitForReady(e=100,t=50){this.log("Waiting for renderer to be ready");let n=0;return new Promise((i,s)=>{let o=Ar(()=>{if(n++,this.renderer.isReady())this.log(`Renderer ready after ${n*t}ms`),i();else if(n>=e){let a=`Renderer failed to be ready after ${e*t}ms`;this.log(a),s(new Error(a))}else setTimeout(o,t)},"check");o()})}async loadDefaultFont(e){console.warn("[RendererManager] loadDefaultFont() is deprecated. Use ImageFont instead.")}renderDisplay(e){return!this.renderer.isReady()||!e?!1:(this.renderer.renderDisplayData(e),!0)}render(e,t){let n=this.layerFilter?e.getRenderState(t,this.layerFilter):e.getRenderState(t);return!n||n.displays.length===0?!1:this.renderDisplay(n.displays[0])}getRenderer(){return this.renderer}getCanvas(){return this.renderer.getCanvas()}getAvailableSize(){if(this.renderer.getAvailableSize)return this.renderer.getAvailableSize();let e=this.getCanvas();return{width:(e==null?void 0:e.clientWidth)||(e==null?void 0:e.width)||0,height:(e==null?void 0:e.clientHeight)||(e==null?void 0:e.height)||0}}isReady(){return this.renderer.isReady()}destroy(){this.log("Destroying renderer"),this.renderer.destroy()}log(e){}};Ar(Lw,"RendererManager");var cm=Lw,_w=class{constructor(e){if(se(this,"core"),se(this,"rendererManagers",new Map),se(this,"rendererInitPromises",new Map),se(this,"rendererManager"),se(this,"rendererType"),se(this,"primaryDisplayId",0),se(this,"displayConfigs"),se(this,"options"),se(this,"running",!1),se(this,"startTime",0),se(this,"lastTimestamp",0),se(this,"userId",""),se(this,"visibilityChangeHandler"),se(this,"tickRate",30),se(this,"accumulatedTime",0),se(this,"FRAME_TIME_MIN",1e3/60),se(this,"lastRenderTimestamp",0),se(this,"rafId",0),se(this,"firstTickDone",!1),se(this,"performanceMonitor"),se(this,"renderMode","continuous"),se(this,"renderRequested",!1),this.options={application:e.application,container:e.container,displayContainers:e.displayContainers,debug:e.debug??!1,renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,renderMode:e.renderMode??"continuous"},this.log("Initializing BaseClientRuntime"),this.core=new Nv({mode:"client",maxUsers:1}),this.core.onPaletteChanged(t=>{this.onCorePaletteChanged(t)}),this.core.onFontAllocated(()=>{this.onCoreImageFontAllocated(0)}),this.core.onFontBlockAdded(t=>{this.onCoreImageFontBlockAdded(0,t)}),this.core.onImageFontChanged(t=>{this.onCoreImageFontChanged(t)}),this.visibilityChangeHandler=()=>{!document.hidden&&this.running&&(this.lastTimestamp=performance.now(),this.accumulatedTime=0,this.log("Tab visible: Reset timing"))},document.addEventListener("visibilitychange",this.visibilityChangeHandler),this.rendererType=this.options.renderer,this.options.displayContainers&&this.options.displayContainers.length>0){this.displayConfigs=new Map([[0,{container:this.options.container,renderer:this.options.renderer}]]);for(let t of this.options.displayContainers){let n=t.renderer;this.displayConfigs.set(t.id,{container:t.container,renderer:n})}this.primaryDisplayId=0}else this.displayConfigs=new Map([[0,{container:this.options.container,renderer:this.options.renderer}]]),this.primaryDisplayId=0;this.createRendererManagers(),this.performanceMonitor=new EE(60),this.tickRate=20,this.renderMode=e.renderMode??"continuous",this.log(`Configured: tickRate=${this.tickRate}, renderMode=${this.renderMode}`),this.log("BaseClientRuntime initialized")}getMode(){return"client"}createRenderer(e,t){if(t==="terminal2d"){this.log("Creating Terminal 2D renderer");let s=new uk(e,{fixedCols:80,fixedRows:25,cellAspectRatio:1});return this.log("Canvas 2D renderer created successfully"),s}this.log("Creating TerminalGL renderer");let n=document.createElement("canvas").getContext("webgl");if(!n)throw new Error("WebGL not supported. TerminalGL requires WebGL 1.0.");if(!n.getExtension("OES_element_index_uint"))throw new Error("OES_element_index_uint extension not supported. TerminalGL requires this extension for large terminals (256x256).");if(!(e instanceof HTMLDivElement))throw new Error(`TerminalGL requires container to be an HTMLDivElement. Received: ${e.tagName}`);let i=new lk(e,{cols:80,rows:25,charWidth:8,charHeight:8});return this.log("TerminalGL created successfully"),i}createRendererManagers(){let e=this.displayConfigs.size>=3;this.rendererManagers.clear();for(let[n,i]of this.displayConfigs.entries()){let s=e?"terminal2d":i.renderer??this.options.renderer,o=this.createRenderer(i.container,s??"webgl"),a=new cm(o,{debug:this.options.debug,useImageDataRendering:this.options.useImageDataRendering});this.rendererManagers.set(n,a)}let t=this.rendererManagers.get(this.primaryDisplayId);if(!t)throw new Error(`Primary display ${this.primaryDisplayId} has no renderer. Check displayContainers configuration.`);this.rendererManager=t}ensureRendererManager(e){var a;let t=this.rendererManagers.get(e);if(t)return t;let n=document.createElement("div");n.dataset.displayId=String(e),n.style.cssText="position:relative;display:inline-block;margin:4px;background:#000;overflow:hidden;",(((a=this.options.container)==null?void 0:a.parentElement)??document.body).appendChild(n),this.displayConfigs.set(e,{container:n});let i=this.displayConfigs.size>=3?"terminal2d":this.options.renderer??"webgl",s=this.createRenderer(n,i),o=new cm(s,{debug:this.options.debug,useImageDataRendering:this.options.useImageDataRendering});if(this.rendererManagers.set(e,o),!this.rendererInitPromises.has(e)){let l=o.initialize(this.core).then(()=>{this.onCorePaletteChanged(this.core.getPalette());let u=this.core.getImageFontIds,c=typeof u=="function"?u.call(this.core):[];c.length>0&&this.onCoreImageFontChanged(c[0]);let d=this.rebuildPostProcessOverlays;typeof d=="function"&&d.call(this)}).catch(u=>{console.warn(`[BaseClientRuntime] Failed to init renderer for display ${e}:`,u)});this.rendererInitPromises.set(e,l)}return o}getRendererType(){return this.rendererType}disconnectUser(e,t="Disconnected"){return this.log(`disconnectUser called for ${e} (Reason: ${t}) - No-op in BaseClientRuntime`),!1}isRunning(){return this.running}setTickRate(e){if(e<0||e>1e3)throw new Error(`Invalid tick rate: ${e}. Must be between 0 and 1000.`);if(this.tickRate=e,this.userId){let t=this.core.getUser(this.userId);t&&t.setBytesTickRate(e>0?e:20)}e===0&&this.renderMode==="continuous"?(this.renderMode="on-demand",this.log("Tick rate set to 0, switched to on-demand render mode")):this.log(`Tick rate set to ${e} TPS`)}setRenderMode(e){this.renderMode=e,this.log(`Render mode set to ${e}`)}setMaxFPS(e){if(e<=0||e>240)throw new Error(`Invalid FPS: ${e}. Must be between 1 and 240.`);this.FRAME_TIME_MIN=1e3/e,this.log(`Max FPS set to ${e}`)}getTickRate(){return this.tickRate}requestRender(){this.renderMode==="on-demand"&&(this.renderRequested=!0,this.log("Render requested"))}async start(){if(this.running){this.log("Already running");return}this.log("Starting BaseClientRuntime"),await this.onBeforeStart();for(let[e,t]of this.rendererManagers.entries())await t.initialize(this.core),this.log(`Renderer for display ${e} is ready`);this.onCorePaletteChanged(this.core.getPalette()),this.log("Initial palette sent to renderers"),this.options.application&&(this.log("Calling application.init()"),await this.options.application.init(this,this.core)),await this.onAfterInit(),await this.createLocalUser(),this.running=!0,this.startTime=performance.now(),this.lastTimestamp=this.startTime,this.lastRenderTimestamp=this.startTime,this.accumulatedTime=0,this.firstTickDone=!1,this.performanceMonitor.reset(),this.performanceMonitor.startTracking(this.startTime),this.log("Starting main loop"),this.mainLoop(this.lastTimestamp)}async onBeforeStart(){}async onAfterInit(){}async stop(){var t;if(!this.running)return;this.log("Stopping BaseClientRuntime"),this.running=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0),await this.onStop();let e=this.core.getUser(this.userId);e&&((t=this.options.application)!=null&&t.destroyUser)&&this.options.application.destroyUser(this,this.core,e,"Runtime stopped"),this.log("BaseClientRuntime stopped")}async onStop(){}getStats(){let e=this.performanceMonitor.getStats();return{running:this.running,userCount:this.core.getUsers().length,fps:e.fps,uptime:this.running?performance.now()-this.startTime:0,totalFrames:0,lastFrameTiming:e.lastFrame,avgFrameTiming:e.avgFrame}}getTotalBytesReceived(){var e;return((e=this.core.getUser(this.userId))==null?void 0:e.getTotalBytesReceived())??0}getBytesReceivedPerSecond(){var e;return((e=this.core.getUser(this.userId))==null?void 0:e.getBytesReceivedPerSecond())??0}resetBytesReceived(){let e=this.core.getUser(this.userId);e&&e.resetByteCounters()}async destroy(){var e;await this.stop(),this.log("Destroying BaseClientRuntime"),this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=void 0),await this.onDestroy();for(let t of this.rendererManagers.values()){let n=t.getRenderer();n&&"clearOnResizeCallback"in n&&n.clearOnResizeCallback()}(e=this.options.application)!=null&&e.destroy&&this.options.application.destroy(this);for(let t of this.rendererManagers.values())t.destroy();this.log("BaseClientRuntime destroyed")}async onDestroy(){}async createLocalUser(){var s;this.userId="local",this.log(`Creating local user: ${this.userId}`);let e=this.core.createUser(this.userId,"User");e.setBytesTickRate(this.tickRate>0?this.tickRate:20),this.onUserCreated(e),(s=this.options.application)!=null&&s.initUser&&(this.log("Calling application.initUser()"),this.options.application.initUser(this,this.core,e,{username:"User"})),this.processInitialOrders(e);let t=this.core.generateAllLoadPackets();t.forEach(o=>{e.recordBytesReceived(o.length)});let n=this.core.generateMacroLoadPackets(this.userId);n.forEach(o=>{e.recordBytesReceived(o.length)});let i=e.getInputBindingsLoadPacket();i&&e.recordBytesReceived(i.length),this.log(`Simulated ${t.length} load packets, ${n.length} macro packets for byte counting`),this.log("Performing initial render"),this.core.endTick().forEach(({static:o,dynamic:a},l)=>{let u=this.core.getUser(l);u&&(o&&u.recordBytesReceived(o.length),a&&u.recordBytesReceived(a.length))})}processInitialOrders(e){if(e.hasPendingMacroOrders()){this.log("Applying macro orders from initUser()");let t=e.flushMacroOrders();e.applyMacroOrders(t)}}onUserCreated(e){}mainLoop(e){var u,c,d,h;if(!this.running){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0);return}if(this.renderMode==="on-demand"){this.renderRequested&&(this.renderRequested=!1,this.performanceMonitor.updateFPS(e),this.render()),this.rafId=requestAnimationFrame(f=>this.mainLoop(f));return}let t=e-this.lastRenderTimestamp;if(this.lastRenderTimestamp>0&&t<this.FRAME_TIME_MIN-1){this.rafId=requestAnimationFrame(f=>this.mainLoop(f));return}this.lastRenderTimestamp=e;let n=(e-this.lastTimestamp)/1e3,i=Math.min(n,.1);this.lastTimestamp=e,this.performanceMonitor.updateFPS(e);let s=this.core.getUser(this.userId);if(!s){this.rafId=requestAnimationFrame(f=>this.mainLoop(f));return}if(this.tickRate===0){let f=performance.now();this.render();let p=performance.now()-f;this.performanceMonitor.recordFrameTiming(0,p),this.rafId=requestAnimationFrame(m=>this.mainLoop(m));return}if(!this.firstTickDone){this.firstTickDone=!0,this.lastTimestamp=e,this.accumulatedTime=0,this.rafId=requestAnimationFrame(f=>this.mainLoop(f));return}this.accumulatedTime+=i;let o=1/this.tickRate;this.accumulatedTime>.5&&(this.accumulatedTime=o);let a=0,l=0;for(;this.accumulatedTime>=o&&a<5;){let f=performance.now();this.collectAndApplyInput(s),this.options.application&&((c=(u=this.options.application).update)==null||c.call(u,this,this.core,o),(h=(d=this.options.application).updateUser)==null||h.call(d,this,this.core,s,o)),this.processTickOrders(s);let p=s.updateMacros();s.processMacroEvents(p),this.core.endTick().forEach(({static:m,dynamic:S})=>{let w=((m==null?void 0:m.length)??0)+((S==null?void 0:S.length)??0);s.recordBytesReceived(w)}),l+=performance.now()-f,this.accumulatedTime-=o,a++}if(a>0){let f=performance.now();this.render();let p=performance.now()-f;this.performanceMonitor.recordFrameTiming(l,p)}this.rafId=requestAnimationFrame(f=>this.mainLoop(f))}collectAndApplyInput(e){}processTickOrders(e){if(e.clearTextInputs(),e.hasPendingMacroOrders()){let t=e.flushMacroOrders();e.applyMacroOrders(t)}}render(){let e=this.core.getUser(this.userId);if(e){let n=e.getMacroRenderOrders();for(let[i,s]of n){let o=e.getLayerById(i);o&&s.length>0&&o.addTemporaryOrders(s)}}let t=this.core.getRenderState(this.userId);if(!(!t||t.displays.length===0))for(let n of t.displays){let i=this.rendererManagers.get(n.id)??this.ensureRendererManager(n.id);if(!i)continue;let s=i.getLayerFilter(),o=s?this.core.getRenderState(this.userId,s):t;if(!o){this.options.debug&&this.log(`Render state unavailable for display ${n.id} with filter`);continue}let a=o.displays.find(u=>u.id===n.id);if(!a){this.options.debug&&this.log(`Render state missing display ${n.id} after filtering`);continue}if(!i.isReady()){this.options.debug&&this.log(`Renderer for display ${n.id} not ready yet`);continue}let l=i.getRenderer();(l.getCols()!==a.width||l.getRows()!==a.height)&&(this.options.debug&&this.log(`Resizing renderer ${n.id}: ${l.getCols()}x${l.getRows()} → ${a.width}x${a.height}`),l.resize(a.width,a.height)),i.renderDisplay(a)}}onCorePaletteChanged(e){this.log(`Palette changed, updating renderer (${e.size} colors)`);let t=[];for(let s=0;s<256;s++){let o=e.get(s);o?t.push({r:o.r,g:o.g,b:o.b,a:o.a}):t.push({r:0,g:0,b:0,a:0})}let n=Ar(s=>{s&&"setPalette"in s&&typeof s.setPalette=="function"&&s.setPalette(t)},"applyPalette"),i=0;for(let s of this.rendererManagers.values()){let o=s.getRenderer();o&&(n(o),i++)}i===0||this.log(`✓ Palette updated on ${i} renderer(s)`)}onCoreImageFontAllocated(e){let t=this.core.getImageFont(e);if(!t)return;this.log(`Allocating image font ${e} structure: blocks=${t.getAtlasBlocks()}, size=${t.getGlyphWidth()}x${t.getGlyphHeight()}`);let n=Ar(i=>{i&&typeof i.setImageFontStructure=="function"&&i.setImageFontStructure(t.getGlyphWidth(),t.getGlyphHeight(),t.getCellWidth(),t.getCellHeight(),t.getAtlasBlocks())},"applyStruct");for(let i of this.rendererManagers.values()){let s=i.getRenderer();s&&n(s)}}onCoreImageFontBlockAdded(e,t){let n=this.core.getImageFont(e);if(!n)return;let i=n.getBlock(t);if(!i)return;let s=Ar(o=>{o&&typeof o.setImageFontBlock=="function"&&o.setImageFontBlock(t,i)},"applyBlock");for(let o of this.rendererManagers.values()){let a=o.getRenderer();a&&s(a)}}onCoreImageFontChanged(e){this.log(`Image font ${e} changed (legacy event), updating renderer`),this.onCoreImageFontAllocated(e);let t=this.core.getImageFont(e);if(!t)return;let n=t.getAtlasBlocks();for(let i=0;i<n;i++)t.getBlock(i)&&this.onCoreImageFontBlockAdded(e,i);for(let[i,s]of this.rendererManagers.entries()){let o=s.getRenderer();o&&this.onFontChanged(o,i)}}onFontChanged(e,t){}log(e){}getCore(){return this.core}getRendererManager(e=this.primaryDisplayId){let t=this.rendererManagers.get(e);if(!t)throw new Error(`Renderer manager for display ${e} not found`);return t}setDisplayContainers(e){this.displayConfigs=new Map(e.map(n=>[n.id,{container:n.container}]));let t=Array.from(this.displayConfigs.keys());this.primaryDisplayId=t.length>0?Math.min(...t):0;for(let n of this.rendererManagers.values())n.destroy();this.rendererManagers.clear(),this.createRendererManagers()}getUserId(){return this.userId}};Ar(_w,"BaseClientRuntime");var UE=_w,Gn=1e3,$w=class{constructor(e,t,n,i,s,o){se(this,"network"),se(this,"core"),se(this,"rendererManagers"),se(this,"primaryDisplayId"),se(this,"performanceMonitor"),se(this,"options"),se(this,"layerTraffic",new Map),se(this,"miscTraffic",new Map),se(this,"displayTraffic",new Map),se(this,"audioManager",null),se(this,"postProcessCallback",null),se(this,"soundHandlersSetup",!1),se(this,"userId",""),se(this,"lastReceivedTick",-1),se(this,"connected",!1),se(this,"totalBytesReceived",0),se(this,"lastSentViewports",new Map),se(this,"lastCollectedTouches",[]),se(this,"touchZonesCallback",null),se(this,"onUpdateReceived",null),se(this,"audioLoadingState",{totalExpected:0,loadedSounds:new Set,errors:new Map}),this.network=e,this.core=t,this.rendererManagers=n,this.primaryDisplayId=o,this.performanceMonitor=i,this.options={serverUrl:s.serverUrl,username:s.username,token:s.token??"",debug:s.debug??!1,autoReconnect:s.autoReconnect??!0,canvasWidth:s.canvasWidth,canvasHeight:s.canvasHeight}}getPrimaryRendererManager(){return this.rendererManagers.get(this.primaryDisplayId)??Array.from(this.rendererManagers.values())[0]}async connect(){this.log(`Connecting to ${this.options.serverUrl}`),await this.network.connect(),this.connected=!0,this.log("Connected to server"),this.setupNetworkHandlers()}async joinGame(e,t){return new Promise((n,i)=>{this.network.send("join",{username:this.options.username,token:this.options.token}),this.network.on("join_response",s=>{if(s.success){this.userId=s.userId,this.log(`Joined game as ${this.userId}`);let o=this.core.createUser(this.userId,this.options.username);o.setBytesTickRate(20),this.audioManager&&o.setAudioProcessor(this.audioManager),t!=null&&t.initUser&&t.initUser(e,this.core,o,{username:this.options.username,token:this.options.token}),n(this.userId)}else i(new Error(s.error||"Failed to join game"))}),setTimeout(()=>i(new Error("Join timeout")),5e3)})}sendInput(e){var C,x,I;let t=this.core.getUser(this.userId);if(!t)return;let n=this.getPrimaryRendererManager(),i=n==null?void 0:n.getCanvas();if(i){let E=t.getDisplays(),A=((C=E.find(V=>V.getId&&V.getId()===this.primaryDisplayId)??E[0])==null?void 0:C.getSize())??{x:this.options.canvasWidth,y:this.options.canvasHeight},R=A.x,F=A.y,z=(I=(x=n==null?void 0:n.getRenderer())==null?void 0:x.getOffsets)==null?void 0:I.call(x),P={offsetX:(z==null?void 0:z.offsetX)??0,offsetY:(z==null?void 0:z.offsetY)??0},D=Er.collectMousePosition(e,i,R,F,P);t.setMousePosition(D.x,D.y,D.over),t.updateMacroMouse(D.x,D.y,D.isLeftDown);let L=Er.collectTouchPositions(e,i,R,F,10,P);L.forEach(V=>{t.setTouchPosition(V.id,V.x,V.y,V.over)}),this.lastCollectedTouches=L}else this.lastCollectedTouches=[];let s=t.getInputBindingRegistry(),o=s.getAllAxes(),a=s.getAllButtons(),l=Er.collectAxisSources(o,e),u=Er.collectButtonSources(a,e),c=Er.collectTextInputs(e);c.length>0&&t.setTextInputs(c);let d=o.sort((E,A)=>E.bindingId-A.bindingId),h=new Map;for(let E of d){let A=s.evaluateAxis(E.bindingId,l);h.set(E.bindingId,A),t.setAxis(E.name,A)}let f=a.sort((E,A)=>E.bindingId-A.bindingId),p=new Map;for(let E of f){let A=s.evaluateButton(E.bindingId,u);p.set(E.bindingId,A),t.setButton(E.name,A)}let m=t.getMouseDisplayInfo(),S=t.getIsMouseOnADisplay(),w=this.collectChangedViewports(),g=this.lastCollectedTouches.map(E=>({id:E.id,x:E.x,y:E.y,over:E.over})),y=Hv(BigInt(this.core.currentTick),h,p,(m==null?void 0:m.displayId)??0,(m==null?void 0:m.localX)??0,(m==null?void 0:m.localY)??0,S,c,[],w,g,document.hidden);this.network.send("input",y)}collectChangedViewports(){let e=[];for(let[t,n]of this.rendererManagers.entries()){let{width:i,height:s}=n.getAvailableSize();if(i===0||s===0)continue;let o=this.lastSentViewports.get(t);(!o||o.pixelWidth!==i||o.pixelHeight!==s)&&(e.push({displayId:t,pixelWidth:i,pixelHeight:s}),this.lastSentViewports.set(t,{pixelWidth:i,pixelHeight:s}),this.log(`Viewport changed: display ${t} = ${i}x${s}px`))}return e}disconnect(){this.connected&&(this.network.send("leave",{}),this.network.disconnect(),this.connected=!1,this.soundHandlersSetup=!1,this.log("Disconnected from server"))}getUserId(){return this.userId}isConnected(){return this.connected}getTotalBytesReceived(){return this.totalBytesReceived}getPing(){return this.network.getPing()}getAudioLoadingState(){let e=this.audioLoadingState.loadedSounds.size,t=this.audioLoadingState.totalExpected,n=this.audioLoadingState.errors.size,i=t>0&&e>=t,s=Array.from(this.audioLoadingState.errors.keys());return{loadedCount:e,totalExpected:t,errorCount:n,isComplete:i,errors:s}}destroy(){this.disconnect(),this.network.destroy(),this.log("NetworkSync destroyed")}setupNetworkHandlers(){this.network.on("update",e=>{var t;try{let n=this.convertToUint8Array(e,"update");if(!n)return;this.recordBytesReceived(n.length);let i=this.core.applyUpdatePacketBuffer(this.userId,n);i?(this.postProcessCallback&&i.postProcessOrders&&i.postProcessOrders.length>0&&this.postProcessCallback(i.postProcessOrders),(t=this.onUpdateReceived)==null||t.call(this)):this.log("Failed to apply update packet")}catch(n){this.log(`Error applying update packet: ${n}`)}}),this.network.on("update-static",e=>{this.handleUpdatePacket(e,"update-static")}),this.network.on("update-dynamic",e=>{this.handleUpdatePacket(e,"update-dynamic")}),this.network.on("load",e=>{try{let t=this.convertToUint8Array(e,"load");if(!t)return;this.recordBytesReceived(t.length),this.core.applyLoadPacket(t)?this.log("Load packet applied successfully"):this.log("Failed to apply load packet")}catch(t){this.log(`Error applying load packet: ${t}`)}}),this.network.on("input-bindings",e=>{var t;if(this.recordBytesReceived(e.length),this.core.applyInputBindingsLoadPacket(this.userId,e)){this.log("Input bindings configured");try{let n=JSON.parse(e);if(this.log(`Touch zones in packet: ${((t=n.touchZones)==null?void 0:t.length)??0}, callback defined: ${!!this.touchZonesCallback}`),n.touchZones&&n.touchZones.length>0&&this.touchZonesCallback){let i=n.touchZones.map(s=>({id:s.zoneId,x:s.x,y:s.y,width:s.width,height:s.height}));this.touchZonesCallback(i),this.log(`Touch zones configured: ${i.length} zones`)}}catch{}}else this.log("Failed to apply input bindings")}),this.audioManager&&this.setupSoundHandlers(),this.network.on("disconnect",()=>{this.connected=!1,this.soundHandlersSetup=!1,this.log("Disconnected from server")})}handleUpdatePacket(e,t){var n;try{let i=this.convertToUint8Array(e,t);if(!i)return;this.recordBytesReceived(i.length);let s=new DataView(i.buffer,i.byteOffset,i.byteLength),o=Number(s.getBigUint64(0,!1));if(t==="update-dynamic"&&o<this.lastReceivedTick)return;o>this.lastReceivedTick&&(this.lastReceivedTick=o);let a=this.core.applyUpdatePacketBuffer(this.userId,i);if(a){let l=performance.now(),u=Ar((g,y)=>{if(y<=0)return;let C=this.miscTraffic.get(g)??{total:0,windowSum:0,samples:[]};C.total+=y,C.windowSum+=y,C.samples.push({time:l,bytes:y}),this.miscTraffic.set(g,C)},"recordMisc"),c=Ar(g=>{try{return JSON.stringify(g).length}catch{return 0}},"safeLen"),d=a.__byteSizes,h=d==null?void 0:d.audioOrders;typeof h=="number"?u("update.audioOrders",h):a.audioOrders&&a.audioOrders.length&&u("update.audioOrders",c(a.audioOrders));let f=d==null?void 0:d.vibrationOrders;typeof f=="number"?u("update.vibrationOrders",f):a.vibrationOrders&&a.vibrationOrders.length&&u("update.vibrationOrders",c(a.vibrationOrders));let p=d==null?void 0:d.macroOrders;typeof p=="number"?u("update.macroOrders",p):a.macroOrders&&a.macroOrders.length&&u("update.macroOrders",c(a.macroOrders));let m=d==null?void 0:d.postProcessOrders;if(typeof m=="number"?u("update.postProcessOrders",m):a.postProcessOrders&&a.postProcessOrders.length&&u("update.postProcessOrders",c(a.postProcessOrders)),a.displays&&a.displays.length)for(let g of a.displays){let y=g.id;if(typeof y!="number")continue;let C=this.displayTraffic.get(y)??{total:0,windowSum:0,samples:[]},x=7;C.total+=x,C.windowSum+=x,C.samples.push({time:l,bytes:x}),this.displayTraffic.set(y,C)}for(let g of a.layers){let y=g.byteSize??0,C=this.layerTraffic.get(g.id)??{total:0,windowSum:0,samples:[]};C.total+=y,C.windowSum+=y,C.samples.push({time:l,bytes:y});let x=l-Gn;for(;C.samples.length&&C.samples[0].time<x;){let I=C.samples.shift();I&&(C.windowSum-=I.bytes)}this.layerTraffic.set(g.id,C)}{let g=l-Gn;this.miscTraffic.forEach((y,C)=>{for(;y.samples.length&&y.samples[0].time<g;){let x=y.samples.shift();x&&(y.windowSum-=x.bytes)}y.windowSum<0&&(y.windowSum=0),this.miscTraffic.set(C,y)})}{let g=l-Gn;this.displayTraffic.forEach((y,C)=>{for(;y.samples.length&&y.samples[0].time<g;){let x=y.samples.shift();x&&(y.windowSum-=x.bytes)}y.windowSum<0&&(y.windowSum=0),this.displayTraffic.set(C,y)})}this.postProcessCallback&&a.postProcessOrders&&a.postProcessOrders.length>0&&this.postProcessCallback(a.postProcessOrders),this.options.debug&&this.debugRenderState();let S=performance.now();(n=this.onUpdateReceived)==null||n.call(this);let w=performance.now()-S;this.performanceMonitor.recordFrameTiming(0,w),this.options.debug&&this.log(`render() completed for ${t} (${w.toFixed(2)}ms)`)}else this.options.debug&&this.log(`Failed to apply ${t} packet (tick ${o})`)}catch(i){this.log(`Error applying ${t} update packet: ${i}`),console.error(i)}}convertToUint8Array(e,t){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):e.data&&Array.isArray(e.data)?new Uint8Array(e.data):typeof e=="object"&&e.type==="Buffer"?new Uint8Array(e.data):(this.log(`Unknown data type for ${t} packet: ${typeof e}`),null)}debugRenderState(){var n;let e=this.core.getUser(this.userId);if(e){let i=e.getLayers();this.log(`User has ${i.length} layers`),i.forEach((s,o)=>{let a=s.getOrders(),l=s.getMustBeReliable();(a.length>0||l)&&this.log(` Layer ${o}: ${a.length} orders, reliable=${l}, z=${s.getZOrder()}`)})}let t=((n=this.getPrimaryRendererManager())==null?void 0:n.isReady())??!1;this.log(`Renderer ready: ${t}`)}log(e){}recordBytesReceived(e){this.totalBytesReceived+=e;let t=this.core.getUser(this.userId);t&&t.recordBytesReceived(e)}getLayerTrafficStats(){let e={},t=performance.now()-Gn;return this.layerTraffic.forEach((n,i)=>{for(;n.samples.length&&n.samples[0].time<t;){let s=n.samples.shift();s&&(n.windowSum-=s.bytes)}n.windowSum<0&&(n.windowSum=0),e[i]={total:n.total,bytesPerSec1s:n.windowSum/(Gn/1e3)}}),e}getMiscTrafficStats(){let e={},t=performance.now()-Gn;return this.miscTraffic.forEach((n,i)=>{for(;n.samples.length&&n.samples[0].time<t;){let s=n.samples.shift();s&&(n.windowSum-=s.bytes)}n.windowSum<0&&(n.windowSum=0),e[i]={total:n.total,bytesPerSec1s:n.windowSum/(Gn/1e3)}}),e}getDisplayTrafficStats(){let e={},t=performance.now()-Gn;return this.displayTraffic.forEach((n,i)=>{for(;n.samples.length&&n.samples[0].time<t;){let s=n.samples.shift();s&&(n.windowSum-=s.bytes)}n.windowSum<0&&(n.windowSum=0),e[i]={total:n.total,bytesPerSec1s:n.windowSum/(Gn/1e3)}}),e}getSoundPacketSize(e){return e.mode==="file"?e.sounds.reduce((t,n)=>t+this.getSoundDataLength(n.data)+n.name.length+10,0):e.sounds.reduce((t,n)=>t+n.url.length+n.name.length+10,0)}getSoundDataLength(e){if(e instanceof Uint8Array)return e.length;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;let t=globalThis.Buffer;return t&&e instanceof t?e.length:e&&typeof e=="object"&&Array.isArray(e.data)?e.data.length:Array.isArray(e)?e.length:0}setAudioManager(e){if(this.audioManager=e,e&&this.userId){let t=this.core.getUser(this.userId);t&&t.setAudioProcessor(e)}this.connected&&e&&this.setupSoundHandlers()}setPostProcessCallback(e){this.postProcessCallback=e}setTouchZonesCallback(e){this.touchZonesCallback=e}setupSoundHandlers(){if(this.audioManager){if(this.soundHandlersSetup){this.log("Sound handlers already registered, skipping");return}this.soundHandlersSetup=!0,this.network.on("sound-load",async e=>{this.recordBytesReceived(this.getSoundPacketSize(e)),e.totalSounds!==void 0&&e.totalSounds>this.audioLoadingState.totalExpected&&(this.audioLoadingState.totalExpected=e.totalSounds,this.log(`Audio loading: expecting ${e.totalSounds} total sounds`)),e.mode==="file"?await this.handleSoundLoad(e):e.mode==="external"&&await this.handleSoundExternalLoad(e)}),this.log("Sound handlers registered")}}async handleSoundLoad(e){if(!this.audioManager){this.log("Cannot load sounds: AudioManager not initialized");return}let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load sounds: SoundBank not initialized");return}for(let n of e.sounds)try{let i=this.normalizeSoundData(n.data);await t.loadFromData(n.soundId,n.name,i),this.log(`Loaded sound: ${n.name} (${i.length} bytes)`),this.audioLoadingState.loadedSounds.add(n.name),this.audioLoadingState.errors.delete(n.name),this.sendAudioAck({type:"sound-loaded",soundId:n.soundId,name:n.name})}catch(i){console.error(`[NetworkSync] Failed to load sound "${n.name}":`,i),this.audioLoadingState.errors.set(n.name,String(i)),this.sendAudioAck({type:"sound-error",soundId:n.soundId,name:n.name,error:String(i)})}}normalizeSoundData(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));let t=globalThis.Buffer;if(t&&e instanceof t)return new Uint8Array(e);if(e&&typeof e=="object"&&Array.isArray(e.data))return new Uint8Array(e.data);if(Array.isArray(e))return new Uint8Array(e);if(typeof e=="string")try{let n=atob(e),i=n.length,s=new Uint8Array(i);for(let o=0;o<i;o++)s[o]=n.charCodeAt(o);return s}catch{}throw new Error("Invalid sound data payload")}async handleSoundExternalLoad(e){if(!this.audioManager){this.log("Cannot load external sounds: AudioManager not initialized");return}let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load external sounds: SoundBank not initialized");return}for(let n of e.sounds)try{await t.loadFromUrl(n.soundId,n.name,n.url),this.log(`Loaded external sound: ${n.name} from ${n.url}`),this.audioLoadingState.loadedSounds.add(n.name),this.audioLoadingState.errors.delete(n.name),this.sendAudioAck({type:"sound-loaded",soundId:n.soundId,name:n.name})}catch(i){console.error(`[NetworkSync] Failed to load external sound "${n.name}":`,i),this.audioLoadingState.errors.set(n.name,String(i)),this.sendAudioAck({type:"sound-error",soundId:n.soundId,name:n.name,error:String(i)})}}sendAudioAck(e){this.network.send("audio-ack",e),this.log(`Sent audio-ack: ${e.type}`)}sendBridge(e,t){var n,i;(i=(n=this.network).sendBridge)==null||i.call(n,e,t),this.log(`Bridge sent on channel '${e}'`)}onBridge(e,t){var n,i;(i=(n=this.network).onBridge)==null||i.call(n,e,t),this.log(`Bridge handler registered for channel '${e}'`)}offBridge(e,t){var n,i;(i=(n=this.network).offBridge)==null||i.call(n,e,t),this.log(`Bridge handler removed for channel '${e}'`)}removeAllBridgeHandlers(e){var t,n;(n=(t=this.network).removeAllBridgeHandlers)==null||n.call(t,e),this.log(e?`All bridge handlers removed for '${e}'`:"All bridge handlers removed")}};Ar($w,"NetworkSync");var AE=$w,Nw=class extends UE{constructor(e){let t=e.mode;if(t!=="standalone"&&t!=="socketio"&&t!=="webrtc")throw new Error(`Invalid ClientRuntime mode: "${t}". Expected 'standalone', 'socketio', or 'webrtc'.`);let n;if(e.mode==="standalone"&&(n=e.standalone.application),!n&&e.mode==="standalone")throw new Error("Application instance required for standalone mode");super({application:n,container:e.container,displayContainers:e.displayContainers,debug:e.debug,renderer:e.renderer,useImageDataRendering:e.useImageDataRendering,renderMode:e.renderMode}),se(this,"input",null),se(this,"networkSync",null),se(this,"mode"),se(this,"localOptions",null),se(this,"autoplayOverlay",null),se(this,"autoplay",!0),se(this,"audioManager",null),se(this,"mobileVibration",null),se(this,"postProcessOverlay",null),se(this,"postProcessOverlays",new Map),se(this,"postProcessOrderCollector",new Mf),se(this,"pendingPaletteSlotByDisplay",new Map),se(this,"localBridgeHandlers",new Map),se(this,"localBridgeWildcardHandlers",new Set),se(this,"visibilityHandler",null),this.mode=e.mode,this.autoplay=e.autoplay??!0,e.mode==="standalone"?(this.localOptions=e,this.userId=e.standalone.userId??"local"):this.localOptions=null,this.mode==="standalone"?(this.log("Initializing in STANDALONE mode"),this.initLocalMode()):(this.log(`Initializing in ${this.mode.toUpperCase()} mode`),this.initConnectedMode(e))}initLocalMode(){let e=this.localOptions;e&&(this.log("Initializing ClientRuntime (standalone mode)"),e.inputEnabled??!0?this.initInput(e):this.log("Input disabled (inputEnabled: false)"))}initConnectedMode(e){this.log(`Initializing ClientRuntime (${this.mode} mode)`),this.core=new Nv({mode:"client",maxUsers:100}),this.core.onPaletteChanged(i=>{this.onCorePaletteChanged(i),this.retryPendingPaletteSelections()}),this.visibilityHandler=()=>{this.networkSync&&this.input&&this.networkSync.sendInput(this.input)},document.addEventListener("visibilitychange",this.visibilityHandler),this.core.onImageFontChanged(i=>{this.onCoreImageFontChanged(i)});let t;if(e.mode==="webrtc"){let i=e.webrtc;t=new SE({url:i.signalUrl??"",sessionId:i.sessionId,signalingPath:i.signalingPath,iceServers:i.iceServers,autoReconnect:i.autoReconnect,auth:i.auth??{username:i.username},debug:e.debug})}else{let i=e.socketio;if(!i)throw new Error(`SocketIO configuration missing. Mode is '${e.mode}' but 'socketio' options are undefined.`);t=new bE({url:i.url??"",path:i.path,autoReconnect:i.autoReconnect,auth:i.auth??{username:i.username},debug:e.debug})}let n=e.mode==="socketio"?e.socketio:e.webrtc;this.networkSync=new AE(t,this.core,this.rendererManagers,this.performanceMonitor,{serverUrl:e.mode==="socketio"?e.socketio.url:e.webrtc.signalUrl||"WebRTC",username:n.username??"User",debug:e.debug,autoReconnect:n.autoReconnect,canvasWidth:80,canvasHeight:25},this.primaryDisplayId),this.networkSync&&(this.networkSync.onUpdateReceived=()=>{this.renderRequested=!0}),(e.inputEnabled??!0)&&(this.input||this.initInput(e))}initInput(e){var t,n,i,s,o,a,l,u,c,d;this.input=new hw({enableKeyboardMouse:!0,enableGamepad:!0,enableMobile:!0,targetElement:window,mobileTargetElement:((t=e.touchZones)==null?void 0:t.targetElement)??void 0,debug:e.debug,keyboardConfig:{preventDefault:e.captureInput??!1,stopPropagation:e.captureInput??!1},mouseConfig:{preventDefault:e.captureInput??!1,stopPropagation:e.captureInput??!1},mobileConfig:{preventDefault:((n=e.mobileInputConfig)==null?void 0:n.preventDefault)??!1,passive:((i=e.mobileInputConfig)==null?void 0:i.passive)??!0,maxTouches:((s=e.mobileInputConfig)==null?void 0:s.maxTouches)??10},enableTouchZones:((o=e.touchZones)==null?void 0:o.enable)??!1,touchZoneConfig:{targetElement:(a=e.touchZones)==null?void 0:a.targetElement,gridWidth:((l=e.touchZones)==null?void 0:l.gridWidth)??0,gridHeight:((u=e.touchZones)==null?void 0:u.gridHeight)??0,rendererOffsets:(c=e.touchZones)==null?void 0:c.rendererOffsets,zones:(d=e.touchZones)==null?void 0:d.zones}})}rebuildPostProcessOverlays(){for(let e of this.postProcessOverlays.values())e.destroy();this.postProcessOverlays.clear(),this.postProcessOverlay=null;for(let[e,t]of this.displayConfigs.entries()){let n=new Jv(t.container);this.postProcessOverlays.set(e,n),e===this.primaryDisplayId&&(this.postProcessOverlay=n)}!this.postProcessOverlay&&this.postProcessOverlays.size>0&&(this.postProcessOverlay=Array.from(this.postProcessOverlays.values())[0]??null)}getMode(){return this.mode}setTickRate(e){if(this.mode!=="standalone"){this.log("setTickRate() has no effect in connected mode");return}super.setTickRate(e)}async onBeforeStart(){this.audioManager=new zw({debug:this.options.debug}),this.mobileVibration=new Uf({debug:this.options.debug}),this.autoplay?(this.log("Autoplay enabled, initializing AudioManager..."),this.audioManager.initialize()):(this.log("Autoplay disabled, showing overlay..."),await new Promise(e=>{var t;this.autoplayOverlay=new ck(this.options.container,{...(t=this.localOptions)==null?void 0:t.autoplayOptions,onStart:()=>{this.log("User clicked start button"),this.audioManager&&(this.audioManager.initialize(),this.audioManager.playStartSound()),this.mobileVibration&&this.mobileVibration.vibrate(50),this.autoplayOverlay&&(this.autoplayOverlay.destroy(),this.autoplayOverlay=null),e()}})}),this.log("Autoplay overlay dismissed, continuing startup..."))}async start(){if(this.running){this.log("Already running");return}this.log("Starting ClientRuntime"),await this.onBeforeStart();for(let[n,i]of this.rendererManagers.entries())await i.initialize(this.core),this.log(`Renderer for display ${n} is ready`);this.rebuildPostProcessOverlays(),this.log("PostProcessOverlays created"),this.onCorePaletteChanged(this.core.getPalette()),this.log("Initial palette sent to renderer"),this.options.application&&(this.log("Calling application.init()"),await this.options.application.init(this,this.core));let e=this.rendererManager.getCanvas();if(e&&this.input&&this.input.setMobileTarget(e),this.mode!=="standalone"&&this.networkSync){if(this.audioManager&&this.networkSync.setAudioManager(this.audioManager),this.networkSync.setPostProcessCallback(i=>{this.applyPostProcessOrders(i)}),this.input){let i=this.input,s=this.rendererManager;this.networkSync.setTouchZonesCallback(o=>{this.log(`[start] Touch zones callback called with ${o.length} zones`);let a=s.getCanvas();if(this.log(`[start] Canvas available: ${!!a}`),a){let l=o.reduce((d,h)=>Math.max(d,h.x+h.width),0),u=o.reduce((d,h)=>Math.max(d,h.y+h.height),0);this.log(`[start] Grid from zones: ${l}x${u}`);let c=i.enableTouchZonesDevice(a,l,u,o);this.log(`[start] enableTouchZonesDevice returned: ${c}`),c&&this.log(`Touch zones configured from server: ${o.length} zones`)}})}await this.networkSync.connect(),this.userId=await this.networkSync.joinGame(this,this.options.application);let n=this.core.getUser(this.userId);n&&this.configureUserProcessors(n)}else await this.createLocalUser();let t=this.core.getUser(this.userId);if(t){let n=t.getDisplays();if(n.length>0){let i=n[0].getSize(),s=i.x,o=i.y,a=this.rendererManager.getRenderer(),l,u;if(this.rendererType==="webgl"){let c=a.getGridSize();l=c.cols,u=c.rows}else{let c=a;l=c.getCols(),u=c.getRows()}(l!==s||u!==o)&&(this.log(`Adjusting renderer from ${l}×${u} to match display ${s}×${o}`),a.resize(s,o))}}this.input&&this.input.start(),this.running=!0,this.startTime=performance.now(),this.lastTimestamp=this.startTime,this.lastRenderTimestamp=this.startTime,this.accumulatedTime=0,this.firstTickDone=!1,this.performanceMonitor.reset(),this.performanceMonitor.startTracking(this.startTime),this.log("Starting main loop"),this.mainLoop(this.lastTimestamp)}async onStop(){this.audioManager&&this.audioManager.stopAll(),this.input&&this.input.stop(),this.mode!=="standalone"&&this.networkSync&&this.networkSync.disconnect()}getStats(){var s;let e=super.getStats(),t=this.core.getUser(this.userId),n=t==null?void 0:t.getTotalBytesReceived(),i=t==null?void 0:t.getBytesReceivedPerSecond();return{...e,mode:this.mode,latency:((s=this.networkSync)==null?void 0:s.getPing())??0,totalBytesReceived:n,bytesReceivedPerSec:i}}getAudioLoadingState(){if(this.mode!=="standalone"&&this.networkSync)return this.networkSync.getAudioLoadingState();if(this.audioManager){let e=this.audioManager.getSoundBank();if(e){let t=e.getStats();return{loadedCount:t.totalSounds,totalExpected:t.totalSounds,errorCount:0,isComplete:!0,errors:[]}}}return{loadedCount:0,totalExpected:0,errorCount:0,isComplete:!0,errors:[]}}configureUserProcessors(e){if(this.audioManager&&e.setAudioProcessor(this.audioManager),this.mobileVibration&&e.setMobileVibrationProcessor(this.mobileVibration),this.input){let t=this.input.getGamepad();t&&e.setGamepadVibrationProcessor(t)}}async createLocalUser(){var o;let e=this.localOptions;this.userId=(e==null?void 0:e.standalone.userId)??"local",this.log(`Creating local user: ${this.userId}`);let t=this.core.createUser(this.userId,(e==null?void 0:e.standalone.username)??"User");if(t.setBytesTickRate(this.tickRate>0?this.tickRate:20),this.configureUserProcessors(t),(o=this.options.application)!=null&&o.initUser&&(this.log("Calling application.initUser()"),this.options.application.initUser(this,this.core,t,{username:(e==null?void 0:e.standalone.username)??"User"})),t.hasAudioConfigCommands()&&(this.log("Applying audio config commands from initUser()"),t.applyAudioConfigCommands(t.flushAudioConfigCommands())),t.hasPendingMacroOrders()){this.log("Applying macro orders from initUser()");let a=t.flushMacroOrders();t.applyMacroOrders(a)}if(t.hasPostProcessCommands()){this.log("Applying post-process commands from initUser()");let a=t.flushPostProcessCommands(),l=this.postProcessOrderCollector.convertCommands(a);this.applyPostProcessOrders(l)}t.needsSendSounds()&&(await this.loadSoundsFromRegistry(),t.clearSendSounds());let n=this.core.generateAllLoadPackets();n.forEach(a=>{t.recordBytesReceived(a.length)});let i=this.core.generateMacroLoadPackets(this.userId);i.forEach(a=>{t.recordBytesReceived(a.length)});let s=t.getInputBindingsLoadPacket();if(s&&(t.recordBytesReceived(s.length),this.input)){let a=t.getInputBindingRegistry().getAllTouchZones();if(a.length>0){let l=this.rendererManager.getCanvas();if(l){let u=t.getDisplays(),c=u.length>0?u[0].getSize():{x:80,y:25},d=a.map(h=>({id:h.zoneId,x:h.x,y:h.y,width:h.width,height:h.height}));this.input.enableTouchZonesDevice(l,c.x,c.y,d)?this.log(`Touch zones synchronized from registry: ${a.length} zones`):this.log("Failed to enable touch zones - mobile input may not be initialized")}}}this.log(`Simulated ${n.length} load packets, ${i.length} macro packets for byte counting`),this.log("Performing initial render"),this.core.endTick().forEach(({static:a,dynamic:l},u)=>{let c=this.core.getUser(u);c&&(a&&c.recordBytesReceived(a.length),l&&c.recordBytesReceived(l.length))}),this.render(),this.log("Initial render complete")}async loadSoundsFromRegistry(){if(!this.audioManager){this.log("Cannot load sounds: AudioManager not initialized");return}let e=this.audioManager.getSoundBank();if(!e){this.log("Cannot load sounds: SoundBank not initialized");return}let t=this.core.getSoundRegistry().getAll();if(t.length===0){this.log("No sounds to load from registry");return}this.log(`Loading ${t.length} sounds from Core registry into AudioManager...`);let n=this.core.getUser(this.userId),i=0;for(let s of t)try{if(s.loadType==="file"&&s.data){await e.loadFromData(s.soundId,s.name,s.data);let o=s.data.length+s.name.length+10;i+=o,this.log(`🔊 Loaded sound: ${s.name} (${s.data.length} bytes)`)}else if(s.loadType==="external"&&s.url){await e.loadFromUrl(s.soundId,s.name,s.url);let o=s.url.length+s.name.length+10;i+=o,this.log(`🔊 Loaded external sound: ${s.name} from ${s.url}`)}}catch(o){console.error(`[ClientRuntime] Failed to load sound "${s.name}":`,o)}n&&i>0&&(n.recordBytesReceived(i),this.log(`Simulated ${i} bytes for ${t.length} sound(s)`)),this.log(`✓ ${e.size} sounds loaded into AudioManager`)}mainLoop(e){var o,a,l,u;if(!this.running){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0);return}if(this.renderMode==="on-demand"){this.renderRequested&&(this.renderRequested=!1,this.performanceMonitor.updateFPS(e),this.render()),this.rafId=requestAnimationFrame(c=>this.mainLoop(c));return}let t=e-this.lastRenderTimestamp;if(this.lastRenderTimestamp>0&&t<this.FRAME_TIME_MIN-1){this.rafId=requestAnimationFrame(c=>this.mainLoop(c));return}this.lastRenderTimestamp=e;let n=(e-this.lastTimestamp)/1e3,i=Math.min(n,.1);this.lastTimestamp=e,this.performanceMonitor.updateFPS(e);let s=this.core.getUser(this.userId);if(!s){this.rafId=requestAnimationFrame(c=>this.mainLoop(c));return}if(this.mode==="standalone"){if(this.tickRate===0){let f=performance.now();this.render();let p=performance.now()-f;this.performanceMonitor.recordFrameTiming(0,p),this.rafId=requestAnimationFrame(m=>this.mainLoop(m));return}if(!this.firstTickDone){this.firstTickDone=!0,this.lastTimestamp=e,this.accumulatedTime=0,this.rafId=requestAnimationFrame(f=>this.mainLoop(f));return}this.accumulatedTime+=i;let c=1/this.tickRate;this.accumulatedTime>.5&&(this.accumulatedTime=c);let d=0,h=0;for(;this.accumulatedTime>=c&&d<5;){let f=performance.now();if(this.collectAndApplyInput(s),this.options.application&&((a=(o=this.options.application).update)==null||a.call(o,this,this.core,c),(u=(l=this.options.application).updateUser)==null||u.call(l,this,this.core,s,c)),s.clearTextInputs(),s.hasAudioConfigCommands()&&s.applyAudioConfigCommands(s.flushAudioConfigCommands()),s.hasSoundCommands()&&s.applyAudioCommands(s.flushSoundCommands()),s.hasMobileVibrationCommands()&&s.applyMobileVibrationCommands(s.flushMobileVibrationCommands()),s.hasGamepadVibrationCommands()&&s.applyGamepadVibrationCommands(s.flushGamepadVibrationCommands()),s.hasPostProcessCommands()){let m=s.flushPostProcessCommands(),S=this.postProcessOrderCollector.convertCommands(m);this.applyPostProcessOrders(S)}if(s.hasPendingMacroOrders()){let m=s.flushMacroOrders();s.applyMacroOrders(m)}let p=s.updateMacros();if(s.processMacroEvents(p),s.hasBridgeMessages()){let m=s.getBridgeMessages();this.dispatchLocalBridgeMessages(m)}this.core.endTick().forEach(({static:m,dynamic:S})=>{let w=((m==null?void 0:m.length)??0)+((S==null?void 0:S.length)??0);s.recordBytesReceived(w)}),h+=performance.now()-f,this.accumulatedTime-=c,d++}if(d>0){let f=performance.now();this.render();let p=performance.now()-f;this.performanceMonitor.recordFrameTiming(h,p)}}else{let c=s.updateMacros();s.processMacroEvents(c),this.collectAndSendInput(),this.accumulatedTime+=i;let d=1/(this.tickRate>0?this.tickRate:20);for(this.accumulatedTime>.5&&(this.accumulatedTime=d);this.accumulatedTime>=d;)s.endTickBytes(),this.accumulatedTime-=d;(this.renderRequested||this.renderMode==="continuous")&&(this.renderRequested=!1,this.render())}this.rafId=requestAnimationFrame(c=>this.mainLoop(c))}collectAndApplyInput(e){var a,l,u,c,d,h;if(!this.input)return;let t=this.rendererManager.getCanvas();if(t){let f=e.getDisplays(),p=((a=f.find(x=>x.getId&&x.getId()===this.primaryDisplayId)??f[0])==null?void 0:a.getSize())??{x:80,y:25},m=p.x,S=p.y,w=(u=(l=this.rendererManager.getRenderer())==null?void 0:l.getOffsets)==null?void 0:u.call(l),g={offsetX:(w==null?void 0:w.offsetX)??0,offsetY:(w==null?void 0:w.offsetY)??0};this.input.updateTouchZoneLayout(m,S,g);let y=Er.collectMousePosition(this.input,t,m,S,g);e.setMousePosition(y.x,y.y,y.over),e.updateMacroMouse(y.x,y.y,y.isLeftDown),Er.collectTouchPositions(this.input,t,m,S,10,g).forEach(x=>{e.setTouchPosition(x.id,x.x,x.y,x.over)});let C=(c=this.rendererManagers.get(this.primaryDisplayId))==null?void 0:c.getAvailableSize();C&&e.setDisplayViewport(this.primaryDisplayId,C.width,C.height)}let n=Er.collectTextInputs(this.input);n.length>0&&e.setTextInputs(n);let i=e.getInputBindingRegistry(),s=i.getAllAxes(),o=i.getAllButtons();if(s.length>0||o.length>0){let f=Er.collectAxisSources(s,this.input),p=Er.collectButtonSourcesWithTransitions(o,this.input);s.forEach(m=>{let S=i.evaluateAxis(m.bindingId,f);e.setAxis(m.name,S)}),o.forEach(m=>{let S=new Map,w=new Map,g=new Map;for(let[I,E]of p)S.set(I,E.pressed),w.set(I,E.justPressed),g.set(I,E.justReleased);let y=i.evaluateButton(m.bindingId,S),C=i.evaluateButton(m.bindingId,w),x=i.evaluateButton(m.bindingId,g);e.setButton(m.name,y),e.setButton(`${m.name}_justPressed`,C),e.setButton(`${m.name}_justReleased`,x)})}(h=(d=this.input).poll)==null||h.call(d)}collectAndSendInput(){!this.networkSync||!this.input||this.networkSync.sendInput(this.input)}render(){let e=this.core.getUser(this.userId);if(e){let t=e.getDisplays();for(let n of t){let i=n.getId(),s=this.rendererManagers.get(i);if(!s){console.warn(`[ClientRuntime] No renderer for display ${i}, skipping resize`);continue}let o=s.getRenderer();if(!o)continue;let a=n.getSize(),l,u,c,d,h=null;if("getGridSize"in o){let p=o,m=p.getGridSize();l=m.cols,u=m.rows,c=p.getCellWidth(),d=p.getCellHeight(),h=p.getScalingMode()}else if("getCols"in o){let p=o;l=p.getCols(),u=p.getRows(),c=p.getCellWidth(),d=p.getCellHeight(),h=p.getScalingMode()}else continue;if(h===Vt.Responsive){let p=s.getAvailableSize(),m=256*256;"getMaxCells"in o&&(m=Math.min(m,o.getMaxCells()));let S=Math.floor(p.width/c),w=Math.floor(p.height/d);if(S=Math.min(256,Math.max(1,S)),w=Math.min(256,Math.max(1,w)),S*w>m){let g=Math.sqrt(m/(S*w));S=Math.max(1,Math.floor(S*g)),w=Math.max(1,Math.floor(w*g)),this.log(`⚠️ [Display ${i}] Device limit: max ${m} cells, clamping to ${S}×${w}`)}(a.x!==S||a.y!==w)&&(this.log(`📐 [Display ${i}] Resizing display from ${a.x}×${a.y} to ${S}×${w} (available: ${p.width}×${p.height}px, cell: ${c}×${d}px)`),n.setSize(new Yt(S,w)))}let f=n.getSize();(l!==f.x||u!==f.y)&&(this.log(`📐 [Display ${i}] Resizing renderer from ${l}×${u} to ${f.x}×${f.y}`),o.resize(f.x,f.y))}}super.render()}onFontChanged(e,t){let n=t??this.primaryDisplayId,i=this.postProcessOverlays.get(n)??this.postProcessOverlay;i&&"syncWithRenderer"in i&&"getCellWidth"in e&&"getCellHeight"in e&&"getCurrentScale"in e&&"getGridSize"in e&&(i.syncWithRenderer(e),this.log(`✓ PostProcessOverlay synced with renderer dimensions (display ${n})`))}getAudioManager(){return this.audioManager}getLayerTrafficStats(){var e;return((e=this.networkSync)==null?void 0:e.getLayerTrafficStats())??{}}getMiscTrafficStats(){var e,t;return((t=(e=this.networkSync)==null?void 0:e.getMiscTrafficStats)==null?void 0:t.call(e))??{}}getDisplayTrafficStats(){var e,t;return((t=(e=this.networkSync)==null?void 0:e.getDisplayTrafficStats)==null?void 0:t.call(e))??{}}getAudioContext(){var e;return((e=this.audioManager)==null?void 0:e.getContext())??null}getPostProcessOverlay(){return this.postProcessOverlay}applyAmbientEffectConfig(e,t){var i;let n=(i=this.rendererManagers.get(e))==null?void 0:i.getRenderer();n&&"setAmbientEffect"in n&&(t.enabled?n.setAmbientEffect({blur:t.blur,scale:t.scale}):n.setAmbientEffect(!1),this.log(`[Display ${e}] Ambient effect ${t.enabled?"enabled":"disabled"}`))}applyPostProcessOrders(e){var t;for(let n of e){let i=n.displayId??this.primaryDisplayId,s=this.postProcessOverlays.get(i)??this.postProcessOverlay,o=(t=this.rendererManagers.get(i))==null?void 0:t.getRenderer();switch(n.type){case Xr.SetConfig:{if(!s){console.warn(`[ClientRuntime] No PostProcessOverlay for display ${i}`);break}let a={};n.scanlines&&(a.scanlines={enabled:n.scanlines.enabled,opacity:n.scanlines.opacity,pattern:this.patternFromType(n.scanlines.pattern),color:{r:n.scanlines.colorR,g:n.scanlines.colorG,b:n.scanlines.colorB}}),n.ambientEffect&&(a.ambientEffect={enabled:n.ambientEffect.enabled,blur:n.ambientEffect.blur,scale:n.ambientEffect.scale}),s.setConfig(Object.keys(a).length>0?a:null),a.ambientEffect&&o&&this.applyAmbientEffectConfig(i,a.ambientEffect),this.log(`[Display ${i}] SetConfig applied`);break}case Xr.SetScanlines:{if(!s){console.warn(`[ClientRuntime] No PostProcessOverlay for display ${i}`);break}s.setScanlines({enabled:n.enabled,opacity:n.opacity,pattern:this.patternFromType(n.pattern),color:{r:n.colorR,g:n.colorG,b:n.colorB}}),this.log(`[Display ${i}] Scanlines ${n.enabled?"enabled":"disabled"}`);break}case Xr.SetAmbientEffect:{this.applyAmbientEffectConfig(i,{enabled:n.enabled,blur:n.blur,scale:n.scale}),this.log(`[Display ${i}] Ambient effect ${n.enabled?"enabled":"disabled"}`);break}case Xr.SetScalingMode:{this.applyScalingMode(i,n.mode);break}case Xr.SetGrid:{this.applyGridConfig(i,n);break}case Xr.SwitchPalette:{this.applySwitchPalette(i,n);break}case Xr.SetCellSize:{this.applyCellSize(i,n.cellWidth,n.cellHeight);break}}}}applyScalingMode(e,t){var i;let n=(i=this.rendererManagers.get(e))==null?void 0:i.getRenderer();if(n&&"setScalingMode"in n){let s=If(t);n.setScalingMode(s),this.log(`[Display ${e}] Scaling mode set to ${s}`)}}applyGridConfig(e,t){var i;let n=(i=this.rendererManagers.get(e))==null?void 0:i.getRenderer();if(n&&"setGrid"in n){let s=t.colorA/255;n.setGrid({enabled:t.enabled,color:`rgba(${t.colorR},${t.colorG},${t.colorB},${s})`,lineWidth:t.lineWidth}),this.log(`[Display ${e}] Grid ${t.enabled?"enabled":"disabled"}`)}}applySwitchPalette(e,t){var o;let n=this.core.getPaletteFromSlot(t.slotId);if(!n){this.pendingPaletteSlotByDisplay.set(e,t.slotId),console.warn(`[ClientRuntime] Palette slot ${t.slotId} not found (display ${e}); will retry when available`);return}let i=[];for(let a=0;a<256;a++){let l=n.get(a);l?i.push({r:l.r,g:l.g,b:l.b,a:l.a}):i.push({r:0,g:0,b:0,a:0})}let s=(o=this.rendererManagers.get(e))==null?void 0:o.getRenderer();s&&"setPalette"in s&&(s.setPalette(i),this.log(`[Display ${e}] Switched to palette slot ${t.slotId}`)),this.pendingPaletteSlotByDisplay.get(e)===t.slotId&&this.pendingPaletteSlotByDisplay.delete(e)}retryPendingPaletteSelections(){var e;if(this.pendingPaletteSlotByDisplay.size!==0)for(let[t,n]of this.pendingPaletteSlotByDisplay.entries()){let i=this.core.getPaletteFromSlot(n);if(!i)continue;let s=[];for(let a=0;a<256;a++){let l=i.get(a);l?s.push({r:l.r,g:l.g,b:l.b,a:l.a}):s.push({r:0,g:0,b:0,a:0})}let o=(e=this.rendererManagers.get(t))==null?void 0:e.getRenderer();o&&"setPalette"in o&&(o.setPalette(s),this.log(`[Display ${t}] Applied pending palette slot ${n}`),this.pendingPaletteSlotByDisplay.delete(t))}}applyCellSize(e,t,n){var s;let i=(s=this.rendererManagers.get(e))==null?void 0:s.getRenderer();i&&"setCellSize"in i&&(i.setCellSize(t,n),this.log(`[Display ${e}] Cell size set to ${t}×${n}px`))}patternFromType(e){switch(e){case 0:return"horizontal";case 1:return"vertical";case 2:return"grid";default:return"horizontal"}}dispatchLocalBridgeMessages(e){for(let t of e){let{channel:n,data:i}=t,s=this.localBridgeHandlers.get(n);if(s)for(let o of s)try{o(i)}catch(a){console.error(`[ClientRuntime] Bridge handler error on '${n}':`,a)}for(let o of this.localBridgeWildcardHandlers)try{o(n,i)}catch(a){console.error("[ClientRuntime] Bridge wildcard handler error:",a)}this.log(`Bridge message dispatched on channel '${n}'`)}}sendBridge(e,t){var n;if(this.mode!=="standalone"&&this.networkSync)this.networkSync.sendBridge(e,t);else if(this.mode==="standalone"){let i=this.core.getUser(this.userId);i&&((n=this.options.application)!=null&&n.onBridgeMessage)&&(this.options.application.onBridgeMessage(this,this.core,i,e,t),this.log(`Bridge message sent to application on channel '${e}'`))}}onBridge(e,t){this.mode!=="standalone"&&this.networkSync?this.networkSync.onBridge(e,t):this.mode==="standalone"&&(e==="*"?this.localBridgeWildcardHandlers.add(t):(this.localBridgeHandlers.has(e)||this.localBridgeHandlers.set(e,new Set),this.localBridgeHandlers.get(e).add(t)),this.log(`Bridge handler registered for channel '${e}'`))}offBridge(e,t){var n;this.mode!=="standalone"&&this.networkSync?this.networkSync.offBridge(e,t):this.mode==="standalone"&&(e==="*"?this.localBridgeWildcardHandlers.delete(t):(n=this.localBridgeHandlers.get(e))==null||n.delete(t))}removeAllBridgeHandlers(e){this.mode!=="standalone"&&this.networkSync?this.networkSync.removeAllBridgeHandlers(e):this.mode==="standalone"&&(e===void 0?(this.localBridgeHandlers.clear(),this.localBridgeWildcardHandlers.clear()):e==="*"?this.localBridgeWildcardHandlers.clear():this.localBridgeHandlers.delete(e))}log(e){}async onDestroy(){this.log("Destroying ClientRuntime resources..."),this.networkSync&&(this.networkSync.disconnect(),this.networkSync=null),this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.input&&(this.input.destroy(),this.input=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null),this.mobileVibration=null,this.autoplayOverlay=null,this.postProcessOverlays.clear(),this.postProcessOverlay=null,this.log("ClientRuntime resources destroyed")}};Ar(Nw,"ClientRuntime");var TE=Nw,RE=class{constructor(e={}){var t,n,i;se(this,"input"),se(this,"mobileVibration"),this.input=new hw({enableKeyboardMouse:!0,enableGamepad:!0,enableMobile:!0,targetElement:window,mobileTargetElement:void 0,debug:e.debug,keyboardConfig:{preventDefault:e.captureInput??!1,stopPropagation:e.captureInput??!1},mouseConfig:{preventDefault:e.captureInput??!1,stopPropagation:e.captureInput??!1},mobileConfig:{preventDefault:((t=e.mobileInputConfig)==null?void 0:t.preventDefault)??!1,passive:((n=e.mobileInputConfig)==null?void 0:n.passive)??!0,maxTouches:((i=e.mobileInputConfig)==null?void 0:i.maxTouches)??10}}),this.mobileVibration=new Uf({debug:e.debug})}setMobileTarget(e){this.input.setMobileTarget(e)}start(){this.input.start()}stop(){this.input.stop()}destroy(){this.input.destroy()}getRouter(){return this.input}getGamepad(){return this.input.getGamepad()}getMobileVibration(){return this.mobileVibration}collectAndApply(e,t,n,i,s){var c,d;if(t){let h=Er.collectMousePosition(this.input,t,n,i,s);e.setMousePosition(h.x,h.y,h.over),e.updateMacroMouse(h.x,h.y,h.isLeftDown),Er.collectTouchPositions(this.input,t,n,i,10,s).forEach(f=>{e.setTouchPosition(f.id,f.x,f.y,f.over)})}let o=Er.collectTextInputs(this.input);o.length>0&&e.setTextInputs(o);let a=e.getInputBindingRegistry(),l=a.getAllAxes(),u=a.getAllButtons();if(l.length>0||u.length>0){let h=Er.collectAxisSources(l,this.input),f=Er.collectButtonSourcesWithTransitions(u,this.input);l.forEach(p=>{let m=a.evaluateAxis(p.bindingId,h);e.setAxis(p.name,m)}),u.forEach(p=>{let m=new Map,S=new Map,w=new Map;for(let[x,I]of f)m.set(x,I.pressed),S.set(x,I.justPressed),w.set(x,I.justReleased);let g=a.evaluateButton(p.bindingId,m),y=a.evaluateButton(p.bindingId,S),C=a.evaluateButton(p.bindingId,w);e.setButton(p.name,g),e.setButton(`${p.name}_justPressed`,y),e.setButton(`${p.name}_justReleased`,C)})}(d=(c=this.input).poll)==null||d.call(c)}processVibrationCommands(e){e.hasMobileVibrationCommands()&&e.applyMobileVibrationCommands(e.flushMobileVibrationCommands()),e.hasGamepadVibrationCommands()&&e.applyGamepadVibrationCommands(e.flushGamepadVibrationCommands())}};Ar(RE,"InputFeature");var PE=class{constructor(e={}){se(this,"audioManager"),se(this,"debug"),this.debug=e.debug??!1,this.audioManager=new zw({debug:e.debug})}initialize(){this.audioManager.initialize()}playStartSound(){this.audioManager.playStartSound()}stopAll(){this.audioManager.stopAll()}destroy(){this.audioManager.destroy()}getManager(){return this.audioManager}getContext(){return this.audioManager.getContext()}injectIntoUser(e){e.setAudioProcessor(this.audioManager)}processAudioCommands(e){e.hasAudioConfigCommands()&&e.applyAudioConfigCommands(e.flushAudioConfigCommands()),e.hasSoundCommands()&&e.applyAudioCommands(e.flushSoundCommands())}async loadSoundsFromRegistry(e){let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load sounds: SoundBank not initialized");return}let n=e.getSoundRegistry().getAll();if(n.length===0){this.log("No sounds to load from registry");return}this.log(`Loading ${n.length} sounds from Core registry...`);for(let i of n)try{i.loadType==="file"&&i.data?(await t.loadFromData(i.soundId,i.name,i.data),this.log(`Loaded sound: ${i.name} (${i.data.length} bytes)`)):i.loadType==="external"&&i.url&&(await t.loadFromUrl(i.soundId,i.name,i.url),this.log(`Loaded external sound: ${i.name} from ${i.url}`))}catch(s){console.error(`[AudioFeature] Failed to load sound "${i.name}":`,s)}this.log(`${t.size} sounds loaded`)}log(e){this.debug&&console.warn(`[AudioFeature] ${e}`)}};Ar(PE,"AudioFeature");var BE=class{constructor(e,t={}){se(this,"overlay"),se(this,"orderCollector"),se(this,"debug"),this.debug=t.debug??!1,this.overlay=new Jv(e),this.orderCollector=new Mf}destroy(){this.overlay.destroy()}getOverlay(){return this.overlay}syncWithRenderer(e){this.overlay.syncWithRenderer(e),this.log("Overlay synced with renderer dimensions")}processCommands(e,t){if(!e.hasPostProcessCommands())return;let n=e.flushPostProcessCommands(),i=this.orderCollector.convertCommands(n);this.applyOrders(i,t)}applyOrders(e,t){for(let n of e){let i=n.displayId;switch(n.type){case Xr.SetConfig:{let s={};n.scanlines&&(s.scanlines={enabled:n.scanlines.enabled,opacity:n.scanlines.opacity,pattern:this.patternFromType(n.scanlines.pattern),color:{r:n.scanlines.colorR,g:n.scanlines.colorG,b:n.scanlines.colorB}}),n.ambientEffect&&(s.ambientEffect={enabled:n.ambientEffect.enabled,blur:n.ambientEffect.blur,scale:n.ambientEffect.scale}),this.overlay.setConfig(Object.keys(s).length>0?s:null),s.ambientEffect&&this.applyAmbientEffect(t,s.ambientEffect),this.log(`[Display ${i}] SetConfig applied`);break}case Xr.SetScanlines:{this.overlay.setScanlines({enabled:n.enabled,opacity:n.opacity,pattern:this.patternFromType(n.pattern),color:{r:n.colorR,g:n.colorG,b:n.colorB}}),this.log(`[Display ${i}] Scanlines ${n.enabled?"enabled":"disabled"}`);break}case Xr.SetAmbientEffect:{this.applyAmbientEffect(t,{enabled:n.enabled,blur:n.blur,scale:n.scale}),this.log(`[Display ${i}] Ambient effect ${n.enabled?"enabled":"disabled"}`);break}case Xr.SetScalingMode:{this.applyScalingMode(t,i,n.mode);break}case Xr.SetGrid:{this.applyGridConfig(t,i,n);break}}}}applyAmbientEffect(e,t){e&&"setAmbientEffect"in e&&(t.enabled?e.setAmbientEffect({blur:t.blur,scale:t.scale}):e.setAmbientEffect(!1))}applyScalingMode(e,t,n){if(e&&"setScalingMode"in e){let i=If(n);e.setScalingMode(i),this.log(`[Display ${t}] Scaling mode set to ${i}`)}}applyGridConfig(e,t,n){if(e&&"setGrid"in e){let i=n.colorA/255;e.setGrid({enabled:n.enabled,color:`rgba(${n.colorR},${n.colorG},${n.colorB},${i})`,lineWidth:n.lineWidth}),this.log(`[Display ${t}] Grid ${n.enabled?"enabled":"disabled"}`)}}patternFromType(e){switch(e){case 0:return"horizontal";case 1:return"vertical";case 2:return"grid";default:return"horizontal"}}log(e){this.debug&&console.warn(`[PostProcessFeature] ${e}`)}};Ar(BE,"PostProcessFeature");const zE={},dm=r=>{let e;const t=new Set,n=(c,d)=>{const h=typeof c=="function"?c(e):c;if(!Object.is(h,e)){const f=e;e=d??(typeof h!="object"||h===null)?h:Object.assign({},e,h),t.forEach(p=>p(e,f))}},i=()=>e,l={setState:n,getState:i,getInitialState:()=>u,subscribe:c=>(t.add(c),()=>t.delete(c)),destroy:()=>{(zE?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),t.clear()}},u=e=r(n,i,l);return l},OE=r=>r?dm(r):dm;var Vw={exports:{}},Hw={},jw={exports:{}},Yw={};/**
|
|
258
258
|
* @license React
|
|
259
259
|
* use-sync-external-store-shim.production.js
|
|
260
260
|
*
|
|
@@ -262,7 +262,7 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
262
262
|
*
|
|
263
263
|
* This source code is licensed under the MIT license found in the
|
|
264
264
|
* LICENSE file in the root directory of this source tree.
|
|
265
|
-
*/var ao=N;function
|
|
265
|
+
*/var ao=N;function DE(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var FE=typeof Object.is=="function"?Object.is:DE,LE=ao.useState,_E=ao.useEffect,$E=ao.useLayoutEffect,NE=ao.useDebugValue;function VE(r,e){var t=e(),n=LE({inst:{value:t,getSnapshot:e}}),i=n[0].inst,s=n[1];return $E(function(){i.value=t,i.getSnapshot=e,jc(i)&&s({inst:i})},[r,t,e]),_E(function(){return jc(i)&&s({inst:i}),r(function(){jc(i)&&s({inst:i})})},[r]),NE(t),t}function jc(r){var e=r.getSnapshot;r=r.value;try{var t=e();return!FE(r,t)}catch{return!0}}function HE(r,e){return e()}var jE=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?HE:VE;Yw.useSyncExternalStore=ao.useSyncExternalStore!==void 0?ao.useSyncExternalStore:jE;jw.exports=Yw;var YE=jw.exports;/**
|
|
266
266
|
* @license React
|
|
267
267
|
* use-sync-external-store-shim/with-selector.production.js
|
|
268
268
|
*
|
|
@@ -270,6 +270,6 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
270
270
|
*
|
|
271
271
|
* This source code is licensed under the MIT license found in the
|
|
272
272
|
* LICENSE file in the root directory of this source tree.
|
|
273
|
-
*/var zu=N,WE=YE;function GE(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var XE=typeof Object.is=="function"?Object.is:GE,KE=WE.useSyncExternalStore,ZE=zu.useRef,qE=zu.useEffect,QE=zu.useMemo,JE=zu.useDebugValue;Hw.useSyncExternalStoreWithSelector=function(r,e,t,n,i){var s=ZE(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=QE(function(){function l(f){if(!u){if(u=!0,c=f,f=n(f),i!==void 0&&o.hasValue){var p=o.value;if(i(p,f))return d=p}return d=f}if(p=d,XE(c,f))return p;var m=n(f);return i!==void 0&&i(p,m)?(c=f,p):(c=f,d=m)}var u=!1,c,d,h=t===void 0?null:t;return[function(){return l(e())},h===null?void 0:function(){return l(h())}]},[e,t,n,i]);var a=KE(r,s[0],s[1]);return qE(function(){o.hasValue=!0,o.value=a},[a]),JE(a),a};Vw.exports=Hw;var eM=Vw.exports;const tM=uy(eM),Ww={},{useDebugValue:rM}=Cy,{useSyncExternalStoreWithSelector:nM}=tM;let hm=!1;const iM=r=>r;function sM(r,e=iM,t){(Ww?"production":void 0)!=="production"&&t&&!hm&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),hm=!0);const n=nM(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return rM(n),n}const fm=r=>{(Ww?"production":void 0)!=="production"&&typeof r!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof r=="function"?DE(r):r,t=(n,i)=>sM(e,n,i);return Object.assign(t,e),t},oM=r=>r?fm(r):fm,Ys=oM(r=>({connected:!1,lastSnapshot:void 0,setConnected:e=>r({connected:e}),setSnapshot:e=>r({lastSnapshot:e})}));class aM{constructor(){Wi(this,"runtime",null);Wi(this,"layerTraffic",{});Wi(this,"miscTraffic",{});Wi(this,"displayTraffic",{});Wi(this,"visibleLayerIds",null);Wi(this,"visibleLayerIdsDisplay255",null)}setMuted(e){var n;const t=(n=this.runtime)==null?void 0:n.getAudioManager();t&&t.setMasterVolume(e?0:1)}setVisibleLayers(e){var i;this.visibleLayerIds=e&&e.length>0?[...e]:null;const t=(i=this.runtime)==null?void 0:i.getRendererManager(0);if(!t)return;if(this.visibleLayerIds==null){t.setLayerFilter(null);return}const n=new Set(this.visibleLayerIds);t.setLayerFilter(s=>n.has(s.getId()))}setVisibleLayersDisplay255(e){var i;this.visibleLayerIdsDisplay255=e&&e.length>0?[...e]:null;const t=(i=this.runtime)==null?void 0:i.getRendererManager(255);if(!t)return;if(this.visibleLayerIdsDisplay255==null){t.setLayerFilter(null);return}const n=new Set(this.visibleLayerIdsDisplay255);t.setLayerFilter(s=>n.has(s.getId()))}sendDisplayTransform(e){var t;(t=this.runtime)==null||t.sendBridge("__debug_display_255",{origin:{x:e.x,y:e.y},size:{x:e.width,y:e.height}})}async start(e){Ys.getState().setConnected(!1),this.runtime&&this.destroy();const t={mode:"socketio",socketio:{url:e.serverUrl},container:e.container,displayContainers:e.displayContainers,renderer:e.renderer??Df.TerminalGL,inputEnabled:e.inputEnabled??!0,captureInput:e.captureInput??!0,debug:!1,autoplay:!1};try{if(this.runtime=new TE(t),this.visibleLayerIds&&this.visibleLayerIds.length>0){const n=new Set(this.visibleLayerIds);this.runtime.getRendererManager().setLayerFilter(i=>n.has(i.getId()))}if(this.visibleLayerIdsDisplay255&&this.visibleLayerIdsDisplay255.length>0){const n=new Set(this.visibleLayerIdsDisplay255);this.runtime.getRendererManager(255).setLayerFilter(i=>n.has(i.getId()))}this.runtime.onBridge("__debug_meta",n=>{var i,s,o,a;try{let l=n;if(this.runtime&&n&&typeof n=="object"){try{this.layerTraffic=this.runtime.getLayerTrafficStats()}catch{this.layerTraffic={}}try{this.miscTraffic=((s=(i=this.runtime).getMiscTrafficStats)==null?void 0:s.call(i))??{}}catch{this.miscTraffic={}}try{this.displayTraffic=((a=(o=this.runtime).getDisplayTrafficStats)==null?void 0:a.call(o))??{}}catch{this.displayTraffic={}}const u=n;if(u.users&&Array.isArray(u.users))for(const c of u.users)c.layers&&Array.isArray(c.layers)&&(c.layers=c.layers.map(d=>{const h=this.layerTraffic[d.id];return h?{...d,bytesTotal:h.total,bytesPerSec1s:h.bytesPerSec1s}:d})),c.miscTraffic=this.miscTraffic,c.displayTraffic=this.displayTraffic;l=u}Ys.getState().setConnected(!0),Ys.getState().setSnapshot(l)}catch{}}),await this.runtime.start(),this.runtime.sendBridge("__debug_auth",{})}catch(n){throw Ys.getState().setConnected(!1),n}}destroy(){var e,t,n,i;if(this.runtime){try{(t=(e=this.runtime.getAudioManager())==null?void 0:e.stopAll)==null||t.call(e)}catch{}try{(i=(n=this.runtime).destroy)==null||i.call(n)}catch{}this.runtime=null}}getAssetsSnapshot(){var u;const e=this.runtime;if(!e)return{audio:[],atlases:[],palettes:[]};const t=e.getAudioManager(),n=(u=t==null?void 0:t.getSoundBank)==null?void 0:u.call(t),i=n?n.getAll().map(c=>({id:c.soundId,name:c.name,duration:c.duration,source:c.metadata.source,originalSize:c.metadata.originalSize,originalUrl:c.metadata.originalUrl})):[],s=e.getCore(),o=s.getImageFontRegistry(),a=o.getAllFonts().map(c=>({id:c.getFontId(),name:o.getFontName(c.getFontId())??`Font ${c.getFontId()}`,glyphSize:`${c.getGlyphWidth()}×${c.getGlyphHeight()}`,cellSize:`${c.getCellWidth()}×${c.getCellHeight()}`,atlasBlocks:c.getAtlasBlocks(),maxCharCode:c.getMaxCharCode()}));a.length===0&&a.push({id:0,name:"Default CP437 (builtin)",glyphSize:"8×8",cellSize:"8×8",atlasBlocks:1,maxCharCode:255});const l=[];for(let c=0;c<256;c++){if(!s.hasPaletteSlot(c))continue;const d=s.getPaletteFromSlot(c);l.push({slotId:c,colors:(d==null?void 0:d.size)??0})}return{audio:i,atlases:a,palettes:l}}}function lM({connected:r,muted:e,rendererPlacement:t,centerTab:n,frameRect:i,rendererHeaderHeight:s,rendererContentSize:o,rendererContainerRef:a,onTogglePlacement:l,onToggleMuted:u,onStartDrag:c,onStartResize:d}){const h=t==="float";return k.jsxs("div",{style:{position:"fixed",left:i.left,top:i.top,width:i.width,height:i.height,zIndex:h?1e3:10,background:"#1a1a1a",border:"1px solid #3c3c3c",boxShadow:h?"0 8px 24px rgba(0,0,0,0.45)":"none",userSelect:"none",pointerEvents:h||n==="renderer"?"auto":"none",display:h||n==="renderer"?"block":"none"},children:[k.jsxs("div",{style:{height:s,background:"#2d2d2d",borderBottom:"1px solid #3c3c3c",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px",cursor:h?"move":"default",fontSize:12,color:"#cccccc"},onMouseDown:f=>{h&&c(f.clientX,f.clientY)},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[k.jsx("div",{style:{width:8,height:8,borderRadius:4,background:r?"#4fc1ff":"#a0a0a0"}}),k.jsx("div",{children:"UTSP Client"}),k.jsxs("div",{style:{color:"#888888",fontSize:11},children:[o.width,"×",o.height," px"]})]}),k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,cursor:"default"},onMouseDown:f=>f.stopPropagation(),children:[k.jsx("button",{onClick:f=>{f.stopPropagation(),l()},style:{height:24,padding:"0 8px",border:"1px solid #3c3c3c",background:"#3c3c3c",color:"#ffffff",cursor:"pointer",fontSize:12},title:h?"Embed into layout":"Float window",children:h?"Embed":"Float"}),k.jsx("button",{onClick:f=>{f.stopPropagation(),u()},style:{width:28,height:24,border:"1px solid #3c3c3c",background:e?"#3c3c3c":"#0e639c",color:"#ffffff",cursor:"pointer",fontSize:12,display:"flex",alignItems:"center",justifyContent:"center",padding:0},title:e?"Unmute audio":"Mute audio",children:k.jsxs("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[k.jsx("path",{d:"M4 9v6h4l5 4V5L8 9H4z"}),!e&&k.jsx("path",{d:"M16 9a5 5 0 0 1 0 6"}),!e&&k.jsx("path",{d:"M18 5a9 9 0 0 1 0 14"}),e&&k.jsx("line",{x1:"17",y1:"9",x2:"21",y2:"13"}),e&&k.jsx("line",{x1:"21",y1:"9",x2:"17",y2:"13"})]})})]})]}),k.jsx("div",{ref:a,style:{position:"absolute",top:s,left:0,right:0,bottom:0,background:"#0d0d0d",overflow:"hidden",opacity:1,pointerEvents:"auto",outline:"1px solid #3c3c3c"},tabIndex:0,onMouseDown:f=>{var p;f.stopPropagation(),(p=a.current)==null||p.focus()}}),h&&k.jsx("div",{onMouseDown:f=>{f.stopPropagation(),d(f.clientX,f.clientY)},style:{position:"absolute",width:14,height:14,right:2,bottom:2,cursor:"nwse-resize",background:"#2d2d2d",border:"1px solid #3c3c3c",borderRadius:2}})]})}function Kr(r){if(r==null||Number.isNaN(r))return"—";const e=["B","KB","MB","GB"];let t=r,n=0;for(;t>=1024&&n<e.length-1;)t/=1024,n++;return`${t.toFixed(t>=10?0:1)} ${e[n]}`}function uM(r){return`${r.toFixed(2)} s`}const cM={muted:{background:"#1a1a1a",border:"#2f2f2f",color:"#cfcfcf"},info:{background:"#1a2531",border:"#2f4f6b",color:"#8dc8ff"},success:{background:"#182420",border:"#2b4d37",color:"#7dd19c"},warning:{background:"#292114",border:"#514021",color:"#eac172"}};function Lo({label:r,tone:e="muted"}){const t=cM[e];return k.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"1px 6px",borderRadius:6,fontSize:10,fontWeight:600,letterSpacing:"0.05px",background:t.background,border:`1px solid ${t.border}`,color:t.color},children:r})}function pm({children:r}){return k.jsx("div",{style:{border:"1px solid #2a2a2a",borderRadius:6,background:"#161616"},children:r})}function Xn({label:r,value:e,divider:t}){return k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"6px 8px",fontSize:11,color:"#d6d6d6",borderBottom:t?"1px solid #222":"none"},children:[k.jsx("span",{style:{color:"#9a9a9a",letterSpacing:"0.05px"},children:r}),k.jsx("span",{style:{fontWeight:600,textAlign:"right"},children:e})]})}function dM({detailTarget:r}){return k.jsxs("div",{style:{background:"transparent",padding:0,minHeight:0,display:"flex",flexDirection:"column"},children:[k.jsx("div",{style:{padding:"8px 12px",borderBottom:"1px solid #3c3c3c"},children:k.jsx("div",{style:{fontSize:11,color:"#bbbbbb",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Properties"})}),k.jsxs("div",{style:{padding:"8px 12px",flex:1,overflowY:"auto"},children:[!r&&k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Hover or select an item"}),(r==null?void 0:r.type)==="display"&&k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:6,padding:"2px 0"},children:[k.jsxs("div",{style:{color:"#e7f3ff",fontWeight:600},children:["Display ",r.item.id]}),k.jsx(Lo,{label:"Active",tone:"info"})]}),k.jsxs(pm,{children:[k.jsx(Xn,{label:"Origin",value:`(${r.item.origin.x}, ${r.item.origin.y})`,divider:!0}),k.jsx(Xn,{label:"Size",value:`${r.item.size.x} × ${r.item.size.y}`})]})]}),(r==null?void 0:r.type)==="layer"&&k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:6,padding:"2px 0"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[k.jsx("div",{style:{color:"#e7f3ff",fontWeight:700},children:r.item.name??"Layer"}),k.jsx(Lo,{label:`#${r.item.id}`,tone:"info"})]}),k.jsx(Lo,{label:`z ${r.item.z}`,tone:"muted"})]}),k.jsxs(pm,{children:[k.jsx(Xn,{label:"Mode",value:r.item.charCodeMode,divider:!0}),k.jsx(Xn,{label:"Orders",value:r.item.ordersCount,divider:!0}),k.jsx(Xn,{label:"Size",value:`${r.item.width} × ${r.item.height}`,divider:!0}),k.jsx(Xn,{label:"Origin",value:`(${r.item.origin.x}, ${r.item.origin.y})`,divider:!0}),k.jsx(Xn,{label:"Channel",value:r.item.mustBeReliable?k.jsx(Lo,{label:"Reliable",tone:"success"}):k.jsx(Lo,{label:"Volatile",tone:"muted"}),divider:!0}),r.item.bytesTotal!==void 0&&k.jsxs(k.Fragment,{children:[k.jsx(Xn,{label:"Total",value:Kr(r.item.bytesTotal),divider:!0}),k.jsx(Xn,{label:"Throughput",value:`${Kr(r.item.bytesPerSec1s)} /s`})]})]})]})]})]})}function gm({isSelected:r,onClick:e,children:t}){return k.jsx("div",{onClick:e,style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"2px 12px",cursor:"pointer",fontSize:12,background:r?"#094771":"transparent",color:r?"#ffffff":"#cccccc",userSelect:"none"},children:t})}function hM(r){return r<1e3?`${r} B`:r<1e6?`${(r/1e3).toFixed(2)} KB`:`${(r/1e6).toFixed(2)} MB`}const Ms={id:"1fr",net:"90px",gap:4};function fM({displays:r,layers:e,selectedDisplayId:t,selectedLayerIds:n,onSelectDisplay:i,onSelectLayer:s}){const o=new Set(n),[a,l]=N.useState("id"),[u,c]=N.useState("asc"),d=N.useMemo(()=>{const f=[...e];return f.sort((p,m)=>{const S=a==="id"?p.id:p.bytesTotal??0,w=a==="id"?m.id:m.bytesTotal??0,g=S===w?0:S<w?-1:1;return u==="asc"?g:-g}),f},[e,u,a]),h=f=>{l(p=>p===f?(c(m=>m==="asc"?"desc":"asc"),p):(c("asc"),f))};return k.jsxs("div",{style:{padding:"4px 0",overflowY:"auto",flex:1,display:"flex",flexDirection:"column",gap:0,userSelect:"none"},children:[r.length===0&&e.length===0&&k.jsx("div",{style:{fontSize:12,color:"#858585",padding:"4px 12px"},children:"No items"}),r.length>0&&k.jsxs(k.Fragment,{children:[k.jsx("div",{style:{fontSize:10,color:"#858585",padding:"6px 12px 2px",textTransform:"uppercase"},children:"Displays"}),r.map(f=>k.jsxs(gm,{isSelected:t===f.id,onClick:()=>i(f.id),children:[k.jsxs("span",{children:["Display ",f.id,f.id===255?" (debug)":""]}),k.jsxs("span",{style:{color:"#858585",fontSize:11},children:[f.size.x,"×",f.size.y]})]},`display-${f.id}`))]}),e.length>0&&k.jsxs(k.Fragment,{children:[k.jsx("div",{style:{fontSize:10,color:"#858585",padding:"8px 12px 4px",textTransform:"uppercase"},children:"Layers"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:`${Ms.id} ${Ms.net}`,alignItems:"center",columnGap:Ms.gap,padding:"0 12px 4px",fontSize:11,color:"#858585",userSelect:"none"},children:[k.jsxs("button",{type:"button",onClick:()=>h("id"),style:{all:"unset",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4,color:"#858585",justifySelf:"start",whiteSpace:"nowrap"},children:["ID",k.jsx("span",{style:{fontSize:10,opacity:a==="id"?1:.3},children:a==="id"?u==="asc"?"▲":"▼":"▲"})]}),k.jsxs("button",{type:"button",onClick:()=>h("net"),style:{all:"unset",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4,color:"#858585",justifySelf:"end",whiteSpace:"nowrap"},children:["Network",k.jsx("span",{style:{fontSize:10,opacity:a==="net"?1:.3},children:a==="net"?u==="asc"?"▲":"▼":"▲"})]})]}),d.map(f=>{const p=o.has(f.id),m=f.name?`${f.id}:${f.name}`:String(f.id);return k.jsx(gm,{isSelected:p,onClick:S=>s(f.id,S),children:k.jsxs("span",{style:{display:"grid",gridTemplateColumns:`${Ms.id} ${Ms.net}`,alignItems:"center",columnGap:Ms.gap,width:"100%"},children:[k.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:k.jsx("span",{style:{color:"inherit"},children:m})}),k.jsx("span",{style:{color:"#858585",fontSize:11,textAlign:"right",whiteSpace:"nowrap"},children:f.bytesTotal!==void 0&&hM(f.bytesTotal)})]})},`layer-${f.id}-${p}`)})]})]})}function pM({primaryUser:r,selectedDisplayId:e,selectedLayerIds:t,onSelectDisplay:n,onSelectLayer:i}){var s;return k.jsxs("div",{style:{borderRight:"1px solid #3c3c3c",background:"#252526",display:"flex",flexDirection:"column",minHeight:0},children:[k.jsx("div",{style:{padding:"8px 12px",borderBottom:"1px solid #3c3c3c"},children:k.jsx("div",{style:{fontSize:11,color:"#bbbbbb",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Explorer"})}),k.jsxs("div",{style:{padding:"4px 0",overflowY:"auto",flex:1,display:"flex",flexDirection:"column",gap:0,userSelect:"none"},children:[!r&&k.jsx("div",{style:{fontSize:12,color:"#858585",padding:"4px 12px"},children:"No items"}),r&&k.jsx(fM,{displays:(s=r.displays)==null?void 0:s.filter(o=>o.id!==255),layers:r.layers,selectedDisplayId:e,selectedLayerIds:t,onSelectDisplay:n,onSelectLayer:i})]})]})}function gM({connected:r,serverUrl:e,onServerUrlChange:t,onReconnect:n}){return k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",height:34,padding:"0 10px",borderBottom:"1px solid #3c3c3c",background:"#252526"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[k.jsx("img",{src:"/logo_debugger.png",alt:"UTSP logo",style:{width:18,height:18,objectFit:"contain"}}),k.jsx("div",{style:{fontSize:13,color:"#cccccc",fontWeight:600},children:"UTSP Visual Debugger"})]}),k.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,color:r?"#9adcff":"#bbbbbb"},children:[k.jsx("span",{style:{width:8,height:8,borderRadius:4,background:r?"#4fc1ff":"#a0a0a0",display:"inline-block"}}),k.jsx("span",{children:r?"Connected":"Disconnected"})]}),k.jsx("input",{value:e,onChange:i=>t(i.target.value),style:{width:220,padding:"4px 8px",borderRadius:0,border:"1px solid #3c3c3c",background:"#3c3c3c",color:"#cccccc",fontSize:12},placeholder:"http://localhost:3000"}),k.jsx("button",{onClick:n,style:{padding:"4px 10px",borderRadius:0,border:"1px solid #0e639c",background:"#0e639c",color:"#ffffff",fontWeight:500,cursor:"pointer",fontSize:12},children:"Reconnect"})]})]})}function Yc({title:r,headers:e,rows:t,emptyLabel:n}){const i=t.length>0;return k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{fontSize:12,color:"#bbbbbb"},children:r}),k.jsxs("div",{style:{border:"1px solid #3c3c3c",borderRadius:2,overflow:"hidden",background:"#1e1e1e"},children:[k.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.length}, minmax(0, 1fr))`,gap:0,background:"#252526",borderBottom:"1px solid #3c3c3c",fontSize:11,color:"#aaaaaa"},children:e.map(s=>k.jsx("div",{style:{padding:"6px 8px",whiteSpace:"nowrap"},children:s},s))}),!i&&k.jsx("div",{style:{padding:"8px 10px",color:"#858585",fontSize:12},children:n}),i&&k.jsx("div",{children:t.map((s,o)=>k.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.length}, minmax(0, 1fr))`,gap:0,borderTop:o===0?"none":"1px solid #2e2e2e",fontSize:12,color:"#cccccc"},children:s.map((a,l)=>k.jsx("div",{style:{padding:"6px 8px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:a,children:a},l))},`${r}-${o}`))})]})]})}function mM({assetsSnapshot:r}){return k.jsxs("div",{style:{height:"100%",overflow:"auto",padding:"8px 10px",display:"flex",flexDirection:"column",gap:12,color:"#cccccc",fontSize:12},children:[k.jsx(Yc,{title:"Audio",emptyLabel:"No audio loaded",headers:["Name","Source","Duration","Size","URL"],rows:r.audio.map(e=>[e.name,e.source,uM(e.duration),Kr(e.originalSize),e.originalUrl??"—"])}),k.jsx(Yc,{title:"Atlas",emptyLabel:"No atlas",headers:["ID","Name","Glyph","Cell","Blocks","Max char"],rows:r.atlases.map(e=>[String(e.id),e.name,e.glyphSize,e.cellSize,String(e.atlasBlocks),String(e.maxCharCode)])}),k.jsx(Yc,{title:"Palettes",emptyLabel:"No palette",headers:["Slot","Colors"],rows:r.palettes.map(e=>[String(e.slotId),String(e.colors)])})]})}const yM=!0,Gt="u-",vM="uplot",wM=Gt+"hz",CM=Gt+"vt",bM=Gt+"title",SM=Gt+"wrap",xM=Gt+"under",IM=Gt+"over",kM=Gt+"axis",Ji=Gt+"off",EM=Gt+"select",MM=Gt+"cursor-x",UM=Gt+"cursor-y",AM=Gt+"cursor-pt",TM=Gt+"legend",RM=Gt+"live",PM=Gt+"inline",BM=Gt+"series",zM=Gt+"marker",mm=Gt+"label",DM=Gt+"value",Go="width",Xo="height",_o="top",ym="bottom",Us="left",Wc="right",Of="#000",vm=Of+"0",Gc="mousemove",wm="mousedown",Xc="mouseup",Cm="mouseenter",bm="mouseleave",Sm="dblclick",OM="resize",FM="scroll",xm="change",uu="dppxchange",Ff="--",yo=typeof window<"u",gh=yo?document:null,Js=yo?window:null,LM=yo?navigator:null;let je,hl;function mh(){let r=devicePixelRatio;je!=r&&(je=r,hl&&vh(xm,hl,mh),hl=matchMedia(`(min-resolution: ${je-.001}dppx) and (max-resolution: ${je+.001}dppx)`),ss(xm,hl,mh),Js.dispatchEvent(new CustomEvent(uu)))}function Wr(r,e){if(e!=null){let t=r.classList;!t.contains(e)&&t.add(e)}}function yh(r,e){let t=r.classList;t.contains(e)&&t.remove(e)}function lt(r,e,t){r.style[e]=t+"px"}function Cn(r,e,t,n){let i=gh.createElement(r);return e!=null&&Wr(i,e),t!=null&&t.insertBefore(i,n),i}function on(r,e){return Cn("div",r,e)}const Im=new WeakMap;function _n(r,e,t,n,i){let s="translate("+e+"px,"+t+"px)",o=Im.get(r);s!=o&&(r.style.transform=s,Im.set(r,s),e<0||t<0||e>n||t>i?Wr(r,Ji):yh(r,Ji))}const km=new WeakMap;function Em(r,e,t){let n=e+t,i=km.get(r);n!=i&&(km.set(r,n),r.style.background=e,r.style.borderColor=t)}const Mm=new WeakMap;function Um(r,e,t,n){let i=e+""+t,s=Mm.get(r);i!=s&&(Mm.set(r,i),r.style.height=t+"px",r.style.width=e+"px",r.style.marginLeft=n?-e/2+"px":0,r.style.marginTop=n?-t/2+"px":0)}const Lf={passive:!0},_M={...Lf,capture:!0};function ss(r,e,t,n){e.addEventListener(r,t,n?_M:Lf)}function vh(r,e,t,n){e.removeEventListener(r,t,Lf)}yo&&mh();function In(r,e,t,n){let i;t=t||0,n=n||e.length-1;let s=n<=2147483647;for(;n-t>1;)i=s?t+n>>1:Qr((t+n)/2),e[i]<r?t=i:n=i;return r-e[t]<=e[n]-r?t:n}function Gw(r){return(t,n,i)=>{let s=-1,o=-1;for(let a=n;a<=i;a++)if(r(t[a])){s=a;break}for(let a=i;a>=n;a--)if(r(t[a])){o=a;break}return[s,o]}}const Xw=r=>r!=null,Kw=r=>r!=null&&r>0,Du=Gw(Xw),$M=Gw(Kw);function NM(r,e,t,n=0,i=!1){let s=i?$M:Du,o=i?Kw:Xw;[e,t]=s(r,e,t);let a=r[e],l=r[e];if(e>-1)if(n==1)a=r[e],l=r[t];else if(n==-1)a=r[t],l=r[e];else for(let u=e;u<=t;u++){let c=r[u];o(c)&&(c<a?a=c:c>l&&(l=c))}return[a??Qe,l??-Qe]}function Ou(r,e,t,n){let i=Rm(r),s=Rm(e);r==e&&(i==-1?(r*=t,e/=t):(r/=t,e*=t));let o=t==10?ei:Zw,a=i==1?Qr:an,l=s==1?an:Qr,u=a(o(jt(r))),c=l(o(jt(e))),d=lo(t,u),h=lo(t,c);return t==10&&(u<0&&(d=Je(d,-u)),c<0&&(h=Je(h,-c))),n||t==2?(r=d*i,e=h*s):(r=eC(r,d),e=Fu(e,h)),[r,e]}function _f(r,e,t,n){let i=Ou(r,e,t,n);return r==0&&(i[0]=0),e==0&&(i[1]=0),i}const $f=.1,Am={mode:3,pad:$f},ca={pad:0,soft:null,mode:0},VM={min:ca,max:ca};function cu(r,e,t,n){return Lu(t)?Tm(r,e,t):(ca.pad=t,ca.soft=n?0:null,ca.mode=n?3:0,Tm(r,e,VM))}function _e(r,e){return r??e}function HM(r,e,t){for(e=_e(e,0),t=_e(t,r.length-1);e<=t;){if(r[e]!=null)return!0;e++}return!1}function Tm(r,e,t){let n=t.min,i=t.max,s=_e(n.pad,0),o=_e(i.pad,0),a=_e(n.hard,-Qe),l=_e(i.hard,Qe),u=_e(n.soft,Qe),c=_e(i.soft,-Qe),d=_e(n.mode,0),h=_e(i.mode,0),f=e-r,p=ei(f),m=Mr(jt(r),jt(e)),S=ei(m),w=jt(S-p);(f<1e-24||w>10)&&(f=0,(r==0||e==0)&&(f=1e-24,d==2&&u!=Qe&&(s=0),h==2&&c!=-Qe&&(o=0)));let g=f||m||1e3,y=ei(g),C=lo(10,Qr(y)),x=g*(f==0?r==0?.1:1:s),I=Je(eC(r-x,C/10),24),E=r>=u&&(d==1||d==3&&I<=u||d==2&&I>=u)?u:Qe,A=Mr(a,I<E&&r>=E?E:En(E,I)),R=g*(f==0?e==0?.1:1:o),F=Je(Fu(e+R,C/10),24),z=e<=c&&(h==1||h==3&&F>=c||h==2&&F<=c)?c:-Qe,P=En(l,F>z&&e<=z?z:Mr(z,F));return A==P&&A==0&&(P=100),[A,P]}const jM=new Intl.NumberFormat(yo?LM.language:"en-US"),Nf=r=>jM.format(r),rn=Math,zl=rn.PI,jt=rn.abs,Qr=rn.floor,$t=rn.round,an=rn.ceil,En=rn.min,Mr=rn.max,lo=rn.pow,Rm=rn.sign,ei=rn.log10,Zw=rn.log2,YM=(r,e=1)=>rn.sinh(r)*e,Kc=(r,e=1)=>rn.asinh(r/e),Qe=1/0;function Pm(r){return(ei((r^r>>31)-(r>>31))|0)+1}function wh(r,e,t){return En(Mr(r,e),t)}function qw(r){return typeof r=="function"}function Pe(r){return qw(r)?r:()=>r}const WM=()=>{},Qw=r=>r,Jw=(r,e)=>e,GM=r=>null,Bm=r=>!0,zm=(r,e)=>r==e,XM=/\.\d*?(?=9{6,}|0{6,})/gm,ds=r=>{if(rC(r)||zi.has(r))return r;const e=`${r}`,t=e.match(XM);if(t==null)return r;let n=t[0].length-1;if(e.indexOf("e-")!=-1){let[i,s]=e.split("e");return+`${ds(i)}e${s}`}return Je(r,n)};function qi(r,e){return ds(Je(ds(r/e))*e)}function Fu(r,e){return ds(an(ds(r/e))*e)}function eC(r,e){return ds(Qr(ds(r/e))*e)}function Je(r,e=0){if(rC(r))return r;let t=10**e,n=r*t*(1+Number.EPSILON);return $t(n)/t}const zi=new Map;function tC(r){return((""+r).split(".")[1]||"").length}function Ta(r,e,t,n){let i=[],s=n.map(tC);for(let o=e;o<t;o++){let a=jt(o),l=Je(lo(r,o),a);for(let u=0;u<n.length;u++){let c=r==10?+`${n[u]}e${o}`:n[u]*l,d=(o>=0?0:a)+(o>=s[u]?0:s[u]),h=r==10?c:Je(c,d);i.push(h),zi.set(h,d)}}return i}const da={},Vf=[],uo=[null,null],mi=Array.isArray,rC=Number.isInteger,KM=r=>r===void 0;function Dm(r){return typeof r=="string"}function Lu(r){let e=!1;if(r!=null){let t=r.constructor;e=t==null||t==Object}return e}function ZM(r){return r!=null&&typeof r=="object"}const qM=Object.getPrototypeOf(Uint8Array),nC="__proto__";function co(r,e=Lu){let t;if(mi(r)){let n=r.find(i=>i!=null);if(mi(n)||e(n)){t=Array(r.length);for(let i=0;i<r.length;i++)t[i]=co(r[i],e)}else t=r.slice()}else if(r instanceof qM)t=r.slice();else if(e(r)){t={};for(let n in r)n!=nC&&(t[n]=co(r[n],e))}else t=r;return t}function zt(r){let e=arguments;for(let t=1;t<e.length;t++){let n=e[t];for(let i in n)i!=nC&&(Lu(r[i])?zt(r[i],co(n[i])):r[i]=co(n[i]))}return r}const QM=0,JM=1,e5=2;function t5(r,e,t){for(let n=0,i,s=-1;n<e.length;n++){let o=e[n];if(o>s){for(i=o-1;i>=0&&r[i]==null;)r[i--]=null;for(i=o+1;i<t&&r[i]==null;)r[s=i++]=null}}}function r5(r,e){if(s5(r)){let o=r[0].slice();for(let a=1;a<r.length;a++)o.push(...r[a].slice(1));return o5(o[0])||(o=i5(o)),o}let t=new Set;for(let o=0;o<r.length;o++){let l=r[o][0],u=l.length;for(let c=0;c<u;c++)t.add(l[c])}let n=[Array.from(t).sort((o,a)=>o-a)],i=n[0].length,s=new Map;for(let o=0;o<i;o++)s.set(n[0][o],o);for(let o=0;o<r.length;o++){let a=r[o],l=a[0];for(let u=1;u<a.length;u++){let c=a[u],d=Array(i).fill(void 0),h=e?e[o][u]:JM,f=[];for(let p=0;p<c.length;p++){let m=c[p],S=s.get(l[p]);m===null?h!=QM&&(d[S]=m,h==e5&&f.push(S)):d[S]=m}t5(d,f,i),n.push(d)}}return n}const n5=typeof queueMicrotask>"u"?r=>Promise.resolve().then(r):queueMicrotask;function i5(r){let e=r[0],t=e.length,n=Array(t);for(let s=0;s<n.length;s++)n[s]=s;n.sort((s,o)=>e[s]-e[o]);let i=[];for(let s=0;s<r.length;s++){let o=r[s],a=Array(t);for(let l=0;l<t;l++)a[l]=o[n[l]];i.push(a)}return i}function s5(r){let e=r[0][0],t=e.length;for(let n=1;n<r.length;n++){let i=r[n][0];if(i.length!=t)return!1;if(i!=e){for(let s=0;s<t;s++)if(i[s]!=e[s])return!1}}return!0}function o5(r,e=100){const t=r.length;if(t<=1)return!0;let n=0,i=t-1;for(;n<=i&&r[n]==null;)n++;for(;i>=n&&r[i]==null;)i--;if(i<=n)return!0;const s=Mr(1,Qr((i-n+1)/e));for(let o=r[n],a=n+s;a<=i;a+=s){const l=r[a];if(l!=null){if(l<=o)return!1;o=l}}return!0}const iC=["January","February","March","April","May","June","July","August","September","October","November","December"],sC=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function oC(r){return r.slice(0,3)}const a5=sC.map(oC),l5=iC.map(oC),u5={MMMM:iC,MMM:l5,WWWW:sC,WWW:a5};function $o(r){return(r<10?"0":"")+r}function c5(r){return(r<10?"00":r<100?"0":"")+r}const d5={YYYY:r=>r.getFullYear(),YY:r=>(r.getFullYear()+"").slice(2),MMMM:(r,e)=>e.MMMM[r.getMonth()],MMM:(r,e)=>e.MMM[r.getMonth()],MM:r=>$o(r.getMonth()+1),M:r=>r.getMonth()+1,DD:r=>$o(r.getDate()),D:r=>r.getDate(),WWWW:(r,e)=>e.WWWW[r.getDay()],WWW:(r,e)=>e.WWW[r.getDay()],HH:r=>$o(r.getHours()),H:r=>r.getHours(),h:r=>{let e=r.getHours();return e==0?12:e>12?e-12:e},AA:r=>r.getHours()>=12?"PM":"AM",aa:r=>r.getHours()>=12?"pm":"am",a:r=>r.getHours()>=12?"p":"a",mm:r=>$o(r.getMinutes()),m:r=>r.getMinutes(),ss:r=>$o(r.getSeconds()),s:r=>r.getSeconds(),fff:r=>c5(r.getMilliseconds())};function Hf(r,e){e=e||u5;let t=[],n=/\{([a-z]+)\}|[^{]+/gi,i;for(;i=n.exec(r);)t.push(i[0][0]=="{"?d5[i[1]]:i[0]);return s=>{let o="";for(let a=0;a<t.length;a++)o+=typeof t[a]=="string"?t[a]:t[a](s,e);return o}}const h5=new Intl.DateTimeFormat().resolvedOptions().timeZone;function f5(r,e){let t;return e=="UTC"||e=="Etc/UTC"?t=new Date(+r+r.getTimezoneOffset()*6e4):e==h5?t=r:(t=new Date(r.toLocaleString("en-US",{timeZone:e})),t.setMilliseconds(r.getMilliseconds())),t}const aC=r=>r%1==0,du=[1,2,2.5,5],p5=Ta(10,-32,0,du),lC=Ta(10,0,32,du),g5=lC.filter(aC),Qi=p5.concat(lC),jf=`
|
|
274
|
-
`,uC="{YYYY}",Om=jf+uC,cC="{M}/{D}",Ko=jf+cC,fl=Ko+"/{YY}",dC="{aa}",m5="{h}:{mm}",Rs=m5+dC,Fm=jf+Rs,Lm=":{ss}",We=null;function hC(r){let e=r*1e3,t=e*60,n=t*60,i=n*24,s=i*30,o=i*365,l=(r==1?Ta(10,0,3,du).filter(aC):Ta(10,-3,0,du)).concat([e,e*5,e*10,e*15,e*30,t,t*5,t*10,t*15,t*30,n,n*2,n*3,n*4,n*6,n*8,n*12,i,i*2,i*3,i*4,i*5,i*6,i*7,i*8,i*9,i*10,i*15,s,s*2,s*3,s*4,s*6,o,o*2,o*5,o*10,o*25,o*50,o*100]);const u=[[o,uC,We,We,We,We,We,We,1],[i*28,"{MMM}",Om,We,We,We,We,We,1],[i,cC,Om,We,We,We,We,We,1],[n,"{h}"+dC,fl,We,Ko,We,We,We,1],[t,Rs,fl,We,Ko,We,We,We,1],[e,Lm,fl+" "+Rs,We,Ko+" "+Rs,We,Fm,We,1],[r,Lm+".{fff}",fl+" "+Rs,We,Ko+" "+Rs,We,Fm,We,1]];function c(d){return(h,f,p,m,S,w)=>{let g=[],y=S>=o,C=S>=s&&S<o,x=d(p),I=Je(x*r,3),E=Zc(x.getFullYear(),y?0:x.getMonth(),C||y?1:x.getDate()),A=Je(E*r,3);if(C||y){let R=C?S/s:0,F=y?S/o:0,z=I==A?I:Je(Zc(E.getFullYear()+F,E.getMonth()+R,1)*r,3),P=new Date($t(z/r)),O=P.getFullYear(),L=P.getMonth();for(let V=0;z<=m;V++){let X=Zc(O+F*V,L+R*V,1),T=X-d(Je(X*r,3));z=Je((+X+T)*r,3),z<=m&&g.push(z)}}else{let R=S>=i?i:S,F=Qr(p)-Qr(I),z=A+F+Fu(I-A,R);g.push(z);let P=d(z),O=P.getHours()+P.getMinutes()/t+P.getSeconds()/n,L=S/n,V=h.axes[f]._space,X=w/V;for(;z=Je(z+S,r==1?0:3),!(z>m);)if(L>1){let T=Qr(Je(O+L,6))%24,G=d(z).getHours()-T;G>1&&(G=-1),z-=G*n,O=(O+L)%24;let ee=g[g.length-1];Je((z-ee)/S,3)*X>=.7&&g.push(z)}else g.push(z)}return g}}return[l,u,c]}const[y5,v5,w5]=hC(1),[C5,b5,S5]=hC(.001);Ta(2,-53,53,[1]);function _m(r,e){return r.map(t=>t.map((n,i)=>i==0||i==8||n==null?n:e(i==1||t[8]==0?n:t[1]+n)))}function $m(r,e){return(t,n,i,s,o)=>{let a=e.find(p=>o>=p[0])||e[e.length-1],l,u,c,d,h,f;return n.map(p=>{let m=r(p),S=m.getFullYear(),w=m.getMonth(),g=m.getDate(),y=m.getHours(),C=m.getMinutes(),x=m.getSeconds(),I=S!=l&&a[2]||w!=u&&a[3]||g!=c&&a[4]||y!=d&&a[5]||C!=h&&a[6]||x!=f&&a[7]||a[1];return l=S,u=w,c=g,d=y,h=C,f=x,I(m)})}}function x5(r,e){let t=Hf(e);return(n,i,s,o,a)=>i.map(l=>t(r(l)))}function Zc(r,e,t){return new Date(r,e,t)}function Nm(r,e){return e(r)}const I5="{YYYY}-{MM}-{DD} {h}:{mm}{aa}";function Vm(r,e){return(t,n,i,s)=>s==null?Ff:e(r(n))}function k5(r,e){let t=r.series[e];return t.width?t.stroke(r,e):t.points.width?t.points.stroke(r,e):null}function E5(r,e){return r.series[e].fill(r,e)}const M5={show:!0,live:!0,isolate:!1,mount:WM,markers:{show:!0,width:2,stroke:k5,fill:E5,dash:"solid"},idx:null,idxs:null,values:[]};function U5(r,e){let t=r.cursor.points,n=on(),i=t.size(r,e);lt(n,Go,i),lt(n,Xo,i);let s=i/-2;lt(n,"marginLeft",s),lt(n,"marginTop",s);let o=t.width(r,e,i);return o&<(n,"borderWidth",o),n}function A5(r,e){let t=r.series[e].points;return t._fill||t._stroke}function T5(r,e){let t=r.series[e].points;return t._stroke||t._fill}function R5(r,e){return r.series[e].points.size}const qc=[0,0];function P5(r,e,t){return qc[0]=e,qc[1]=t,qc}function pl(r,e,t,n=!0){return i=>{i.button==0&&(!n||i.target==e)&&t(i)}}function Qc(r,e,t,n=!0){return i=>{(!n||i.target==e)&&t(i)}}const B5={show:!0,x:!0,y:!0,lock:!1,move:P5,points:{one:!1,show:U5,size:R5,width:0,stroke:T5,fill:A5},bind:{mousedown:pl,mouseup:pl,click:pl,dblclick:pl,mousemove:Qc,mouseleave:Qc,mouseenter:Qc},drag:{setScale:!0,x:!0,y:!1,dist:0,uni:null,click:(r,e)=>{e.stopPropagation(),e.stopImmediatePropagation()},_x:!1,_y:!1},focus:{dist:(r,e,t,n,i)=>n-i,prox:-1,bias:0},hover:{skip:[void 0],prox:null,bias:0},left:-10,top:-10,idx:null,dataIdx:null,idxs:null,event:null},fC={show:!0,stroke:"rgba(0,0,0,0.07)",width:2},Yf=zt({},fC,{filter:Jw}),pC=zt({},Yf,{size:10}),gC=zt({},fC,{show:!1}),Wf='12px system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',mC="bold "+Wf,yC=1.5,Hm={show:!0,scale:"x",stroke:Of,space:50,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:mC,side:2,grid:Yf,ticks:pC,border:gC,font:Wf,lineGap:yC,rotate:0},z5="Value",D5="Time",jm={show:!0,scale:"x",auto:!1,sorted:1,min:Qe,max:-Qe,idxs:[]};function O5(r,e,t,n,i){return e.map(s=>s==null?"":Nf(s))}function F5(r,e,t,n,i,s,o){let a=[],l=zi.get(i)||0;t=o?t:Je(Fu(t,i),l);for(let u=t;u<=n;u=Je(u+i,l))a.push(Object.is(u,-0)?0:u);return a}function Ch(r,e,t,n,i,s,o){const a=[],l=r.scales[r.axes[e].scale].log,u=l==10?ei:Zw,c=Qr(u(t));i=lo(l,c),l==10&&(i=Qi[In(i,Qi)]);let d=t,h=i*l;l==10&&(h=Qi[In(h,Qi)]);do a.push(d),d=d+i,l==10&&!zi.has(d)&&(d=Je(d,zi.get(i))),d>=h&&(i=d,h=i*l,l==10&&(h=Qi[In(h,Qi)]));while(d<=n);return a}function L5(r,e,t,n,i,s,o){let l=r.scales[r.axes[e].scale].asinh,u=n>l?Ch(r,e,Mr(l,t),n,i):[l],c=n>=0&&t<=0?[0]:[];return(t<-l?Ch(r,e,Mr(l,-n),-t,i):[l]).reverse().map(h=>-h).concat(c,u)}const vC=/./,_5=/[12357]/,$5=/[125]/,Ym=/1/,bh=(r,e,t,n)=>r.map((i,s)=>e==4&&i==0||s%n==0&&t.test(i.toExponential()[i<0?1:0])?i:null);function N5(r,e,t,n,i){let s=r.axes[t],o=s.scale,a=r.scales[o],l=r.valToPos,u=s._space,c=l(10,o),d=l(9,o)-c>=u?vC:l(7,o)-c>=u?_5:l(5,o)-c>=u?$5:Ym;if(d==Ym){let h=jt(l(1,o)-c);if(h<u)return bh(e.slice().reverse(),a.distr,d,an(u/h)).reverse()}return bh(e,a.distr,d,1)}function V5(r,e,t,n,i){let s=r.axes[t],o=s.scale,a=s._space,l=r.valToPos,u=jt(l(1,o)-l(2,o));return u<a?bh(e.slice().reverse(),3,vC,an(a/u)).reverse():e}function H5(r,e,t,n){return n==null?Ff:e==null?"":Nf(e)}const Wm={show:!0,scale:"y",stroke:Of,space:30,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:mC,side:3,grid:Yf,ticks:pC,border:gC,font:Wf,lineGap:yC,rotate:0};function j5(r,e){let t=3+(r||1)*2;return Je(t*e,3)}function Y5(r,e){let{scale:t,idxs:n}=r.series[0],i=r._data[0],s=r.valToPos(i[n[0]],t,!0),o=r.valToPos(i[n[1]],t,!0),a=jt(o-s),l=r.series[e],u=a/(l.points.space*je);return n[1]-n[0]<=u}const Gm={scale:null,auto:!0,sorted:0,min:Qe,max:-Qe},wC=(r,e,t,n,i)=>i,Xm={show:!0,auto:!0,sorted:0,gaps:wC,alpha:1,facets:[zt({},Gm,{scale:"x"}),zt({},Gm,{scale:"y"})]},Km={scale:"y",auto:!0,sorted:0,show:!0,spanGaps:!1,gaps:wC,alpha:1,points:{show:Y5,filter:null},values:null,min:Qe,max:-Qe,idxs:[],path:null,clip:null};function W5(r,e,t,n,i){return t/10}const CC={time:yM,auto:!0,distr:1,log:10,asinh:1,min:null,max:null,dir:1,ori:0},G5=zt({},CC,{time:!1,ori:1}),Zm={};function bC(r,e){let t=Zm[r];return t||(t={key:r,plots:[],sub(n){t.plots.push(n)},unsub(n){t.plots=t.plots.filter(i=>i!=n)},pub(n,i,s,o,a,l,u){for(let c=0;c<t.plots.length;c++)t.plots[c]!=i&&t.plots[c].pub(n,i,s,o,a,l,u)}},r!=null&&(Zm[r]=t)),t}const ho=1,Sh=2;function ps(r,e,t){const n=r.mode,i=r.series[e],s=n==2?r._data[e]:r._data,o=r.scales,a=r.bbox;let l=s[0],u=n==2?s[1]:s[e],c=n==2?o[i.facets[0].scale]:o[r.series[0].scale],d=n==2?o[i.facets[1].scale]:o[i.scale],h=a.left,f=a.top,p=a.width,m=a.height,S=r.valToPosH,w=r.valToPosV;return c.ori==0?t(i,l,u,c,d,S,w,h,f,p,m,$u,vo,Vu,xC,kC):t(i,l,u,c,d,w,S,f,h,m,p,Nu,wo,Kf,IC,EC)}function Gf(r,e){let t=0,n=0,i=_e(r.bands,Vf);for(let s=0;s<i.length;s++){let o=i[s];o.series[0]==e?t=o.dir:o.series[1]==e&&(o.dir==1?n|=1:n|=2)}return[t,n==1?-1:n==2?1:n==3?2:0]}function X5(r,e,t,n,i){let s=r.mode,o=r.series[e],a=s==2?o.facets[1].scale:o.scale,l=r.scales[a];return i==-1?l.min:i==1?l.max:l.distr==3?l.dir==1?l.min:l.max:0}function ti(r,e,t,n,i,s){return ps(r,e,(o,a,l,u,c,d,h,f,p,m,S)=>{let w=o.pxRound;const g=u.dir*(u.ori==0?1:-1),y=u.ori==0?vo:wo;let C,x;g==1?(C=t,x=n):(C=n,x=t);let I=w(d(a[C],u,m,f)),E=w(h(l[C],c,S,p)),A=w(d(a[x],u,m,f)),R=w(h(s==1?c.max:c.min,c,S,p)),F=new Path2D(i);return y(F,A,R),y(F,I,R),y(F,I,E),F})}function _u(r,e,t,n,i,s){let o=null;if(r.length>0){o=new Path2D;const a=e==0?Vu:Kf;let l=t;for(let d=0;d<r.length;d++){let h=r[d];if(h[1]>h[0]){let f=h[0]-l;f>0&&a(o,l,n,f,n+s),l=h[1]}}let u=t+i-l,c=10;u>0&&a(o,l,n-c/2,u,n+s+c)}return o}function K5(r,e,t){let n=r[r.length-1];n&&n[0]==e?n[1]=t:r.push([e,t])}function Xf(r,e,t,n,i,s,o){let a=[],l=r.length;for(let u=i==1?t:n;u>=t&&u<=n;u+=i)if(e[u]===null){let d=u,h=u;if(i==1)for(;++u<=n&&e[u]===null;)h=u;else for(;--u>=t&&e[u]===null;)h=u;let f=s(r[d]),p=h==d?f:s(r[h]),m=d-i;f=o<=0&&m>=0&&m<l?s(r[m]):f;let w=h+i;p=o>=0&&w>=0&&w<l?s(r[w]):p,p>=f&&a.push([f,p])}return a}function qm(r){return r==0?Qw:r==1?$t:e=>qi(e,r)}function SC(r){let e=r==0?$u:Nu,t=r==0?(i,s,o,a,l,u)=>{i.arcTo(s,o,a,l,u)}:(i,s,o,a,l,u)=>{i.arcTo(o,s,l,a,u)},n=r==0?(i,s,o,a,l)=>{i.rect(s,o,a,l)}:(i,s,o,a,l)=>{i.rect(o,s,l,a)};return(i,s,o,a,l,u=0,c=0)=>{u==0&&c==0?n(i,s,o,a,l):(u=En(u,a/2,l/2),c=En(c,a/2,l/2),e(i,s+u,o),t(i,s+a,o,s+a,o+l,u),t(i,s+a,o+l,s,o+l,c),t(i,s,o+l,s,o,c),t(i,s,o,s+a,o,u),i.closePath())}}const $u=(r,e,t)=>{r.moveTo(e,t)},Nu=(r,e,t)=>{r.moveTo(t,e)},vo=(r,e,t)=>{r.lineTo(e,t)},wo=(r,e,t)=>{r.lineTo(t,e)},Vu=SC(0),Kf=SC(1),xC=(r,e,t,n,i,s)=>{r.arc(e,t,n,i,s)},IC=(r,e,t,n,i,s)=>{r.arc(t,e,n,i,s)},kC=(r,e,t,n,i,s,o)=>{r.bezierCurveTo(e,t,n,i,s,o)},EC=(r,e,t,n,i,s,o)=>{r.bezierCurveTo(t,e,i,n,o,s)};function MC(r){return(e,t,n,i,s)=>ps(e,t,(o,a,l,u,c,d,h,f,p,m,S)=>{let{pxRound:w,points:g}=o,y,C;u.ori==0?(y=$u,C=xC):(y=Nu,C=IC);const x=Je(g.width*je,3);let I=(g.size-g.width)/2*je,E=Je(I*2,3),A=new Path2D,R=new Path2D,{left:F,top:z,width:P,height:O}=e.bbox;Vu(R,F-E,z-E,P+E*2,O+E*2);const L=V=>{if(l[V]!=null){let X=w(d(a[V],u,m,f)),T=w(h(l[V],c,S,p));y(A,X+I,T),C(A,X,T,I,0,zl*2)}};if(s)s.forEach(L);else for(let V=n;V<=i;V++)L(V);return{stroke:x>0?A:null,fill:A,clip:R,flags:ho|Sh}})}function UC(r){return(e,t,n,i,s,o)=>{n!=i&&(s!=n&&o!=n&&r(e,t,n),s!=i&&o!=i&&r(e,t,i),r(e,t,o))}}const Z5=UC(vo),q5=UC(wo);function AC(r){const e=_e(r==null?void 0:r.alignGaps,0);return(t,n,i,s)=>ps(t,n,(o,a,l,u,c,d,h,f,p,m,S)=>{[i,s]=Du(l,i,s);let w=o.pxRound,g=O=>w(d(O,u,m,f)),y=O=>w(h(O,c,S,p)),C,x;u.ori==0?(C=vo,x=Z5):(C=wo,x=q5);const I=u.dir*(u.ori==0?1:-1),E={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:ho},A=E.stroke;let R=!1;if(s-i>=m*4){let O=K=>t.posToVal(K,u.key,!0),L=null,V=null,X,T,_,j=g(a[I==1?i:s]),G=g(a[i]),ee=g(a[s]),q=O(I==1?G+1:ee-1);for(let K=I==1?i:s;K>=i&&K<=s;K+=I){let oe=a[K],ge=(I==1?oe<q:oe>q)?j:g(oe),Ce=l[K];ge==j?Ce!=null?(T=Ce,L==null?(C(A,ge,y(T)),X=L=V=T):T<L?L=T:T>V&&(V=T)):Ce===null&&(R=!0):(L!=null&&x(A,j,y(L),y(V),y(X),y(T)),Ce!=null?(T=Ce,C(A,ge,y(T)),L=V=X=T):(L=V=null,Ce===null&&(R=!0)),j=ge,q=O(j+I))}L!=null&&L!=V&&_!=j&&x(A,j,y(L),y(V),y(X),y(T))}else for(let O=I==1?i:s;O>=i&&O<=s;O+=I){let L=l[O];L===null?R=!0:L!=null&&C(A,g(a[O]),y(L))}let[z,P]=Gf(t,n);if(o.fill!=null||z!=0){let O=E.fill=new Path2D(A),L=o.fillTo(t,n,o.min,o.max,z),V=y(L),X=g(a[i]),T=g(a[s]);I==-1&&([T,X]=[X,T]),C(O,T,V),C(O,X,V)}if(!o.spanGaps){let O=[];R&&O.push(...Xf(a,l,i,s,I,g,e)),E.gaps=O=o.gaps(t,n,i,s,O),E.clip=_u(O,u.ori,f,p,m,S)}return P!=0&&(E.band=P==2?[ti(t,n,i,s,A,-1),ti(t,n,i,s,A,1)]:ti(t,n,i,s,A,P)),E})}function Q5(r){const e=_e(r.align,1),t=_e(r.ascDesc,!1),n=_e(r.alignGaps,0),i=_e(r.extend,!1);return(s,o,a,l)=>ps(s,o,(u,c,d,h,f,p,m,S,w,g,y)=>{[a,l]=Du(d,a,l);let C=u.pxRound,{left:x,width:I}=s.bbox,E=G=>C(p(G,h,g,S)),A=G=>C(m(G,f,y,w)),R=h.ori==0?vo:wo;const F={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:ho},z=F.stroke,P=h.dir*(h.ori==0?1:-1);let O=A(d[P==1?a:l]),L=E(c[P==1?a:l]),V=L,X=L;i&&e==-1&&(X=x,R(z,X,O)),R(z,L,O);for(let G=P==1?a:l;G>=a&&G<=l;G+=P){let ee=d[G];if(ee==null)continue;let q=E(c[G]),K=A(ee);e==1?R(z,q,O):R(z,V,K),R(z,q,K),O=K,V=q}let T=V;i&&e==1&&(T=x+I,R(z,T,O));let[_,j]=Gf(s,o);if(u.fill!=null||_!=0){let G=F.fill=new Path2D(z),ee=u.fillTo(s,o,u.min,u.max,_),q=A(ee);R(G,T,q),R(G,X,q)}if(!u.spanGaps){let G=[];G.push(...Xf(c,d,a,l,P,E,n));let ee=u.width*je/2,q=t||e==1?ee:-ee,K=t||e==-1?-ee:ee;G.forEach(oe=>{oe[0]+=q,oe[1]+=K}),F.gaps=G=u.gaps(s,o,a,l,G),F.clip=_u(G,h.ori,S,w,g,y)}return j!=0&&(F.band=j==2?[ti(s,o,a,l,z,-1),ti(s,o,a,l,z,1)]:ti(s,o,a,l,z,j)),F})}function Qm(r,e,t,n,i,s,o=Qe){if(r.length>1){let a=null;for(let l=0,u=1/0;l<r.length;l++)if(e[l]!==void 0){if(a!=null){let c=jt(r[l]-r[a]);c<u&&(u=c,o=jt(t(r[l],n,i,s)-t(r[a],n,i,s)))}a=l}}return o}function J5(r){r=r||da;const e=_e(r.size,[.6,Qe,1]),t=r.align||0,n=r.gap||0;let i=r.radius;i=i==null?[0,0]:typeof i=="number"?[i,0]:i;const s=Pe(i),o=1-e[0],a=_e(e[1],Qe),l=_e(e[2],1),u=_e(r.disp,da),c=_e(r.each,f=>{}),{fill:d,stroke:h}=u;return(f,p,m,S)=>ps(f,p,(w,g,y,C,x,I,E,A,R,F,z)=>{let P=w.pxRound,O=t,L=n*je,V=a*je,X=l*je,T,_;C.ori==0?[T,_]=s(f,p):[_,T]=s(f,p);const j=C.dir*(C.ori==0?1:-1);let G=C.ori==0?Vu:Kf,ee=C.ori==0?c:(ne,$e,ht,Q,W,le,ye)=>{c(ne,$e,ht,W,Q,ye,le)},q=_e(f.bands,Vf).find(ne=>ne.series[0]==p),K=q!=null?q.dir:0,oe=w.fillTo(f,p,w.min,w.max,K),ve=P(E(oe,x,z,R)),ge,Ce,ct,dt=F,xe=P(w.width*je),et=!1,Ke=null,qe=null,At=null,wt=null;d!=null&&(xe==0||h!=null)&&(et=!0,Ke=d.values(f,p,m,S),qe=new Map,new Set(Ke).forEach(ne=>{ne!=null&&qe.set(ne,new Path2D)}),xe>0&&(At=h.values(f,p,m,S),wt=new Map,new Set(At).forEach(ne=>{ne!=null&&wt.set(ne,new Path2D)})));let{x0:Ft,size:cr}=u;if(Ft!=null&&cr!=null){O=1,g=Ft.values(f,p,m,S),Ft.unit==2&&(g=g.map(ht=>f.posToVal(A+ht*F,C.key,!0)));let ne=cr.values(f,p,m,S);cr.unit==2?Ce=ne[0]*F:Ce=I(ne[0],C,F,A)-I(0,C,F,A),dt=Qm(g,y,I,C,F,A,dt),ct=dt-Ce+L}else dt=Qm(g,y,I,C,F,A,dt),ct=dt*o+L,Ce=dt-ct;ct<1&&(ct=0),xe>=Ce/2&&(xe=0),ct<5&&(P=Qw);let tt=ct>0,kt=dt-ct-(tt?xe:0);Ce=P(wh(kt,X,V)),ge=(O==0?Ce/2:O==j?0:Ce)-O*j*((O==0?L/2:0)+(tt?xe/2:0));const nt={stroke:null,fill:null,clip:null,band:null,gaps:null,flags:0},Cr=et?null:new Path2D;let Se=null;if(q!=null)Se=f.data[q.series[1]];else{let{y0:ne,y1:$e}=u;ne!=null&&$e!=null&&(y=$e.values(f,p,m,S),Se=ne.values(f,p,m,S))}let Re=T*Ce,pe=_*Ce;for(let ne=j==1?m:S;ne>=m&&ne<=S;ne+=j){let $e=y[ne];if($e==null)continue;if(Se!=null){let Ee=Se[ne]??0;if($e-Ee==0)continue;ve=E(Ee,x,z,R)}let ht=C.distr!=2||u!=null?g[ne]:ne,Q=I(ht,C,F,A),W=E(_e($e,oe),x,z,R),le=P(Q-ge),ye=P(Mr(W,ve)),de=P(En(W,ve)),Ue=ye-de;if($e!=null){let Ee=$e<0?pe:Re,Me=$e<0?Re:pe;et?(xe>0&&At[ne]!=null&&G(wt.get(At[ne]),le,de+Qr(xe/2),Ce,Mr(0,Ue-xe),Ee,Me),Ke[ne]!=null&&G(qe.get(Ke[ne]),le,de+Qr(xe/2),Ce,Mr(0,Ue-xe),Ee,Me)):G(Cr,le,de+Qr(xe/2),Ce,Mr(0,Ue-xe),Ee,Me),ee(f,p,ne,le-xe/2,de,Ce+xe,Ue)}}return xe>0?nt.stroke=et?wt:Cr:et||(nt._fill=w.width==0?w._fill:w._stroke??w._fill,nt.width=0),nt.fill=et?qe:Cr,nt})}function eU(r,e){const t=_e(e==null?void 0:e.alignGaps,0);return(n,i,s,o)=>ps(n,i,(a,l,u,c,d,h,f,p,m,S,w)=>{[s,o]=Du(u,s,o);let g=a.pxRound,y=T=>g(h(T,c,S,p)),C=T=>g(f(T,d,w,m)),x,I,E;c.ori==0?(x=$u,E=vo,I=kC):(x=Nu,E=wo,I=EC);const A=c.dir*(c.ori==0?1:-1);let R=y(l[A==1?s:o]),F=R,z=[],P=[];for(let T=A==1?s:o;T>=s&&T<=o;T+=A)if(u[T]!=null){let j=l[T],G=y(j);z.push(F=G),P.push(C(u[T]))}const O={stroke:r(z,P,x,E,I,g),fill:null,clip:null,band:null,gaps:null,flags:ho},L=O.stroke;let[V,X]=Gf(n,i);if(a.fill!=null||V!=0){let T=O.fill=new Path2D(L),_=a.fillTo(n,i,a.min,a.max,V),j=C(_);E(T,F,j),E(T,R,j)}if(!a.spanGaps){let T=[];T.push(...Xf(l,u,s,o,A,y,t)),O.gaps=T=a.gaps(n,i,s,o,T),O.clip=_u(T,c.ori,p,m,S,w)}return X!=0&&(O.band=X==2?[ti(n,i,s,o,L,-1),ti(n,i,s,o,L,1)]:ti(n,i,s,o,L,X)),O})}function tU(r){return eU(rU,r)}function rU(r,e,t,n,i,s){const o=r.length;if(o<2)return null;const a=new Path2D;if(t(a,r[0],e[0]),o==2)n(a,r[1],e[1]);else{let l=Array(o),u=Array(o-1),c=Array(o-1),d=Array(o-1);for(let h=0;h<o-1;h++)c[h]=e[h+1]-e[h],d[h]=r[h+1]-r[h],u[h]=c[h]/d[h];l[0]=u[0];for(let h=1;h<o-1;h++)u[h]===0||u[h-1]===0||u[h-1]>0!=u[h]>0?l[h]=0:(l[h]=3*(d[h-1]+d[h])/((2*d[h]+d[h-1])/u[h-1]+(d[h]+2*d[h-1])/u[h]),isFinite(l[h])||(l[h]=0));l[o-1]=u[o-2];for(let h=0;h<o-1;h++)i(a,r[h]+d[h]/3,e[h]+l[h]*d[h]/3,r[h+1]-d[h]/3,e[h+1]-l[h+1]*d[h]/3,r[h+1],e[h+1])}return a}const xh=new Set;function Jm(){for(let r of xh)r.syncRect(!0)}yo&&(ss(OM,Js,Jm),ss(FM,Js,Jm,!0),ss(uu,Js,()=>{yr.pxRatio=je}));const nU=AC(),iU=MC();function ey(r,e,t,n){return(n?[r[0],r[1]].concat(r.slice(2)):[r[0]].concat(r.slice(1))).map((s,o)=>Ih(s,o,e,t))}function sU(r,e){return r.map((t,n)=>n==0?{}:zt({},e,t))}function Ih(r,e,t,n){return zt({},e==0?t:n,r)}function TC(r,e,t){return e==null?uo:[e,t]}const oU=TC;function aU(r,e,t){return e==null?uo:cu(e,t,$f,!0)}function RC(r,e,t,n){return e==null?uo:Ou(e,t,r.scales[n].log,!1)}const lU=RC;function PC(r,e,t,n){return e==null?uo:_f(e,t,r.scales[n].log,!1)}const uU=PC;function cU(r,e,t,n,i){let s=Mr(Pm(r),Pm(e)),o=e-r,a=In(i/n*o,t);do{let l=t[a],u=n*l/o;if(u>=i&&s+(l<5?zi.get(l):0)<=17)return[l,u]}while(++a<t.length);return[0,0]}function ty(r){let e,t;return r=r.replace(/(\d+)px/,(n,i)=>(e=$t((t=+i)*je))+"px"),[r,e,t]}function dU(r){r.show&&[r.font,r.labelFont].forEach(e=>{let t=Je(e[2]*je,1);e[0]=e[0].replace(/[0-9.]+px/,t+"px"),e[1]=t})}function yr(r,e,t){const n={mode:_e(r.mode,1)},i=n.mode;function s(v,b,M,U){let B=b.valToPct(v);return U+M*(b.dir==-1?1-B:B)}function o(v,b,M,U){let B=b.valToPct(v);return U+M*(b.dir==-1?B:1-B)}function a(v,b,M,U){return b.ori==0?s(v,b,M,U):o(v,b,M,U)}n.valToPosH=s,n.valToPosV=o;let l=!1;n.status=0;const u=n.root=on(vM);if(r.id!=null&&(u.id=r.id),Wr(u,r.class),r.title){let v=on(bM,u);v.textContent=r.title}const c=Cn("canvas"),d=n.ctx=c.getContext("2d"),h=on(SM,u);ss("click",h,v=>{v.target===p&&(it!=bs||pt!=Ss)&&sr.click(n,v)},!0);const f=n.under=on(xM,h);h.appendChild(c);const p=n.over=on(IM,h);r=co(r);const m=+_e(r.pxAlign,1),S=qm(m);(r.plugins||[]).forEach(v=>{v.opts&&(r=v.opts(n,r)||r)});const w=r.ms||.001,g=n.series=i==1?ey(r.series||[],jm,Km,!1):sU(r.series||[null],Xm),y=n.axes=ey(r.axes||[],Hm,Wm,!0),C=n.scales={},x=n.bands=r.bands||[];x.forEach(v=>{v.fill=Pe(v.fill||null),v.dir=_e(v.dir,-1)});const I=i==2?g[1].facets[0].scale:g[0].scale,E={axes:YC,series:$C},A=(r.drawOrder||["axes","series"]).map(v=>E[v]);function R(v){const b=v.distr==3?M=>ei(M>0?M:v.clamp(n,M,v.min,v.max,v.key)):v.distr==4?M=>Kc(M,v.asinh):v.distr==100?M=>v.fwd(M):M=>M;return M=>{let U=b(M),{_min:B,_max:$}=v,Y=$-B;return(U-B)/Y}}function F(v){let b=C[v];if(b==null){let M=(r.scales||da)[v]||da;if(M.from!=null){F(M.from);let U=zt({},C[M.from],M,{key:v});U.valToPct=R(U),C[v]=U}else{b=C[v]=zt({},v==I?CC:G5,M),b.key=v;let U=b.time,B=b.range,$=mi(B);if((v!=I||i==2&&!U)&&($&&(B[0]==null||B[1]==null)&&(B={min:B[0]==null?Am:{mode:1,hard:B[0],soft:B[0]},max:B[1]==null?Am:{mode:1,hard:B[1],soft:B[1]}},$=!1),!$&&Lu(B))){let Y=B;B=(Z,re,ae)=>re==null?uo:cu(re,ae,Y)}b.range=Pe(B||(U?oU:v==I?b.distr==3?lU:b.distr==4?uU:TC:b.distr==3?RC:b.distr==4?PC:aU)),b.auto=Pe($?!1:b.auto),b.clamp=Pe(b.clamp||W5),b._min=b._max=null,b.valToPct=R(b)}}}F("x"),F("y"),i==1&&g.forEach(v=>{F(v.scale)}),y.forEach(v=>{F(v.scale)});for(let v in r.scales)F(v);const z=C[I],P=z.distr;let O,L;z.ori==0?(Wr(u,wM),O=s,L=o):(Wr(u,CM),O=o,L=s);const V={};for(let v in C){let b=C[v];(b.min!=null||b.max!=null)&&(V[v]={min:b.min,max:b.max},b.min=b.max=null)}const X=r.tzDate||(v=>new Date($t(v/w))),T=r.fmtDate||Hf,_=w==1?w5(X):S5(X),j=$m(X,_m(w==1?v5:b5,T)),G=Vm(X,Nm(I5,T)),ee=[],q=n.legend=zt({},M5,r.legend),K=n.cursor=zt({},B5,{drag:{y:i==2}},r.cursor),oe=q.show,ve=K.show,ge=q.markers;q.idxs=ee,ge.width=Pe(ge.width),ge.dash=Pe(ge.dash),ge.stroke=Pe(ge.stroke),ge.fill=Pe(ge.fill);let Ce,ct,dt,xe=[],et=[],Ke,qe=!1,At={};if(q.live){const v=g[1]?g[1].values:null;qe=v!=null,Ke=qe?v(n,1,0):{_:0};for(let b in Ke)At[b]=Ff}if(oe)if(Ce=Cn("table",TM,u),dt=Cn("tbody",null,Ce),q.mount(n,Ce),qe){ct=Cn("thead",null,Ce,dt);let v=Cn("tr",null,ct);Cn("th",null,v);for(var wt in Ke)Cn("th",mm,v).textContent=wt}else Wr(Ce,PM),q.live&&Wr(Ce,RM);const Ft={show:!0},cr={show:!1};function tt(v,b){if(b==0&&(qe||!q.live||i==2))return uo;let M=[],U=Cn("tr",BM,dt,dt.childNodes[b]);Wr(U,v.class),v.show||Wr(U,Ji);let B=Cn("th",null,U);if(ge.show){let Z=on(zM,B);if(b>0){let re=ge.width(n,b);re&&(Z.style.border=re+"px "+ge.dash(n,b)+" "+ge.stroke(n,b)),Z.style.background=ge.fill(n,b)}}let $=on(mm,B);v.label instanceof HTMLElement?$.appendChild(v.label):$.textContent=v.label,b>0&&(ge.show||($.style.color=v.width>0?ge.stroke(n,b):ge.fill(n,b)),nt("click",B,Z=>{if(K._lock)return;Br(Z);let re=g.indexOf(v);if((Z.ctrlKey||Z.metaKey)!=q.isolate){let ae=g.some((ue,he)=>he>0&&he!=re&&ue.show);g.forEach((ue,he)=>{he>0&&zn(he,ae?he==re?Ft:cr:Ft,!0,Bt.setSeries)})}else zn(re,{show:!v.show},!0,Bt.setSeries)},!1),Tn&&nt(Cm,B,Z=>{K._lock||(Br(Z),zn(g.indexOf(v),Is,!0,Bt.setSeries))},!1));for(var Y in Ke){let Z=Cn("td",DM,U);Z.textContent="--",M.push(Z)}return[U,M]}const kt=new Map;function nt(v,b,M,U=!0){const B=kt.get(b)||{},$=K.bind[v](n,b,M,U);$&&(ss(v,b,B[v]=$),kt.set(b,B))}function Cr(v,b,M){const U=kt.get(b)||{};for(let B in U)(v==null||B==v)&&(vh(B,b,U[B]),delete U[B]);v==null&&kt.delete(b)}let Se=0,Re=0,pe=0,ne=0,$e=0,ht=0,Q=$e,W=ht,le=pe,ye=ne,de=0,Ue=0,Ee=0,Me=0;n.bbox={};let Ne=!1,we=!1,Oe=!1,Tt=!1,ft=!1,Ve=!1;function Xt(v,b,M){(M||v!=n.width||b!=n.height)&&Lt(v,b),ys(!1),Oe=!0,we=!0,vs()}function Lt(v,b){n.width=Se=pe=v,n.height=Re=ne=b,$e=ht=0,Fe(),$i();let M=n.bbox;de=M.left=qi($e*je,.5),Ue=M.top=qi(ht*je,.5),Ee=M.width=qi(pe*je,.5),Me=M.height=qi(ne*je,.5)}const ai=3;function Li(){let v=!1,b=0;for(;!v;){b++;let M=HC(b),U=jC(b);v=b==ai||M&&U,v||(Lt(n.width,n.height),we=!0)}}function _i({width:v,height:b}){Xt(v,b)}n.setSize=_i;function Fe(){let v=!1,b=!1,M=!1,U=!1;y.forEach((B,$)=>{if(B.show&&B._show){let{side:Y,_size:Z}=B,re=Y%2,ae=B.label!=null?B.labelSize:0,ue=Z+ae;ue>0&&(re?(pe-=ue,Y==3?($e+=ue,U=!0):M=!0):(ne-=ue,Y==0?(ht+=ue,v=!0):b=!0))}}),Vi[0]=v,Vi[1]=M,Vi[2]=b,Vi[3]=U,pe-=li[1]+li[3],$e+=li[3],ne-=li[2]+li[0],ht+=li[0]}function $i(){let v=$e+pe,b=ht+ne,M=$e,U=ht;function B($,Y){switch($){case 1:return v+=Y,v-Y;case 2:return b+=Y,b-Y;case 3:return M-=Y,M+Y;case 0:return U-=Y,U+Y}}y.forEach(($,Y)=>{if($.show&&$._show){let Z=$.side;$._pos=B(Z,$._size),$.label!=null&&($._lpos=B(Z,$.labelSize))}})}if(K.dataIdx==null){let v=K.hover,b=v.skip=new Set(v.skip??[]);b.add(void 0);let M=v.prox=Pe(v.prox),U=v.bias??(v.bias=0);K.dataIdx=(B,$,Y,Z)=>{if($==0)return Y;let re=Y,ae=M(B,$,Y,Z)??Qe,ue=ae>=0&&ae<Qe,he=z.ori==0?pe:ne,Ie=K.left,He=e[0],Le=e[$];if(b.has(Le[Y])){re=null;let Ae=null,be=null,me;if(U==0||U==-1)for(me=Y;Ae==null&&me-- >0;)b.has(Le[me])||(Ae=me);if(U==0||U==1)for(me=Y;be==null&&me++<Le.length;)b.has(Le[me])||(be=me);if(Ae!=null||be!=null)if(ue){let ot=Ae==null?-1/0:O(He[Ae],z,he,0),Et=be==null?1/0:O(He[be],z,he,0),er=Ie-ot,Ze=Et-Ie;er<=Ze?er<=ae&&(re=Ae):Ze<=ae&&(re=be)}else re=be==null?Ae:Ae==null?be:Y-Ae<=be-Y?Ae:be}else ue&&jt(Ie-O(He[Y],z,he,0))>ae&&(re=null);return re}}const Br=v=>{K.event=v};K.idxs=ee,K._lock=!1;let Ct=K.points;Ct.show=Pe(Ct.show),Ct.size=Pe(Ct.size),Ct.stroke=Pe(Ct.stroke),Ct.width=Pe(Ct.width),Ct.fill=Pe(Ct.fill);const dr=n.focus=zt({},r.focus||{alpha:.3},K.focus),Tn=dr.prox>=0,Rn=Tn&&Ct.one;let hr=[],Pn=[],Bn=[];function gs(v,b){let M=Ct.show(n,b);if(M instanceof HTMLElement)return Wr(M,AM),Wr(M,v.class),_n(M,-10,-10,pe,ne),p.insertBefore(M,hr[b]),M}function Pt(v,b){if(i==1||b>0){let M=i==1&&C[v.scale].time,U=v.value;v.value=M?Dm(U)?Vm(X,Nm(U,T)):U||G:U||H5,v.label=v.label||(M?D5:z5)}if(Rn||b>0){v.width=v.width==null?1:v.width,v.paths=v.paths||nU||GM,v.fillTo=Pe(v.fillTo||X5),v.pxAlign=+_e(v.pxAlign,m),v.pxRound=qm(v.pxAlign),v.stroke=Pe(v.stroke||null),v.fill=Pe(v.fill||null),v._stroke=v._fill=v._paths=v._focus=null;let M=j5(Mr(1,v.width),1),U=v.points=zt({},{size:M,width:Mr(1,M*.2),stroke:v.stroke,space:M*2,paths:iU,_stroke:null,_fill:null},v.points);U.show=Pe(U.show),U.filter=Pe(U.filter),U.fill=Pe(U.fill),U.stroke=Pe(U.stroke),U.paths=Pe(U.paths),U.pxAlign=v.pxAlign}if(oe){let M=tt(v,b);xe.splice(b,0,M[0]),et.splice(b,0,M[1]),q.values.push(null)}if(ve){ee.splice(b,0,null);let M=null;Rn?b==0&&(M=gs(v,b)):b>0&&(M=gs(v,b)),hr.splice(b,0,M),Pn.splice(b,0,0),Bn.splice(b,0,0)}Jt("addSeries",b)}function bt(v,b){b=b??g.length,v=i==1?Ih(v,b,jm,Km):Ih(v,b,{},Xm),g.splice(b,0,v),Pt(g[b],b)}n.addSeries=bt;function Ni(v){if(g.splice(v,1),oe){q.values.splice(v,1),et.splice(v,1);let b=xe.splice(v,1)[0];Cr(null,b.firstChild),b.remove()}ve&&(ee.splice(v,1),hr.splice(v,1)[0].remove(),Pn.splice(v,1),Bn.splice(v,1)),Jt("delSeries",v)}n.delSeries=Ni;const Vi=[!1,!1,!1,!1];function FC(v,b){if(v._show=v.show,v.show){let M=v.side%2,U=C[v.scale];U==null&&(v.scale=M?g[1].scale:I,U=C[v.scale]);let B=U.time;v.size=Pe(v.size),v.space=Pe(v.space),v.rotate=Pe(v.rotate),mi(v.incrs)&&v.incrs.forEach(Y=>{!zi.has(Y)&&zi.set(Y,tC(Y))}),v.incrs=Pe(v.incrs||(U.distr==2?g5:B?w==1?y5:C5:Qi)),v.splits=Pe(v.splits||(B&&U.distr==1?_:U.distr==3?Ch:U.distr==4?L5:F5)),v.stroke=Pe(v.stroke),v.grid.stroke=Pe(v.grid.stroke),v.ticks.stroke=Pe(v.ticks.stroke),v.border.stroke=Pe(v.border.stroke);let $=v.values;v.values=mi($)&&!mi($[0])?Pe($):B?mi($)?$m(X,_m($,T)):Dm($)?x5(X,$):$||j:$||O5,v.filter=Pe(v.filter||(U.distr>=3&&U.log==10?N5:U.distr==3&&U.log==2?V5:Jw)),v.font=ty(v.font),v.labelFont=ty(v.labelFont),v._size=v.size(n,null,b,0),v._space=v._rotate=v._incrs=v._found=v._splits=v._values=null,v._size>0&&(Vi[b]=!0,v._el=on(kM,h))}}function bo(v,b,M,U){let[B,$,Y,Z]=M,re=b%2,ae=0;return re==0&&(Z||$)&&(ae=b==0&&!B||b==2&&!Y?$t(Hm.size/3):0),re==1&&(B||Y)&&(ae=b==1&&!$||b==3&&!Z?$t(Wm.size/2):0),ae}const Qf=n.padding=(r.padding||[bo,bo,bo,bo]).map(v=>Pe(_e(v,bo))),li=n._padding=Qf.map((v,b)=>v(n,b,Vi,0));let ir,Kt=null,Zt=null;const La=i==1?g[0].idxs:null;let gn=null,So=!1;function Jf(v,b){if(e=v??[],n.data=n._data=e,i==2){ir=0;for(let M=1;M<g.length;M++)ir+=e[M][0].length}else{e.length==0&&(n.data=n._data=e=[[]]),gn=e[0],ir=gn.length;let M=e;if(P==2){M=e.slice();let U=M[0]=Array(ir);for(let B=0;B<ir;B++)U[B]=B}n._data=e=M}if(ys(!0),Jt("setData"),P==2&&(Oe=!0),b!==!1){let M=z;M.auto(n,So)?Hu():ci(I,M.min,M.max),Tt=Tt||K.left>=0,Ve=!0,vs()}}n.setData=Jf;function Hu(){So=!0;let v,b;i==1&&(ir>0?(Kt=La[0]=0,Zt=La[1]=ir-1,v=e[0][Kt],b=e[0][Zt],P==2?(v=Kt,b=Zt):v==b&&(P==3?[v,b]=Ou(v,v,z.log,!1):P==4?[v,b]=_f(v,v,z.log,!1):z.time?b=v+$t(86400/w):[v,b]=cu(v,b,$f,!0))):(Kt=La[0]=v=null,Zt=La[1]=b=null)),ci(I,v,b)}let _a,ms,ju,Yu,Wu,Gu,Xu,Ku,Zu,zr;function ep(v,b,M,U,B,$){v??(v=vm),M??(M=Vf),U??(U="butt"),B??(B=vm),$??($="round"),v!=_a&&(d.strokeStyle=_a=v),B!=ms&&(d.fillStyle=ms=B),b!=ju&&(d.lineWidth=ju=b),$!=Wu&&(d.lineJoin=Wu=$),U!=Gu&&(d.lineCap=Gu=U),M!=Yu&&d.setLineDash(Yu=M)}function tp(v,b,M,U){b!=ms&&(d.fillStyle=ms=b),v!=Xu&&(d.font=Xu=v),M!=Ku&&(d.textAlign=Ku=M),U!=Zu&&(d.textBaseline=Zu=U)}function qu(v,b,M,U,B=0){if(U.length>0&&v.auto(n,So)&&(b==null||b.min==null)){let $=_e(Kt,0),Y=_e(Zt,U.length-1),Z=M.min==null?NM(U,$,Y,B,v.distr==3):[M.min,M.max];v.min=En(v.min,M.min=Z[0]),v.max=Mr(v.max,M.max=Z[1])}}const rp={min:null,max:null};function LC(){for(let U in C){let B=C[U];V[U]==null&&(B.min==null||V[I]!=null&&B.auto(n,So))&&(V[U]=rp)}for(let U in C){let B=C[U];V[U]==null&&B.from!=null&&V[B.from]!=null&&(V[U]=rp)}V[I]!=null&&ys(!0);let v={};for(let U in V){let B=V[U];if(B!=null){let $=v[U]=co(C[U],ZM);if(B.min!=null)zt($,B);else if(U!=I||i==2)if(ir==0&&$.from==null){let Y=$.range(n,null,null,U);$.min=Y[0],$.max=Y[1]}else $.min=Qe,$.max=-Qe}}if(ir>0){g.forEach((U,B)=>{if(i==1){let $=U.scale,Y=V[$];if(Y==null)return;let Z=v[$];if(B==0){let re=Z.range(n,Z.min,Z.max,$);Z.min=re[0],Z.max=re[1],Kt=In(Z.min,e[0]),Zt=In(Z.max,e[0]),Zt-Kt>1&&(e[0][Kt]<Z.min&&Kt++,e[0][Zt]>Z.max&&Zt--),U.min=gn[Kt],U.max=gn[Zt]}else U.show&&U.auto&&qu(Z,Y,U,e[B],U.sorted);U.idxs[0]=Kt,U.idxs[1]=Zt}else if(B>0&&U.show&&U.auto){let[$,Y]=U.facets,Z=$.scale,re=Y.scale,[ae,ue]=e[B],he=v[Z],Ie=v[re];he!=null&&qu(he,V[Z],$,ae,$.sorted),Ie!=null&&qu(Ie,V[re],Y,ue,Y.sorted),U.min=Y.min,U.max=Y.max}});for(let U in v){let B=v[U],$=V[U];if(B.from==null&&($==null||$.min==null)){let Y=B.range(n,B.min==Qe?null:B.min,B.max==-Qe?null:B.max,U);B.min=Y[0],B.max=Y[1]}}}for(let U in v){let B=v[U];if(B.from!=null){let $=v[B.from];if($.min==null)B.min=B.max=null;else{let Y=B.range(n,$.min,$.max,U);B.min=Y[0],B.max=Y[1]}}}let b={},M=!1;for(let U in v){let B=v[U],$=C[U];if($.min!=B.min||$.max!=B.max){$.min=B.min,$.max=B.max;let Y=$.distr;$._min=Y==3?ei($.min):Y==4?Kc($.min,$.asinh):Y==100?$.fwd($.min):$.min,$._max=Y==3?ei($.max):Y==4?Kc($.max,$.asinh):Y==100?$.fwd($.max):$.max,b[U]=M=!0}}if(M){g.forEach((U,B)=>{i==2?B>0&&b.y&&(U._paths=null):b[U.scale]&&(U._paths=null)});for(let U in b)Oe=!0,Jt("setScale",U);ve&&K.left>=0&&(Tt=Ve=!0)}for(let U in V)V[U]=null}function _C(v){let b=wh(Kt-1,0,ir-1),M=wh(Zt+1,0,ir-1);for(;v[b]==null&&b>0;)b--;for(;v[M]==null&&M<ir-1;)M++;return[b,M]}function $C(){if(ir>0){let v=g.some(b=>b._focus)&&zr!=dr.alpha;v&&(d.globalAlpha=zr=dr.alpha),g.forEach((b,M)=>{if(M>0&&b.show&&(np(M,!1),np(M,!0),b._paths==null)){let U=zr;zr!=b.alpha&&(d.globalAlpha=zr=b.alpha);let B=i==2?[0,e[M][0].length-1]:_C(e[M]);b._paths=b.paths(n,M,B[0],B[1]),zr!=U&&(d.globalAlpha=zr=U)}}),g.forEach((b,M)=>{if(M>0&&b.show){let U=zr;zr!=b.alpha&&(d.globalAlpha=zr=b.alpha),b._paths!=null&&ip(M,!1);{let B=b._paths!=null?b._paths.gaps:null,$=b.points.show(n,M,Kt,Zt,B),Y=b.points.filter(n,M,$,B);($||Y)&&(b.points._paths=b.points.paths(n,M,Kt,Zt,Y),ip(M,!0))}zr!=U&&(d.globalAlpha=zr=U),Jt("drawSeries",M)}}),v&&(d.globalAlpha=zr=1)}}function np(v,b){let M=b?g[v].points:g[v];M._stroke=M.stroke(n,v),M._fill=M.fill(n,v)}function ip(v,b){let M=b?g[v].points:g[v],{stroke:U,fill:B,clip:$,flags:Y,_stroke:Z=M._stroke,_fill:re=M._fill,_width:ae=M.width}=M._paths;ae=Je(ae*je,3);let ue=null,he=ae%2/2;b&&re==null&&(re=ae>0?"#fff":Z);let Ie=M.pxAlign==1&&he>0;if(Ie&&d.translate(he,he),!b){let He=de-ae/2,Le=Ue-ae/2,Ae=Ee+ae,be=Me+ae;ue=new Path2D,ue.rect(He,Le,Ae,be)}b?Qu(Z,ae,M.dash,M.cap,re,U,B,Y,$):NC(v,Z,ae,M.dash,M.cap,re,U,B,Y,ue,$),Ie&&d.translate(-he,-he)}function NC(v,b,M,U,B,$,Y,Z,re,ae,ue){let he=!1;re!=0&&x.forEach((Ie,He)=>{if(Ie.series[0]==v){let Le=g[Ie.series[1]],Ae=e[Ie.series[1]],be=(Le._paths||da).band;mi(be)&&(be=Ie.dir==1?be[0]:be[1]);let me,ot=null;Le.show&&be&&HM(Ae,Kt,Zt)?(ot=Ie.fill(n,He)||$,me=Le._paths.clip):be=null,Qu(b,M,U,B,ot,Y,Z,re,ae,ue,me,be),he=!0}}),he||Qu(b,M,U,B,$,Y,Z,re,ae,ue)}const sp=ho|Sh;function Qu(v,b,M,U,B,$,Y,Z,re,ae,ue,he){ep(v,b,M,U,B),(re||ae||he)&&(d.save(),re&&d.clip(re),ae&&d.clip(ae)),he?(Z&sp)==sp?(d.clip(he),ue&&d.clip(ue),Na(B,Y),$a(v,$,b)):Z&Sh?(Na(B,Y),d.clip(he),$a(v,$,b)):Z&ho&&(d.save(),d.clip(he),ue&&d.clip(ue),Na(B,Y),d.restore(),$a(v,$,b)):(Na(B,Y),$a(v,$,b)),(re||ae||he)&&d.restore()}function $a(v,b,M){M>0&&(b instanceof Map?b.forEach((U,B)=>{d.strokeStyle=_a=B,d.stroke(U)}):b!=null&&v&&d.stroke(b))}function Na(v,b){b instanceof Map?b.forEach((M,U)=>{d.fillStyle=ms=U,d.fill(M)}):b!=null&&v&&d.fill(b)}function VC(v,b,M,U){let B=y[v],$;if(U<=0)$=[0,0];else{let Y=B._space=B.space(n,v,b,M,U),Z=B._incrs=B.incrs(n,v,b,M,U,Y);$=cU(b,M,Z,U,Y)}return B._found=$}function Ju(v,b,M,U,B,$,Y,Z,re,ae){let ue=Y%2/2;m==1&&d.translate(ue,ue),ep(Z,Y,re,ae,Z),d.beginPath();let he,Ie,He,Le,Ae=B+(U==0||U==3?-$:$);M==0?(Ie=B,Le=Ae):(he=B,He=Ae);for(let be=0;be<v.length;be++)b[be]!=null&&(M==0?he=He=v[be]:Ie=Le=v[be],d.moveTo(he,Ie),d.lineTo(He,Le));d.stroke(),m==1&&d.translate(-ue,-ue)}function HC(v){let b=!0;return y.forEach((M,U)=>{if(!M.show)return;let B=C[M.scale];if(B.min==null){M._show&&(b=!1,M._show=!1,ys(!1));return}else M._show||(b=!1,M._show=!0,ys(!1));let $=M.side,Y=$%2,{min:Z,max:re}=B,[ae,ue]=VC(U,Z,re,Y==0?pe:ne);if(ue==0)return;let he=B.distr==2,Ie=M._splits=M.splits(n,U,Z,re,ae,ue,he),He=B.distr==2?Ie.map(me=>gn[me]):Ie,Le=B.distr==2?gn[Ie[1]]-gn[Ie[0]]:ae,Ae=M._values=M.values(n,M.filter(n,He,U,ue,Le),U,ue,Le);M._rotate=$==2?M.rotate(n,Ae,U,ue):0;let be=M._size;M._size=an(M.size(n,Ae,U,v)),be!=null&&M._size!=be&&(b=!1)}),b}function jC(v){let b=!0;return Qf.forEach((M,U)=>{let B=M(n,U,Vi,v);B!=li[U]&&(b=!1),li[U]=B}),b}function YC(){for(let v=0;v<y.length;v++){let b=y[v];if(!b.show||!b._show)continue;let M=b.side,U=M%2,B,$,Y=b.stroke(n,v),Z=M==0||M==3?-1:1,[re,ae]=b._found;if(b.label!=null){let Sr=b.labelGap*Z,jr=$t((b._lpos+Sr)*je);tp(b.labelFont[0],Y,"center",M==2?_o:ym),d.save(),U==1?(B=$=0,d.translate(jr,$t(Ue+Me/2)),d.rotate((M==3?-zl:zl)/2)):(B=$t(de+Ee/2),$=jr);let Yi=qw(b.label)?b.label(n,v,re,ae):b.label;d.fillText(Yi,B,$),d.restore()}if(ae==0)continue;let ue=C[b.scale],he=U==0?Ee:Me,Ie=U==0?de:Ue,He=b._splits,Le=ue.distr==2?He.map(Sr=>gn[Sr]):He,Ae=ue.distr==2?gn[He[1]]-gn[He[0]]:re,be=b.ticks,me=b.border,ot=be.show?be.size:0,Et=$t(ot*je),er=$t((b.alignTo==2?b._size-ot-b.gap:b.gap)*je),Ze=b._rotate*-zl/180,Mt=S(b._pos*je),Vr=(Et+er)*Z,br=Mt+Vr;$=U==0?br:0,B=U==1?br:0;let nn=b.font[0],mn=b.align==1?Us:b.align==2?Wc:Ze>0?Us:Ze<0?Wc:U==0?"center":M==3?Wc:Us,On=Ze||U==1?"middle":M==2?_o:ym;tp(nn,Y,mn,On);let Hr=b.font[1]*b.lineGap,sn=He.map(Sr=>S(a(Sr,ue,he,Ie))),yn=b._values;for(let Sr=0;Sr<yn.length;Sr++){let jr=yn[Sr];if(jr!=null){U==0?B=sn[Sr]:$=sn[Sr],jr=""+jr;let Yi=jr.indexOf(`
|
|
275
|
-
`)==-1?[jr]:jr.split(/\n/gm);for(let xr=0;xr<Yi.length;xr++){let Ip=Yi[xr];Ze?(d.save(),d.translate(B,$+xr*Hr),d.rotate(Ze),d.fillText(Ip,0,0),d.restore()):d.fillText(Ip,B,$+xr*Hr)}}}be.show&&Ju(sn,be.filter(n,Le,v,ae,Ae),U,M,Mt,Et,Je(be.width*je,3),be.stroke(n,v),be.dash,be.cap);let Fn=b.grid;Fn.show&&Ju(sn,Fn.filter(n,Le,v,ae,Ae),U,U==0?2:1,U==0?Ue:de,U==0?Me:Ee,Je(Fn.width*je,3),Fn.stroke(n,v),Fn.dash,Fn.cap),me.show&&Ju([Mt],[1],U==0?1:0,U==0?1:2,U==1?Ue:de,U==1?Me:Ee,Je(me.width*je,3),me.stroke(n,v),me.dash,me.cap)}Jt("drawAxes")}function ys(v){g.forEach((b,M)=>{M>0&&(b._paths=null,v&&(i==1?(b.min=null,b.max=null):b.facets.forEach(U=>{U.min=null,U.max=null})))})}let Va=!1,ec=!1,xo=[];function WC(){ec=!1;for(let v=0;v<xo.length;v++)Jt(...xo[v]);xo.length=0}function vs(){Va||(n5(op),Va=!0)}function GC(v,b=!1){Va=!0,ec=b,v(n),op(),b&&xo.length>0&&queueMicrotask(WC)}n.batch=GC;function op(){if(Ne&&(LC(),Ne=!1),Oe&&(Li(),Oe=!1),we){if(lt(f,Us,$e),lt(f,_o,ht),lt(f,Go,pe),lt(f,Xo,ne),lt(p,Us,$e),lt(p,_o,ht),lt(p,Go,pe),lt(p,Xo,ne),lt(h,Go,Se),lt(h,Xo,Re),c.width=$t(Se*je),c.height=$t(Re*je),y.forEach(({_el:v,_show:b,_size:M,_pos:U,side:B})=>{if(v!=null)if(b){let $=B===3||B===0?M:0,Y=B%2==1;lt(v,Y?"left":"top",U-$),lt(v,Y?"width":"height",M),lt(v,Y?"top":"left",Y?ht:$e),lt(v,Y?"height":"width",Y?ne:pe),yh(v,Ji)}else Wr(v,Ji)}),_a=ms=ju=Wu=Gu=Xu=Ku=Zu=Yu=null,zr=1,Eo(!0),$e!=Q||ht!=W||pe!=le||ne!=ye){ys(!1);let v=pe/le,b=ne/ye;if(ve&&!Tt&&K.left>=0){K.left*=v,K.top*=b,ws&&_n(ws,$t(K.left),0,pe,ne),Cs&&_n(Cs,0,$t(K.top),pe,ne);for(let M=0;M<hr.length;M++){let U=hr[M];U!=null&&(Pn[M]*=v,Bn[M]*=b,_n(U,an(Pn[M]),an(Bn[M]),pe,ne))}}if(st.show&&!ft&&st.left>=0&&st.width>0){st.left*=v,st.width*=v,st.top*=b,st.height*=b;for(let M in oc)lt(xs,M,st[M])}Q=$e,W=ht,le=pe,ye=ne}Jt("setSize"),we=!1}Se>0&&Re>0&&(d.clearRect(0,0,c.width,c.height),Jt("drawClear"),A.forEach(v=>v()),Jt("draw")),st.show&&ft&&(Ha(st),ft=!1),ve&&Tt&&(ji(null,!0,!1),Tt=!1),q.show&&q.live&&Ve&&(ic(),Ve=!1),l||(l=!0,n.status=1,Jt("ready")),So=!1,Va=!1}n.redraw=(v,b)=>{Oe=b||!1,v!==!1?ci(I,z.min,z.max):vs()};function tc(v,b){let M=C[v];if(M.from==null){if(ir==0){let U=M.range(n,b.min,b.max,v);b.min=U[0],b.max=U[1]}if(b.min>b.max){let U=b.min;b.min=b.max,b.max=U}if(ir>1&&b.min!=null&&b.max!=null&&b.max-b.min<1e-16)return;v==I&&M.distr==2&&ir>0&&(b.min=In(b.min,e[0]),b.max=In(b.max,e[0]),b.min==b.max&&b.max++),V[v]=b,Ne=!0,vs()}}n.setScale=tc;let rc,nc,ws,Cs,ap,lp,bs,Ss,up,cp,it,pt,ui=!1;const sr=K.drag;let qt=sr.x,Qt=sr.y;ve&&(K.x&&(rc=on(MM,p)),K.y&&(nc=on(UM,p)),z.ori==0?(ws=rc,Cs=nc):(ws=nc,Cs=rc),it=K.left,pt=K.top);const st=n.select=zt({show:!0,over:!0,left:0,width:0,top:0,height:0},r.select),xs=st.show?on(EM,st.over?p:f):null;function Ha(v,b){if(st.show){for(let M in v)st[M]=v[M],M in oc&<(xs,M,v[M]);b!==!1&&Jt("setSelect")}}n.setSelect=Ha;function XC(v){if(g[v].show)oe&&yh(xe[v],Ji);else if(oe&&Wr(xe[v],Ji),ve){let M=Rn?hr[0]:hr[v];M!=null&&_n(M,-10,-10,pe,ne)}}function ci(v,b,M){tc(v,{min:b,max:M})}function zn(v,b,M,U){b.focus!=null&&JC(v),b.show!=null&&g.forEach((B,$)=>{$>0&&(v==$||v==null)&&(B.show=b.show,XC($),i==2?(ci(B.facets[0].scale,null,null),ci(B.facets[1].scale,null,null)):ci(B.scale,null,null),vs())}),M!==!1&&Jt("setSeries",v,b),U&&Mo("setSeries",n,v,b)}n.setSeries=zn;function KC(v,b){zt(x[v],b)}function ZC(v,b){v.fill=Pe(v.fill||null),v.dir=_e(v.dir,-1),b=b??x.length,x.splice(b,0,v)}function qC(v){v==null?x.length=0:x.splice(v,1)}n.addBand=ZC,n.setBand=KC,n.delBand=qC;function QC(v,b){g[v].alpha=b,ve&&hr[v]!=null&&(hr[v].style.opacity=b),oe&&xe[v]&&(xe[v].style.opacity=b)}let Wn,di,Hi;const Is={focus:!0};function JC(v){if(v!=Hi){let b=v==null,M=dr.alpha!=1;g.forEach((U,B)=>{if(i==1||B>0){let $=b||B==0||B==v;U._focus=b?null:$,M&&QC(B,$?1:dr.alpha)}}),Hi=v,M&&vs()}}oe&&Tn&&nt(bm,Ce,v=>{K._lock||(Br(v),Hi!=null&&zn(null,Is,!0,Bt.setSeries))});function Dn(v,b,M){let U=C[b];M&&(v=v/je-(U.ori==1?ht:$e));let B=pe;U.ori==1&&(B=ne,v=B-v),U.dir==-1&&(v=B-v);let $=U._min,Y=U._max,Z=v/B,re=$+(Y-$)*Z,ae=U.distr;return ae==3?lo(10,re):ae==4?YM(re,U.asinh):ae==100?U.bwd(re):re}function eb(v,b){let M=Dn(v,I,b);return In(M,e[0],Kt,Zt)}n.valToIdx=v=>In(v,e[0]),n.posToIdx=eb,n.posToVal=Dn,n.valToPos=(v,b,M)=>C[b].ori==0?s(v,C[b],M?Ee:pe,M?de:0):o(v,C[b],M?Me:ne,M?Ue:0),n.setCursor=(v,b,M)=>{it=v.left,pt=v.top,ji(null,b,M)};function dp(v,b){lt(xs,Us,st.left=v),lt(xs,Go,st.width=b)}function hp(v,b){lt(xs,_o,st.top=v),lt(xs,Xo,st.height=b)}let Io=z.ori==0?dp:hp,ko=z.ori==1?dp:hp;function tb(){if(oe&&q.live)for(let v=i==2?1:0;v<g.length;v++){if(v==0&&qe)continue;let b=q.values[v],M=0;for(let U in b)et[v][M++].firstChild.nodeValue=b[U]}}function ic(v,b){if(v!=null&&(v.idxs?v.idxs.forEach((M,U)=>{ee[U]=M}):KM(v.idx)||ee.fill(v.idx),q.idx=ee[0]),oe&&q.live){for(let M=0;M<g.length;M++)(M>0||i==1&&!qe)&&rb(M,ee[M]);tb()}Ve=!1,b!==!1&&Jt("setLegend")}n.setLegend=ic;function rb(v,b){let M=g[v],U=v==0&&P==2?gn:e[v],B;qe?B=M.values(n,v,b)??At:(B=M.value(n,b==null?null:U[b],v,b),B=B==null?At:{_:B}),q.values[v]=B}function ji(v,b,M){up=it,cp=pt,[it,pt]=K.move(n,it,pt),K.left=it,K.top=pt,ve&&(ws&&_n(ws,$t(it),0,pe,ne),Cs&&_n(Cs,0,$t(pt),pe,ne));let U,B=Kt>Zt;Wn=Qe,di=null;let $=z.ori==0?pe:ne,Y=z.ori==1?pe:ne;if(it<0||ir==0||B){U=K.idx=null;for(let Z=0;Z<g.length;Z++){let re=hr[Z];re!=null&&_n(re,-10,-10,pe,ne)}Tn&&zn(null,Is,!0,v==null&&Bt.setSeries),q.live&&(ee.fill(U),Ve=!0)}else{let Z,re,ae;i==1&&(Z=z.ori==0?it:pt,re=Dn(Z,I),U=K.idx=In(re,e[0],Kt,Zt),ae=O(e[0][U],z,$,0));let ue=-10,he=-10,Ie=0,He=0,Le=!0,Ae="",be="";for(let me=i==2?1:0;me<g.length;me++){let ot=g[me],Et=ee[me],er=Et==null?null:i==1?e[me][Et]:e[me][1][Et],Ze=K.dataIdx(n,me,U,re),Mt=Ze==null?null:i==1?e[me][Ze]:e[me][1][Ze];if(Ve=Ve||Mt!=er||Ze!=Et,ee[me]=Ze,me>0&&ot.show){let Vr=Ze==null?-10:Ze==U?ae:O(i==1?e[0][Ze]:e[me][0][Ze],z,$,0),br=Mt==null?-10:L(Mt,i==1?C[ot.scale]:C[ot.facets[1].scale],Y,0);if(Tn&&Mt!=null){let nn=z.ori==1?it:pt,mn=jt(dr.dist(n,me,Ze,br,nn));if(mn<Wn){let On=dr.bias;if(On!=0){let Hr=Dn(nn,ot.scale),sn=Mt>=0?1:-1,yn=Hr>=0?1:-1;yn==sn&&(yn==1?On==1?Mt>=Hr:Mt<=Hr:On==1?Mt<=Hr:Mt>=Hr)&&(Wn=mn,di=me)}else Wn=mn,di=me}}if(Ve||Rn){let nn,mn;z.ori==0?(nn=Vr,mn=br):(nn=br,mn=Vr);let On,Hr,sn,yn,Fn,Sr,jr=!0,Yi=Ct.bbox;if(Yi!=null){jr=!1;let xr=Yi(n,me);sn=xr.left,yn=xr.top,On=xr.width,Hr=xr.height}else sn=nn,yn=mn,On=Hr=Ct.size(n,me);if(Sr=Ct.fill(n,me),Fn=Ct.stroke(n,me),Rn)me==di&&Wn<=dr.prox&&(ue=sn,he=yn,Ie=On,He=Hr,Le=jr,Ae=Sr,be=Fn);else{let xr=hr[me];xr!=null&&(Pn[me]=sn,Bn[me]=yn,Um(xr,On,Hr,jr),Em(xr,Sr,Fn),_n(xr,an(sn),an(yn),pe,ne))}}}}if(Rn){let me=dr.prox,ot=Hi==null?Wn<=me:Wn>me||di!=Hi;if(Ve||ot){let Et=hr[0];Et!=null&&(Pn[0]=ue,Bn[0]=he,Um(Et,Ie,He,Le),Em(Et,Ae,be),_n(Et,an(ue),an(he),pe,ne))}}}if(st.show&&ui)if(v!=null){let[Z,re]=Bt.scales,[ae,ue]=Bt.match,[he,Ie]=v.cursor.sync.scales,He=v.cursor.drag;if(qt=He._x,Qt=He._y,qt||Qt){let{left:Le,top:Ae,width:be,height:me}=v.select,ot=v.scales[he].ori,Et=v.posToVal,er,Ze,Mt,Vr,br,nn=Z!=null&&ae(Z,he),mn=re!=null&&ue(re,Ie);nn&&qt?(ot==0?(er=Le,Ze=be):(er=Ae,Ze=me),Mt=C[Z],Vr=O(Et(er,he),Mt,$,0),br=O(Et(er+Ze,he),Mt,$,0),Io(En(Vr,br),jt(br-Vr))):Io(0,$),mn&&Qt?(ot==1?(er=Le,Ze=be):(er=Ae,Ze=me),Mt=C[re],Vr=L(Et(er,Ie),Mt,Y,0),br=L(Et(er+Ze,Ie),Mt,Y,0),ko(En(Vr,br),jt(br-Vr))):ko(0,Y)}else ac()}else{let Z=jt(up-ap),re=jt(cp-lp);if(z.ori==1){let Ie=Z;Z=re,re=Ie}qt=sr.x&&Z>=sr.dist,Qt=sr.y&&re>=sr.dist;let ae=sr.uni;ae!=null?qt&&Qt&&(qt=Z>=ae,Qt=re>=ae,!qt&&!Qt&&(re>Z?Qt=!0:qt=!0)):sr.x&&sr.y&&(qt||Qt)&&(qt=Qt=!0);let ue,he;qt&&(z.ori==0?(ue=bs,he=it):(ue=Ss,he=pt),Io(En(ue,he),jt(he-ue)),Qt||ko(0,Y)),Qt&&(z.ori==1?(ue=bs,he=it):(ue=Ss,he=pt),ko(En(ue,he),jt(he-ue)),qt||Io(0,$)),!qt&&!Qt&&(Io(0,0),ko(0,0))}if(sr._x=qt,sr._y=Qt,v==null){if(M){if(xp!=null){let[Z,re]=Bt.scales;Bt.values[0]=Z!=null?Dn(z.ori==0?it:pt,Z):null,Bt.values[1]=re!=null?Dn(z.ori==1?it:pt,re):null}Mo(Gc,n,it,pt,pe,ne,U)}if(Tn){let Z=M&&Bt.setSeries,re=dr.prox;Hi==null?Wn<=re&&zn(di,Is,!0,Z):Wn>re?zn(null,Is,!0,Z):di!=Hi&&zn(di,Is,!0,Z)}}Ve&&(q.idx=U,ic()),b!==!1&&Jt("setCursor")}let hi=null;Object.defineProperty(n,"rect",{get(){return hi==null&&Eo(!1),hi}});function Eo(v=!1){v?hi=null:(hi=p.getBoundingClientRect(),Jt("syncRect",hi))}function fp(v,b,M,U,B,$,Y){K._lock||ui&&v!=null&&v.movementX==0&&v.movementY==0||(sc(v,b,M,U,B,$,Y,!1,v!=null),v!=null?ji(null,!0,!0):ji(b,!0,!1))}function sc(v,b,M,U,B,$,Y,Z,re){if(hi==null&&Eo(!1),Br(v),v!=null)M=v.clientX-hi.left,U=v.clientY-hi.top;else{if(M<0||U<0){it=-10,pt=-10;return}let[ae,ue]=Bt.scales,he=b.cursor.sync,[Ie,He]=he.values,[Le,Ae]=he.scales,[be,me]=Bt.match,ot=b.axes[0].side%2==1,Et=z.ori==0?pe:ne,er=z.ori==1?pe:ne,Ze=ot?$:B,Mt=ot?B:$,Vr=ot?U:M,br=ot?M:U;if(Le!=null?M=be(ae,Le)?a(Ie,C[ae],Et,0):-10:M=Et*(Vr/Ze),Ae!=null?U=me(ue,Ae)?a(He,C[ue],er,0):-10:U=er*(br/Mt),z.ori==1){let nn=M;M=U,U=nn}}re&&(b==null||b.cursor.event.type==Gc)&&((M<=1||M>=pe-1)&&(M=qi(M,pe)),(U<=1||U>=ne-1)&&(U=qi(U,ne))),Z?(ap=M,lp=U,[bs,Ss]=K.move(n,M,U)):(it=M,pt=U)}const oc={width:0,height:0,left:0,top:0};function ac(){Ha(oc,!1)}let pp,gp,mp,yp;function vp(v,b,M,U,B,$,Y){ui=!0,qt=Qt=sr._x=sr._y=!1,sc(v,b,M,U,B,$,Y,!0,!1),v!=null&&(nt(Xc,gh,wp,!1),Mo(wm,n,bs,Ss,pe,ne,null));let{left:Z,top:re,width:ae,height:ue}=st;pp=Z,gp=re,mp=ae,yp=ue}function wp(v,b,M,U,B,$,Y){ui=sr._x=sr._y=!1,sc(v,b,M,U,B,$,Y,!1,!0);let{left:Z,top:re,width:ae,height:ue}=st,he=ae>0||ue>0,Ie=pp!=Z||gp!=re||mp!=ae||yp!=ue;if(he&&Ie&&Ha(st),sr.setScale&&he&&Ie){let He=Z,Le=ae,Ae=re,be=ue;if(z.ori==1&&(He=re,Le=ue,Ae=Z,be=ae),qt&&ci(I,Dn(He,I),Dn(He+Le,I)),Qt)for(let me in C){let ot=C[me];me!=I&&ot.from==null&&ot.min!=Qe&&ci(me,Dn(Ae+be,me),Dn(Ae,me))}ac()}else K.lock&&(K._lock=!K._lock,ji(b,!0,v!=null));v!=null&&(Cr(Xc,gh),Mo(Xc,n,it,pt,pe,ne,null))}function nb(v,b,M,U,B,$,Y){if(K._lock)return;Br(v);let Z=ui;if(ui){let re=!0,ae=!0,ue=10,he,Ie;z.ori==0?(he=qt,Ie=Qt):(he=Qt,Ie=qt),he&&Ie&&(re=it<=ue||it>=pe-ue,ae=pt<=ue||pt>=ne-ue),he&&re&&(it=it<bs?0:pe),Ie&&ae&&(pt=pt<Ss?0:ne),ji(null,!0,!0),ui=!1}it=-10,pt=-10,ee.fill(null),ji(null,!0,!0),Z&&(ui=Z)}function Cp(v,b,M,U,B,$,Y){K._lock||(Br(v),Hu(),ac(),v!=null&&Mo(Sm,n,it,pt,pe,ne,null))}function bp(){y.forEach(dU),Xt(n.width,n.height,!0)}ss(uu,Js,bp);const ks={};ks.mousedown=vp,ks.mousemove=fp,ks.mouseup=wp,ks.dblclick=Cp,ks.setSeries=(v,b,M,U)=>{let B=Bt.match[2];M=B(n,b,M),M!=-1&&zn(M,U,!0,!1)},ve&&(nt(wm,p,vp),nt(Gc,p,fp),nt(Cm,p,v=>{Br(v),Eo(!1)}),nt(bm,p,nb),nt(Sm,p,Cp),xh.add(n),n.syncRect=Eo);const ja=n.hooks=r.hooks||{};function Jt(v,b,M){ec?xo.push([v,b,M]):v in ja&&ja[v].forEach(U=>{U.call(null,n,b,M)})}(r.plugins||[]).forEach(v=>{for(let b in v.hooks)ja[b]=(ja[b]||[]).concat(v.hooks[b])});const Sp=(v,b,M)=>M,Bt=zt({key:null,setSeries:!1,filters:{pub:Bm,sub:Bm},scales:[I,g[1]?g[1].scale:null],match:[zm,zm,Sp],values:[null,null]},K.sync);Bt.match.length==2&&Bt.match.push(Sp),K.sync=Bt;const xp=Bt.key,lc=bC(xp);function Mo(v,b,M,U,B,$,Y){Bt.filters.pub(v,b,M,U,B,$,Y)&&lc.pub(v,b,M,U,B,$,Y)}lc.sub(n);function ib(v,b,M,U,B,$,Y){Bt.filters.sub(v,b,M,U,B,$,Y)&&ks[v](null,b,M,U,B,$,Y)}n.pub=ib;function sb(){lc.unsub(n),xh.delete(n),kt.clear(),vh(uu,Js,bp),u.remove(),Ce==null||Ce.remove(),Jt("destroy")}n.destroy=sb;function uc(){Jt("init",r,e),Jf(e||r.data,!1),V[I]?tc(I,V[I]):Hu(),ft=st.show&&(st.width>0||st.height>0),Tt=Ve=!0,Xt(r.width,r.height)}return g.forEach(Pt),y.forEach(FC),t?t instanceof HTMLElement?(t.appendChild(u),uc()):t(n,uc):uc(),n}yr.assign=zt;yr.fmtNum=Nf;yr.rangeNum=cu;yr.rangeLog=Ou;yr.rangeAsinh=_f;yr.orient=ps;yr.pxRatio=je;yr.join=r5;yr.fmtDate=Hf,yr.tzDate=f5;yr.sync=bC;{yr.addGap=K5,yr.clipGaps=_u;let r=yr.paths={points:MC};r.linear=AC,r.stepped=Q5,r.bars=J5,r.spline=tU}function hU(r,e){const t=/^#([0-9a-fA-F]{6})([0-9a-fA-F]{2})?$/.exec(r.trim());return t?`#${t[1]}${e}`:r}function BC({data:r,seriesKeys:e,seriesLabels:t,colors:n,height:i=300,tickRate:s=60,windowSeconds:o=20,hoveredKey:a=null,onHoverKey:l}){const u=N.useRef(null),c=N.useRef(null),d=N.useRef(null),h=N.useMemo(()=>e.join("|"),[e]),f=N.useMemo(()=>{const w=Math.max(1,Math.round(o*s)),g=Math.max(0,r.length-w),y=r.slice(g),C=Math.max(0,w-y.length),x=new Array(w);for(let E=0;E<w;E++)x[E]=E;const I=e.map(()=>new Array(w).fill(0));for(let E=0;E<y.length;E++){const A=y[E],R=C+E;for(let F=0;F<e.length;F++){const z=e[F],P=Number(A[z]??0);I[F][R]=Number.isFinite(P)?P:0}}return{x,series:I,windowPoints:w}},[r,e,s,o]),p=N.useMemo(()=>[f.x,...f.series],[f]),m=N.useMemo(()=>{const w=typeof globalThis.devicePixelRatio=="number"?globalThis.devicePixelRatio:1,g=[{label:"t"},...e.map((y,C)=>{const x=n[C%n.length]??"#4fc1ff";return{label:t[y]??y,stroke:x,width:2,points:{show:!1}}})];return{width:800,height:i,pxAlign:0,pxRatio:w,padding:[10,10,10,10],scales:{x:{time:!1},y:{}},axes:[{stroke:"#555",grid:{stroke:"#222",width:1},size:0,values:(y,C)=>C.map(()=>"")},{stroke:"#555",grid:{stroke:"#222",width:1}}],series:g,legend:{show:!1},cursor:{drag:{x:!1,y:!1}},hooks:{setCursor:[y=>{var F;if(!l)return;const C=y.cursor.idx;if(C==null||C<0){d.current!==null&&(d.current=null,l(null));return}const x=y.cursor.top;if(x==null||!Number.isFinite(x)){d.current!==null&&(d.current=null,l(null));return}let I=null,E=Number.POSITIVE_INFINITY;for(let z=1;z<y.series.length;z++){const P=e[z-1],O=(F=y.data[z])==null?void 0:F[C];if(O==null||!Number.isFinite(O))continue;const L=y.valToPos(O,"y",!0),V=Math.abs(L-x);V<E&&(E=V,I=P)}const R=E<=12?I:null;d.current!==R&&(d.current=R,l(R))}]}}},[n,i,l,e,t]),S=N.useMemo(()=>e.map((w,g)=>{const y=n[g%n.length]??"#4fc1ff",C=a!=null&&a===w;return{stroke:a!=null&&a!==w?hU(y,"66"):y,width:C?3:2}}),[n,a,e]);return N.useEffect(()=>{var I;const w=u.current;if(!w)return;const g=()=>{l&&d.current!==null&&(d.current=null,l(null))};w.addEventListener("mouseleave",g),(I=c.current)==null||I.destroy(),c.current=null;const y=new yr(m,p,w);c.current=y;const C=new ResizeObserver(()=>{const E=w.getBoundingClientRect();y.setSize({width:Math.max(1,Math.floor(E.width)),height:i})});C.observe(w);const x=w.getBoundingClientRect();return y.setSize({width:Math.max(1,Math.floor(x.width)),height:i}),()=>{w.removeEventListener("mouseleave",g),C.disconnect(),y.destroy(),c.current=null}},[m,p,i,l,h]),N.useEffect(()=>{var w;(w=c.current)==null||w.setData(p)},[p]),N.useEffect(()=>{const w=c.current;if(w)for(let g=0;g<S.length;g++){const y=g+1,C=S[g],x=w.series[y];!x||!C||(x.stroke!==C.stroke||x.width!==C.width)&&w.setSeries(y,{stroke:C.stroke,width:C.width})}},[S]),k.jsx("div",{ref:u,style:{width:"100%",height:i}})}const Dr=(r,e)=>r===e?0:r<e?-1:1,ry=(r,e)=>r.localeCompare(e,void 0,{numeric:!0}),gl=r=>(r??"").trim();function fU({sortedTraffic:r,topTraffic:e,chartData:t,topKeys:n,keyToLabel:i,keyToColor:s,tickRate:o,hoveredTrafficKey:a,setHoveredTrafficKey:l}){const[u,c]=N.useState("bps"),[d,h]=N.useState("desc"),[f,p]=N.useState("bps"),[m,S]=N.useState("desc"),[w,g]=N.useState("bps"),[y,C]=N.useState("desc"),x=T=>{if(T===u){h(_=>_==="asc"?"desc":"asc");return}c(T),h(T==="name"?"asc":"desc")},I=T=>{if(T===w){C(_=>_==="asc"?"desc":"asc");return}g(T),C(T==="name"?"asc":"desc")},E=T=>{if(T===f){S(_=>_==="asc"?"desc":"asc");return}p(T),S(T==="name"?"asc":"desc")},A=(T,_,j)=>{const G=j==="asc"?1:-1,ee=[...T];return ee.sort((q,K)=>{let oe=0;switch(_){case"id":oe=Dr(q.id,K.id);break;case"name":{const ve=gl(q.name),ge=gl(K.name);oe=ry(ve,ge),oe===0&&(oe=Dr(q.id,K.id));break}case"encoding":{const ve=gl(q.encoding),ge=gl(K.encoding);oe=ry(ve,ge),oe===0&&(oe=Dr(q.id,K.id));break}case"bps":oe=Dr(q.bps,K.bps),oe===0&&(oe=Dr(q.total,K.total));break;case"total":oe=Dr(q.total,K.total),oe===0&&(oe=Dr(q.bps,K.bps));break;case"size":{const ve=q.size.x*q.size.y,ge=K.size.x*K.size.y;oe=Dr(ve,ge),oe===0&&(oe=Dr(q.id,K.id));break}case"position":{oe=Dr(q.position.x,K.position.x),oe===0&&(oe=Dr(q.position.y,K.position.y)),oe===0&&(oe=Dr(q.id,K.id));break}case"zIndex":oe=Dr(q.zIndex,K.zIndex),oe===0&&(oe=Dr(q.id,K.id));break}return oe*G}),ee},R=N.useMemo(()=>r.filter(T=>T.key.startsWith("layer-")),[r]),F=N.useMemo(()=>r.filter(T=>T.key.startsWith("misc-")),[r]),z=N.useMemo(()=>r.filter(T=>T.key.startsWith("display-")),[r]),P=N.useMemo(()=>A(R,u,d),[R,d,u]),O=N.useMemo(()=>A(F,w,y),[F,y,w]),L=N.useMemo(()=>A(z,f,m),[z,m,f]),V={userSelect:"none",cursor:"pointer"},X=(T,_,j)=>T!==_?"":j==="asc"?" ▲":" ▼";return k.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",gap:12,padding:12,overflow:"auto",background:"#1b1b1b",color:"#cccccc"},children:[k.jsx("div",{style:{fontSize:13,color:"#e0e0e0",fontWeight:600},children:"Bandwidth"}),R.length===0&&F.length===0&&k.jsx("div",{style:{color:"#888",fontSize:12},children:"No bandwidth data yet. Move the client or send data to see traffic."}),R.length>0&&e.length>0&&k.jsxs("div",{style:{width:"100%",height:300,border:"1px solid #333",background:"#111",padding:"8px 12px 12px",boxSizing:"border-box"},children:[k.jsx("div",{style:{marginBottom:8,color:"#aaa",fontSize:12},children:"Lines — per-layer bandwidth (B/s, last samples)"}),k.jsx(BC,{data:t,seriesKeys:n,seriesLabels:i,colors:n.map(T=>s[T]??"#4fc1ff"),height:260,tickRate:o,windowSeconds:60,hoveredKey:a,onHoverKey:l})]}),R.length>0&&k.jsxs("div",{style:{border:"1px solid #333",background:"#111",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{color:"#aaa",fontSize:12,marginBottom:2},children:"Layers"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1.1fr 0.55fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,color:"#aaa",fontSize:12},children:[k.jsxs("div",{style:V,onClick:()=>x("id"),title:"Sort by ID",children:["ID",X("id",u,d)]}),k.jsxs("div",{style:V,onClick:()=>x("name"),title:"Sort by name",children:["Name",X("name",u,d)]}),k.jsxs("div",{style:V,onClick:()=>x("encoding"),title:"Sort by encoding",children:["Encoding",X("encoding",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("bps"),title:"Sort by Network/s",children:["Network/s",X("bps",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("total"),title:"Sort by Network",children:["Network",X("total",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("size"),title:"Sort by size",children:["Size",X("size",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("position"),title:"Sort by position",children:["Position",X("position",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("zIndex"),title:"Sort by zIndex",children:["zIndex",X("zIndex",u,d)]})]}),P.map(T=>k.jsxs("div",{onMouseEnter:()=>l(T.key),onMouseLeave:()=>l(null),style:{display:"grid",gridTemplateColumns:"70px 1.1fr 0.55fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,fontSize:12,color:a===T.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===T.key?"#1a1a1a":"transparent",outline:a===T.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:T.id}),k.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:2,marginRight:8,verticalAlign:"middle",background:s[T.key]??"#666",boxShadow:a===T.key?`0 0 0 1px #000, 0 0 0 2px ${s[T.key]??"#666"}`:"0 0 0 1px #000"}}),(()=>{var j;const _=((j=T.name)==null?void 0:j.trim())||`Layer ${T.id}`;return T.id===255?`${_} (debug)`:_})()]}),k.jsx("div",{style:{color:"#bbb"},children:T.encoding??""}),k.jsxs("div",{style:{textAlign:"right"},children:[Kr(T.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Kr(T.total)}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.size.x,"×",T.size.y]}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.position.x,"/",T.position.y]}),k.jsx("div",{style:{textAlign:"right",color:"#999"},children:T.zIndex})]},T.key))]}),z.length>0&&k.jsxs("div",{style:{border:"1px solid #333",background:"#111",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{color:"#aaa",fontSize:12,marginBottom:2},children:"Displays"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,color:"#aaa",fontSize:12},children:[k.jsxs("div",{style:V,onClick:()=>E("id"),title:"Sort by ID",children:["ID",X("id",f,m)]}),k.jsxs("div",{style:V,onClick:()=>E("name"),title:"Sort by name",children:["Name",X("name",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("bps"),title:"Sort by Network/s",children:["Network/s",X("bps",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("total"),title:"Sort by Network",children:["Network",X("total",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("size"),title:"Sort by size",children:["Size",X("size",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("position"),title:"Sort by position",children:["Position",X("position",f,m)]}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"zIndex"})]}),L.map(T=>{var _;return k.jsxs("div",{onMouseEnter:()=>l(T.key),onMouseLeave:()=>l(null),style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,fontSize:12,color:a===T.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===T.key?"#1a1a1a":"transparent",outline:a===T.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:T.id}),k.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:2,marginRight:8,verticalAlign:"middle",background:s[T.key]??"#666",boxShadow:a===T.key?`0 0 0 1px #000, 0 0 0 2px ${s[T.key]??"#666"}`:"0 0 0 1px #000"}}),((_=T.name)==null?void 0:_.trim())||`Display ${T.id}`]}),k.jsxs("div",{style:{textAlign:"right"},children:[Kr(T.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Kr(T.total)}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.size.x,"×",T.size.y]}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.position.x,"/",T.position.y]}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"})]},T.key)})]}),F.length>0&&k.jsxs("div",{style:{border:"1px solid #333",background:"#111",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{color:"#aaa",fontSize:12,marginBottom:2},children:"Updates (non-layer)"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,color:"#aaa",fontSize:12},children:[k.jsxs("div",{style:V,onClick:()=>I("id"),title:"Sort by ID",children:["ID",X("id",w,y)]}),k.jsxs("div",{style:V,onClick:()=>I("name"),title:"Sort by name",children:["Name",X("name",w,y)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>I("bps"),title:"Sort by Network/s",children:["Network/s",X("bps",w,y)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>I("total"),title:"Sort by Network",children:["Network",X("total",w,y)]}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"Size"}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"Position"}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"zIndex"})]}),O.map(T=>k.jsxs("div",{onMouseEnter:()=>l(T.key),onMouseLeave:()=>l(null),style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,fontSize:12,color:a===T.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===T.key?"#1a1a1a":"transparent",outline:a===T.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:T.id}),k.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:2,marginRight:8,verticalAlign:"middle",background:s[T.key]??"#666",boxShadow:a===T.key?`0 0 0 1px #000, 0 0 0 2px ${s[T.key]??"#666"}`:"0 0 0 1px #000"}}),T.name??"—"]}),k.jsxs("div",{style:{textAlign:"right"},children:[Kr(T.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Kr(T.total)}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"})]},T.key))]})]})}const tr=65536,Jc=.005,ed=32;function pU({layers:r,displays:e=[],width:t,height:n,hoveredLayerId:i=null,selectedLayerIds:s=null,hoveredDisplayId:o=null,selectedDisplayId:a=null,focusRect:l=null,focusKey:u="",onSelectLayer:c,onSelectDisplay:d,onToolRectCommit:h}){const f=N.useRef(null),[p,m]=N.useState(1),[S,w]=N.useState({x:0,y:0}),g=N.useRef(!1),y=N.useRef({x:0,y:0}),C=N.useRef(""),[x,I]=N.useState(!1),[E,A]=N.useState(null),[R,F]=N.useState(null),[z,P]=N.useState("none"),[O,L]=N.useState(null),V=N.useRef(null),[X,T]=N.useState(!1),_=N.useRef(!1),j=N.useRef(!1),G=N.useCallback((Q,W,le)=>{const ye=t/le,de=n/le,Ue=ye*.5,Ee=de*.5,Me=Math.max(0,tr-ye)+Ue,Ne=Math.max(0,tr-de)+Ee,we=-Ue,Oe=-Ee;return{x:Math.max(we,Math.min(Me,Q)),y:Math.max(Oe,Math.min(Ne,W))}},[t,n]),ee=N.useCallback(()=>{const Q=tr*p,W=tr*p,le=Q<t?(t-Q)/2:0,ye=W<n?(n-W)/2:0;return{toScreenX:Ne=>(Ne-S.x)*p+le,toScreenY:Ne=>(Ne-S.y)*p+ye,toWorldX:Ne=>(Ne-le)/p+S.x,toWorldY:Ne=>(Ne-ye)/p+S.y}},[n,S.x,S.y,p,t]),q=N.useCallback((Q,W)=>{let le=null;for(let ye=0;ye<r.length;ye++){const de=r[ye];if(Q<de.x||Q>de.x+de.width||W<de.y||W>de.y+de.height)continue;const Ue=de.zIndex??0;(!le||Ue>le.z)&&(le={id:de.id,z:Ue})}if(le)return{kind:"layer",id:le.id,zIndex:le.z};for(let ye=e.length-1;ye>=0;ye--){const de=e[ye];if(Q>=de.x&&Q<=de.x+de.width&&W>=de.y&&W<=de.y+de.height)return{kind:"display",id:de.id}}return null},[e,r]),K=N.useCallback((Q,W)=>{const le=[];for(let ye=0;ye<r.length;ye++){const de=r[ye];Q<de.x||Q>de.x+de.width||W<de.y||W>de.y+de.height||le.push({id:de.id,zIndex:de.zIndex??0,name:de.name})}return le.sort((ye,de)=>de.zIndex-ye.zIndex),le},[r]);N.useEffect(()=>{const Q=f.current;if(!Q)return;const W=Q.getContext("2d");if(!W)return;W.clearRect(0,0,t,n),W.fillStyle="#0a0e14",W.fillRect(0,0,t,n);const le=tr*p,ye=tr*p,de=le<t?(t-le)/2:0,Ue=ye<n?(n-ye)/2:0,Ee=we=>(we-S.x)*p+de,Me=we=>(we-S.y)*p+Ue;{const we=Ee(0),Oe=Ee(tr),Tt=Me(0),ft=Me(tr),Ve=Math.max(0,we),Xt=Math.min(t,Oe),Lt=Math.max(0,Tt),ai=Math.min(n,ft);if(!(Xt<=Ve||ai<=Lt)){const Li=[{step:1,alpha:.06,lineWidth:1,minGapPx:8},{step:16,alpha:.1,lineWidth:1,minGapPx:10},{step:256,alpha:.16,lineWidth:1.25,minGapPx:12},{step:4096,alpha:.22,lineWidth:1.5,minGapPx:14}];W.save(),W.beginPath(),W.rect(Ve,Lt,Xt-Ve,ai-Lt),W.clip();let _i=!1;for(const Fe of Li){if(Fe.step*p<Fe.minGapPx)continue;_i=!0,W.strokeStyle=`rgba(255,255,255,${Fe.alpha})`,W.lineWidth=Fe.lineWidth;const Br=bt=>(bt-de)/p+S.x,Ct=bt=>(bt-Ue)/p+S.y,dr=Math.max(0,Br(0)),Tn=Math.min(tr,Br(t)),Rn=Math.max(0,Ct(0)),hr=Math.min(tr,Ct(n)),Pn=Math.floor(dr/Fe.step)*Fe.step,Bn=Math.ceil(Tn/Fe.step)*Fe.step,gs=Math.floor(Rn/Fe.step)*Fe.step,Pt=Math.ceil(hr/Fe.step)*Fe.step;W.beginPath();for(let bt=Pn;bt<=Bn;bt+=Fe.step){if(bt<0||bt>tr)continue;const Ni=Ee(bt);W.moveTo(Ni,Lt),W.lineTo(Ni,ai)}for(let bt=gs;bt<=Pt;bt+=Fe.step){if(bt<0||bt>tr)continue;const Ni=Me(bt);W.moveTo(Ve,Ni),W.lineTo(Xt,Ni)}W.stroke()}if(!_i){const Fe=Li[Li.length-1];W.strokeStyle=`rgba(255,255,255,${Fe.alpha})`,W.lineWidth=Fe.lineWidth;const $i=Pt=>(Pt-de)/p+S.x,Br=Pt=>(Pt-Ue)/p+S.y,Ct=Math.max(0,$i(0)),dr=Math.min(tr,$i(t)),Tn=Math.max(0,Br(0)),Rn=Math.min(tr,Br(n)),hr=Math.floor(Ct/Fe.step)*Fe.step,Pn=Math.ceil(dr/Fe.step)*Fe.step,Bn=Math.floor(Tn/Fe.step)*Fe.step,gs=Math.ceil(Rn/Fe.step)*Fe.step;W.beginPath();for(let Pt=hr;Pt<=Pn;Pt+=Fe.step){if(Pt<0||Pt>tr)continue;const bt=Ee(Pt);W.moveTo(bt,Lt),W.lineTo(bt,ai)}for(let Pt=Bn;Pt<=gs;Pt+=Fe.step){if(Pt<0||Pt>tr)continue;const bt=Me(Pt);W.moveTo(Ve,bt),W.lineTo(Xt,bt)}W.stroke()}W.restore()}}const Ne=[...r].sort((we,Oe)=>(we.zIndex??0)-(Oe.zIndex??0));for(const we of Ne){const Oe=s!=null&&s.includes(we.id),Tt=i!=null&&we.id===i,ft=Ee(we.x),Ve=Me(we.y),Xt=we.width*p,Lt=we.height*p;if(ft+Xt<0||Ve+Lt<0||ft>t||Ve>n)continue;const ai=we.zIndex??0,Li=we.color??(Oe?"rgba(43, 140, 255, 0.60)":Tt?"rgba(102, 217, 239, 0.40)":"rgba(43, 140, 255, 0.42)");if(W.fillStyle=Li,W.fillRect(ft,Ve,Math.max(Xt,1),Math.max(Lt,1)),W.strokeStyle=Oe?"#66d9ef":Tt?"rgba(102, 217, 239, 0.70)":"rgba(255,255,255,0.30)",W.lineWidth=Oe?2:1,W.strokeRect(ft,Ve,Math.max(Xt,1),Math.max(Lt,1)),p>=3&&Xt>=40&&Lt>=16){W.font="11px monospace",W.textBaseline="top";const _i=`z=${ai}`,Fe=4,$i=3,Ct=W.measureText(_i).width+Fe*2,dr=14;W.fillStyle="rgba(0,0,0,0.55)",W.fillRect(ft+3,Ve+3,Ct,dr),W.fillStyle="rgba(255,255,255,0.85)",W.fillText(_i,ft+3+Fe,Ve+3+$i)}}for(const we of e){const Oe=a!=null&&we.id===a,Tt=o!=null&&we.id===o,ft=Ee(we.x),Ve=Me(we.y),Xt=we.width*p,Lt=we.height*p;ft+Xt<0||Ve+Lt<0||ft>t||Ve>n||(W.strokeStyle=Oe?"rgba(255, 120, 120, 1)":Tt?"rgba(255, 120, 120, 0.8)":"rgba(255, 80, 80, 0.9)",W.lineWidth=Oe?3:2,W.strokeRect(ft,Ve,Math.max(Xt,1),Math.max(Lt,1)))}if(O){const we=Ee(O.x),Oe=Me(O.y),Tt=O.width*p,ft=O.height*p;W.strokeStyle="rgba(43, 140, 255, 1)",W.lineWidth=2,W.setLineDash([6,4]),W.strokeRect(we,Oe,Math.max(Tt,1),Math.max(ft,1)),W.setLineDash([])}},[r,e,t,n,p,S,i,s,o,a,O]);const oe=N.useCallback((Q,W)=>{var we;const le=(we=f.current)==null?void 0:we.getBoundingClientRect();if(!le)return null;const ye=Q-le.left,de=W-le.top,{toWorldX:Ue,toWorldY:Ee}=ee(),Me=Ue(ye),Ne=Ee(de);return{x:Me,y:Ne}},[ee]),ve=N.useCallback((Q,W)=>{const le=Math.floor(Math.min(Q.x,W.x)),ye=Math.floor(Math.min(Q.y,W.y)),de=Math.ceil(Math.max(Q.x,W.x)),Ue=Math.ceil(Math.max(Q.y,W.y));return{x:le,y:ye,width:Math.max(1,de-le),height:Math.max(1,Ue-ye)}},[]);N.useEffect(()=>{if(!l){C.current="";return}const Q=`${u}-${l.id}-${l.x}-${l.y}-${l.width}-${l.height}-${t}-${n}`;if(Q===C.current)return;if(j.current){j.current=!1,C.current=Q;return}C.current=Q;const W=1.25,le=Math.max(Jc,Math.min(ed,Math.min(t/(l.width*W),n/(l.height*W)))),ye=t/le,de=n/le,Ue=l.x+l.width/2,Ee=l.y+l.height/2,Me=G(Ue-ye/2,Ee-de/2,le);m(le),w(Me)},[l,u,t,n,G]);const ge=N.useCallback(Q=>{var Lt;const W=(Lt=f.current)==null?void 0:Lt.getBoundingClientRect();if(!W)return;Q.preventDefault();const le=Q.clientX-W.left,ye=Q.clientY-W.top,{toWorldX:de,toWorldY:Ue}=ee(),Ee=de(le),Me=Ue(ye),Ne=Q.deltaY<0?1.15:1/1.15,we=Math.max(Jc,Math.min(ed,p*Ne)),Oe=tr*we,Tt=tr*we,ft=Oe<t?(t-Oe)/2:0,Ve=Tt<n?(n-Tt)/2:0,Xt=G(Ee-(le-ft)/we,Me-(ye-Ve)/we,we);m(we),w(Xt)},[G,ee,n,S,p,t]);N.useEffect(()=>{const Q=f.current;if(!Q)return;const W=le=>ge(le);return Q.addEventListener("wheel",W,{passive:!1}),()=>Q.removeEventListener("wheel",W)},[ge]);const Ce=N.useCallback(Q=>{g.current=!0,I(!0),y.current={x:Q.clientX,y:Q.clientY}},[]),ct=N.useCallback(()=>{g.current=!1,I(!1)},[]),dt=N.useCallback(()=>{g.current=!1,I(!1),A(null)},[]),xe=N.useCallback(Q=>{const W=oe(Q.clientX,Q.clientY);if(!W||z!=="rect"||!h)return;Q.preventDefault(),Q.stopPropagation(),_.current=!0;const le={x:Math.floor(W.x),y:Math.floor(W.y)};V.current={startWorld:le,moved:!1},T(!0),L({x:le.x,y:le.y,width:1,height:1})},[z,oe,h]),et=N.useCallback(Q=>{if(!V.current)return;const W=oe(Q.clientX,Q.clientY);if(!W)return;const le=ve(V.current.startWorld,W);if(!V.current.moved){const ye=Math.abs(W.x-V.current.startWorld.x),de=Math.abs(W.y-V.current.startWorld.y);(ye>0||de>0)&&(V.current.moved=!0)}L(le)},[oe,ve]),Ke=N.useCallback(()=>{!V.current||!O||(_.current=!0,h==null||h(O),j.current=!0,V.current=null,L(null),T(!1),P("none"))},[O,h]),qe=N.useCallback(Q=>{if(V.current){if(Q.preventDefault(),Q.stopPropagation(),!V.current.moved){_.current=!0,V.current=null,L(null),T(!1),P("none");return}Ke()}},[Ke]);N.useEffect(()=>{if(!X)return;const Q=le=>{et(le)},W=le=>{qe(le)};return window.addEventListener("mousemove",Q,!0),window.addEventListener("mouseup",W,!0),()=>{window.removeEventListener("mousemove",Q,!0),window.removeEventListener("mouseup",W,!0)}},[X,et,qe]),N.useEffect(()=>{if(!V.current)return;const Q=W=>{W.key==="Enter"&&Ke()};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[Ke]);const At=N.useCallback(Q=>{var we;if(V.current){et(Q);return}if(g.current){const Oe=Q.clientX-y.current.x,Tt=Q.clientY-y.current.y;y.current={x:Q.clientX,y:Q.clientY},w(ft=>G(ft.x-Oe/p,ft.y-Tt/p,p));return}const W=(we=f.current)==null?void 0:we.getBoundingClientRect();if(!W)return;const le=Q.clientX-W.left,ye=Q.clientY-W.top,{toWorldX:de,toWorldY:Ue}=ee(),Ee=Math.floor(de(le)),Me=Math.floor(Ue(ye)),Ne=q(Ee,Me);if(!Ne){A({kind:"layer",id:-1,world:{x:Ee,y:Me},screen:{x:le,y:ye}});return}A({kind:Ne.kind,id:Ne.id,world:{x:Ee,y:Me},screen:{x:le,y:ye}})},[G,ee,q,p]),wt=N.useCallback(Q=>{var Oe;if(_.current){_.current=!1;return}if(z==="rect"||V.current||x)return;const W=(Oe=f.current)==null?void 0:Oe.getBoundingClientRect();if(!W)return;const le=Q.clientX-W.left,ye=Q.clientY-W.top,{toWorldX:de,toWorldY:Ue}=ee(),Ee=Math.floor(de(le)),Me=Math.floor(Ue(ye)),Ne=K(Ee,Me);if(Ne.length>=2){F({open:!0,anchorScreen:{x:le,y:ye},world:{x:Ee,y:Me},layers:Ne});return}const we=q(Ee,Me);we&&(we.kind==="layer"&&(c==null||c(we.id,{metaKey:Q.metaKey,ctrlKey:Q.ctrlKey})),we.kind==="display"&&(d==null||d(we.id)))},[z,ee,q,K,x,d,c]);N.useEffect(()=>{const Q=W=>{W.key==="Escape"&&F(null)};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[]);const Ft=N.useCallback(()=>{m(1),w(G(0,0,1))},[G]),cr=N.useCallback(Q=>{var Oe;const W=(Oe=f.current)==null?void 0:Oe.getBoundingClientRect();if(!W)return;const le=W.width/2,ye=W.height/2,{toWorldX:de,toWorldY:Ue}=ee(),Ee=de(le),Me=Ue(ye),Ne=Math.max(Jc,Math.min(ed,p*Q)),we=G(Ee-le/Ne,Me-ye/Ne,Ne);m(Ne),w(we)},[G,ee,p]),tt=E&&E.id!==-1?E:null,kt=n<520?6:10,nt=Math.max(40,n-kt*2),Cr=88,Se=42,Re=nt<150,pe=nt<240,ne=nt<200,$e=Math.min(1,Math.max(.7,nt/(Re?64:Cr))),ht=Math.min(1,Math.max(.7,nt/Se));return k.jsxs("div",{style:{position:"absolute",inset:0},children:[k.jsx("canvas",{ref:f,width:t,height:n,style:{display:"block",cursor:z==="rect"?(V.current,"crosshair"):g.current?"grabbing":"grab"},onMouseDown:Q=>{if(z==="rect"&&h){xe(Q);return}Ce(Q)},onMouseMove:At,onMouseUp:Q=>{if(V.current){qe(Q);return}ct()},onMouseLeave:dt,onClick:wt}),k.jsxs("div",{style:{position:"absolute",right:kt,bottom:pe?void 0:kt,top:pe?kt:void 0,display:"flex",flexDirection:Re?"row":"column",alignItems:"center",gap:6,padding:6,background:"rgba(20, 22, 26, 0.85)",border:"1px solid rgba(255,255,255,0.14)",borderRadius:10,boxShadow:"0 10px 26px rgba(0,0,0,0.45)",pointerEvents:"auto",transform:$e===1?void 0:`scale(${$e})`,transformOrigin:pe?"top right":"bottom right",maxWidth:`calc(100% - ${kt*2}px)`},onMouseDown:Q=>Q.stopPropagation(),children:[k.jsx("button",{onClick:()=>{const Q=z==="rect"?"none":"rect";V.current=null,T(!1),P(Q)},style:{width:34,height:34,borderRadius:8,border:z==="rect"?"1px solid rgba(79, 193, 255, 0.9)":"1px solid rgba(255,255,255,0.18)",background:z==="rect"?"rgba(14, 99, 156, 0.7)":"rgba(255,255,255,0.06)",color:"#e6e6e6",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:0},title:z==="rect"?"Rectangle tool (active)":"Rectangle tool",children:k.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:k.jsx("rect",{x:"5",y:"7",width:"14",height:"10",rx:"1"})})}),k.jsx("button",{onClick:()=>{V.current=null,T(!1),P("none")},style:{width:34,height:34,borderRadius:8,border:"1px solid rgba(255,255,255,0.18)",background:z==="none"?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.06)",color:"#e6e6e6",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:0},title:"Drag/Pan",children:"↔"})]}),(R==null?void 0:R.open)&&R.layers.length>=2&&k.jsxs("div",{style:{position:"absolute",left:Math.min(t-220,R.anchorScreen.x+12),top:Math.min(n-260,R.anchorScreen.y-12),width:210,padding:8,background:"rgba(10, 12, 16, 0.94)",border:"1px solid rgba(255,255,255,0.14)",borderRadius:10,boxShadow:"0 10px 30px rgba(0,0,0,0.55)",color:"#e6e6e6",fontSize:12},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[k.jsx("div",{style:{fontWeight:700},children:"Stack"}),k.jsx("button",{onClick:()=>F(null),style:{...ml,padding:"2px 6px",borderRadius:8},title:"Close",children:"✕"})]}),k.jsxs("div",{style:{color:"#9aa7b2",marginTop:4},children:["World: ",R.world.x.toFixed(0),",",R.world.y.toFixed(0)]}),k.jsx("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:6,maxHeight:220,overflow:"auto",paddingRight:2},children:R.layers.map((Q,W)=>{var le;return k.jsx("button",{onClick:ye=>{c==null||c(Q.id,{metaKey:ye.metaKey,ctrlKey:ye.ctrlKey}),F(null)},style:{textAlign:"left",width:"100%",background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.10)",borderRadius:10,padding:"8px 10px",cursor:"pointer",color:"#e6e6e6",position:"relative"},title:"Select layer",children:k.jsxs("div",{style:{fontWeight:650},children:[(le=Q.name)!=null&&le.trim()?Q.name:`Layer ${Q.id}`," ",k.jsxs("span",{style:{color:"#9aa7b2",fontWeight:500},children:["z=",Q.zIndex]}),W===0&&k.jsx("span",{style:{marginLeft:6,color:"#66d9ef",fontWeight:650},children:"top"})]})},Q.id)})})]}),k.jsxs("div",{style:{position:"absolute",top:10,left:10,display:"flex",gap:6,padding:6,background:"rgba(15, 18, 24, 0.85)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,backdropFilter:"blur(6px)",fontSize:12,color:"#cfcfcf"},children:[k.jsx("button",{onClick:()=>cr(1.15),style:ml,title:"Zoom in",children:"+"}),k.jsx("button",{onClick:()=>cr(1/1.15),style:ml,title:"Zoom out",children:"−"}),k.jsx("button",{onClick:Ft,style:ml,title:"Reset view",children:"Reset"})]}),k.jsxs("div",{style:{position:"absolute",left:kt,bottom:ne?void 0:kt,top:ne?kt:void 0,padding:"6px 8px",background:"rgba(15, 18, 24, 0.75)",border:"1px solid rgba(255,255,255,0.10)",borderRadius:8,backdropFilter:"blur(6px)",fontSize:12,color:"#cfcfcf",transform:ht===1?void 0:`scale(${ht})`,transformOrigin:ne?"top left":"bottom left",maxWidth:`calc(100% - ${kt*2}px)`,overflow:"hidden",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{color:"#9aa7b2"},children:"Zoom:"})," ",p.toFixed(3),"x"," ",k.jsx("span",{style:{color:"#9aa7b2"},children:"| Offset:"})," (",S.x.toFixed(0),","," ",S.y.toFixed(0),")",E&&k.jsxs(k.Fragment,{children:[k.jsx("span",{style:{color:"#9aa7b2"},children:"| Mouse:"})," (",E.world.x.toFixed(0),",",E.world.y.toFixed(0),")"]})]}),tt&&k.jsxs("div",{style:{position:"absolute",left:Math.min(t-260,tt.screen.x+12),top:Math.min(n-80,tt.screen.y+12),width:240,padding:"8px 10px",background:"rgba(10, 12, 16, 0.92)",border:"1px solid rgba(255,255,255,0.14)",borderRadius:8,fontSize:12,color:"#e6e6e6",pointerEvents:"none"},children:[k.jsx("div",{style:{fontWeight:600,marginBottom:4},children:tt.kind==="layer"?`Layer ${tt.id}`:`Display ${tt.id}`}),tt.kind==="layer"&&typeof tt.zIndex=="number"&&k.jsxs("div",{style:{color:"#b7c0c8"},children:["zIndex: ",tt.zIndex]}),k.jsxs("div",{style:{color:"#b7c0c8"},children:["World: ",tt.world.x.toFixed(0),",",tt.world.y.toFixed(0)]}),k.jsxs("div",{style:{color:"#b7c0c8"},children:["Screen: ",tt.screen.x.toFixed(0),",",tt.screen.y.toFixed(0)]})]})]})}const ml={background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.14)",color:"#ddd",borderRadius:6,padding:"4px 8px",cursor:"pointer",lineHeight:1};var zC={},Zf={},qf={},Co={};Object.defineProperty(Co,"__esModule",{value:!0});Co.Direction=void 0;var ny;(function(r){r.Right="to right",r.Left="to left",r.Down="to bottom",r.Up="to top"})(ny||(Co.Direction=ny={}));(function(r){var e=Nr&&Nr.__spreadArray||function(P,O,L){if(L||arguments.length===2)for(var V=0,X=O.length,T;V<X;V++)(T||!(V in O))&&(T||(T=Array.prototype.slice.call(O,0,V)),T[V]=O[V]);return P.concat(T||Array.prototype.slice.call(O))};Object.defineProperty(r,"__esModule",{value:!0}),r.isIOS=r.useThumbOverlap=r.assertUnreachable=r.voidFn=r.getTrackBackground=r.replaceAt=r.schd=r.translate=r.getClosestThumbIndex=r.translateThumbs=r.getPaddingAndBorder=r.getMargin=r.checkInitialOverlap=r.checkValuesAgainstBoundaries=r.checkBoundaries=r.isVertical=r.relativeValue=r.normalizeValue=r.isStepDivisible=r.isTouchEvent=r.getStepDecimals=void 0;var t=N,n=Co,i=function(P){var O=P.toString().split(".")[1];return O?O.length:0};r.getStepDecimals=i;function s(P){return P.touches&&P.touches.length||P.changedTouches&&P.changedTouches.length}r.isTouchEvent=s;function o(P,O,L){var V=(O-P)/L,X=8,T=Number(V.toFixed(X));return parseInt(T.toString(),10)===T}r.isStepDivisible=o;function a(P,O,L,V,X,T,_){var j=1e11;if(P=Math.round(P*j)/j,!T){var G=_[O-1],ee=_[O+1];if(G&&G>P)return G;if(ee&&ee<P)return ee}if(P>V)return V;if(P<L)return L;var q=Math.floor(P*j-L*j)%Math.floor(X*j),K=Math.floor(P*j-Math.abs(q)),oe=q===0?P:K/j,ve=Math.abs(q/j)<X/2?oe:oe+X,ge=(0,r.getStepDecimals)(X);return parseFloat(ve.toFixed(ge))}r.normalizeValue=a;function l(P,O,L){return(P-O)/(L-O)}r.relativeValue=l;function u(P){return P===n.Direction.Up||P===n.Direction.Down}r.isVertical=u;function c(P,O,L){if(O>=L)throw new RangeError("min (".concat(O,") is equal/bigger than max (").concat(L,")"));if(P<O)throw new RangeError("value (".concat(P,") is smaller than min (").concat(O,")"));if(P>L)throw new RangeError("value (".concat(P,") is bigger than max (").concat(L,")"))}r.checkBoundaries=c;function d(P,O,L){return P<O?O:P>L?L:P}r.checkValuesAgainstBoundaries=d;function h(P){if(!(P.length<2)&&!P.slice(1).every(function(O,L){return P[L]<=O}))throw new RangeError("values={[".concat(P,"]} needs to be sorted when allowOverlap={false}"))}r.checkInitialOverlap=h;function f(P){var O=window.getComputedStyle(P);return{top:parseInt(O["margin-top"],10),bottom:parseInt(O["margin-bottom"],10),left:parseInt(O["margin-left"],10),right:parseInt(O["margin-right"],10)}}r.getMargin=f;function p(P){var O=window.getComputedStyle(P);return{top:parseInt(O["padding-top"],10)+parseInt(O["border-top-width"],10),bottom:parseInt(O["padding-bottom"],10)+parseInt(O["border-bottom-width"],10),left:parseInt(O["padding-left"],10)+parseInt(O["border-left-width"],10),right:parseInt(O["padding-right"],10)+parseInt(O["border-right-width"],10)}}r.getPaddingAndBorder=p;function m(P,O,L){var V=L?-1:1;P.forEach(function(X,T){return w(X,V*O[T].x,O[T].y)})}r.translateThumbs=m;function S(P,O,L,V){for(var X=0,T=F(P[0],O,L,V),_=1;_<P.length;_++){var j=F(P[_],O,L,V);j<T&&(T=j,X=_)}return X}r.getClosestThumbIndex=S;function w(P,O,L){P.style.transform="translate(".concat(O,"px, ").concat(L,"px)")}r.translate=w;var g=function(P){var O=[],L=null,V=function(){for(var X=[],T=0;T<arguments.length;T++)X[T]=arguments[T];O=X,!L&&(L=requestAnimationFrame(function(){L=null,P.apply(void 0,O)}))};return V};r.schd=g;function y(P,O,L){var V=P.slice(0);return V[O]=L,V}r.replaceAt=y;function C(P){var O=P.values,L=P.colors,V=P.min,X=P.max,T=P.direction,_=T===void 0?n.Direction.Right:T,j=P.rtl,G=j===void 0?!1:j;G&&_===n.Direction.Right?_=n.Direction.Left:G&&n.Direction.Left&&(_=n.Direction.Right);var ee=O.slice(0).sort(function(K,oe){return K-oe}).map(function(K){return(K-V)/(X-V)*100}),q=ee.reduce(function(K,oe,ve){return"".concat(K,", ").concat(L[ve]," ").concat(oe,"%, ").concat(L[ve+1]," ").concat(oe,"%")},"");return"linear-gradient(".concat(_,", ").concat(L[0]," 0%").concat(q,", ").concat(L[L.length-1]," 100%)")}r.getTrackBackground=C;function x(){}r.voidFn=x;function I(P){throw new Error("Didn't expect to get here")}r.assertUnreachable=I;var E=function(P,O,L,V,X){X===void 0&&(X=function(_){return _});var T=Math.ceil(e([P],Array.from(P.children),!0).reduce(function(_,j){var G=Math.ceil(j.getBoundingClientRect().width);if(j.innerText&&j.innerText.includes(L)&&j.childElementCount===0){var ee=j.cloneNode(!0);ee.innerHTML=X(O.toFixed(V)),ee.style.visibility="hidden",document.body.appendChild(ee),G=Math.ceil(ee.getBoundingClientRect().width),document.body.removeChild(ee)}return G>_?G:_},P.getBoundingClientRect().width));return T},A=function(P,O,L,V,X,T,_){_===void 0&&(_=function(ee){return ee});var j=[],G=function(ee){var q=E(L[ee],V[ee],X,T,_),K=O[ee].x;O.forEach(function(oe,ve){var ge=oe.x,Ce=E(L[ve],V[ve],X,T,_);ee!==ve&&(K>=ge&&K<=ge+Ce||K+q>=ge&&K+q<=ge+Ce)&&(j.includes(ve)||(j.push(ee),j.push(ve),j=e(e([],j,!0),[ee,ve],!1),G(ve)))})};return G(P),Array.from(new Set(j.sort()))},R=function(P,O,L,V,X,T){V===void 0&&(V=.1),X===void 0&&(X=" - "),T===void 0&&(T=function(ve){return ve});var _=(0,r.getStepDecimals)(V),j=(0,t.useState)({}),G=j[0],ee=j[1],q=(0,t.useState)(T(O[L].toFixed(_))),K=q[0],oe=q[1];return(0,t.useEffect)(function(){if(P){var ve=P.getThumbs();if(ve.length<1)return;var ge={},Ce=P.getOffsets(),ct=A(L,Ce,ve,O,X,_,T),dt=T(O[L].toFixed(_));if(ct.length){var xe=ct.reduce(function(wt,Ft,cr,tt){return wt.length?e(e([],wt,!0),[Ce[tt[cr]].x],!1):[Ce[tt[cr]].x]},[]);if(Math.min.apply(Math,xe)===Ce[L].x){var et=[];ct.forEach(function(wt){et.push(O[wt].toFixed(_))}),dt=Array.from(new Set(et.sort(function(wt,Ft){return parseFloat(wt)-parseFloat(Ft)}))).map(T).join(X);var Ke=Math.min.apply(Math,xe),qe=Math.max.apply(Math,xe),At=ve[ct[xe.indexOf(qe)]].getBoundingClientRect().width;ge.left="".concat(Math.abs(Ke-(qe+At))/2,"px"),ge.transform="translate(-50%, 0)"}else ge.visibility="hidden"}oe(dt),ee(ge)}},[P,O]),[K,G]};r.useThumbOverlap=R;function F(P,O,L,V){var X=P.getBoundingClientRect(),T=X.left,_=X.top,j=X.width,G=X.height;return u(V)?Math.abs(L-(_+G/2)):Math.abs(O-(T+j/2))}var z=function(){var P,O=((P=navigator.userAgentData)===null||P===void 0?void 0:P.platform)||navigator.platform;return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(O)||navigator.userAgent.includes("Mac")&&"ontouchend"in document};r.isIOS=z})(qf);var gU=Nr&&Nr.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),mU=Nr&&Nr.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),yU=Nr&&Nr.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),vU=Nr&&Nr.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&mU(e,r,t);return yU(e,r),e},iy=Nr&&Nr.__spreadArray||function(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return r.concat(s||Array.prototype.slice.call(e))};Object.defineProperty(Zf,"__esModule",{value:!0});var yl=vU(N),ze=qf,_t=Co,wU=["ArrowRight","ArrowUp","k","PageUp"],CU=["ArrowLeft","ArrowDown","j","PageDown"],bU=function(r){gU(e,r);function e(t){var n=r.call(this,t)||this;if(n.trackRef=yl.createRef(),n.thumbRefs=[],n.state={draggedTrackPos:[-1,-1],draggedThumbIndex:-1,thumbZIndexes:new Array(n.props.values.length).fill(0).map(function(i,s){return s}),isChanged:!1,markOffsets:[]},n.getOffsets=function(){var i=n.props,s=i.direction,o=i.values,a=i.min,l=i.max,u=n.trackRef.current;if(!u)return console.warn("No track element found."),[];var c=u.getBoundingClientRect(),d=(0,ze.getPaddingAndBorder)(u);return n.getThumbs().map(function(h,f){var p={x:0,y:0},m=h.getBoundingClientRect(),S=(0,ze.getMargin)(h);switch(s){case _t.Direction.Right:return p.x=(S.left+d.left)*-1,p.y=((m.height-c.height)/2+d.top)*-1,p.x+=c.width*(0,ze.relativeValue)(o[f],a,l)-m.width/2,p;case _t.Direction.Left:return p.x=(S.right+d.right)*-1,p.y=((m.height-c.height)/2+d.top)*-1,p.x+=c.width-c.width*(0,ze.relativeValue)(o[f],a,l)-m.width/2,p;case _t.Direction.Up:return p.x=((m.width-c.width)/2+S.left+d.left)*-1,p.y=-d.left,p.y+=c.height-c.height*(0,ze.relativeValue)(o[f],a,l)-m.height/2,p;case _t.Direction.Down:return p.x=((m.width-c.width)/2+S.left+d.left)*-1,p.y=-d.left,p.y+=c.height*(0,ze.relativeValue)(o[f],a,l)-m.height/2,p;default:return(0,ze.assertUnreachable)(s)}})},n.getThumbs=function(){return n.trackRef&&n.trackRef.current?Array.from(n.trackRef.current.children).filter(function(i){return i.hasAttribute("aria-valuenow")}):(console.warn("No thumbs found in the track container. Did you forget to pass & spread the `props` param in renderTrack?"),[])},n.getTargetIndex=function(i){return n.getThumbs().findIndex(function(s){return s===i.target||s.contains(i.target)})},n.addTouchEvents=function(i){document.addEventListener("touchmove",n.schdOnTouchMove,{passive:!1}),document.addEventListener("touchend",n.schdOnEnd,{passive:!1}),document.addEventListener("touchcancel",n.schdOnEnd,{passive:!1})},n.addMouseEvents=function(i){document.addEventListener("mousemove",n.schdOnMouseMove),document.addEventListener("mouseup",n.schdOnEnd)},n.onMouseDownTrack=function(i){var s;if(!(i.button!==0||(0,ze.isIOS)()))if(i.persist(),i.preventDefault(),n.addMouseEvents(i.nativeEvent),n.props.values.length>1&&n.props.draggableTrack){if(n.thumbRefs.some(function(a){var l;return(l=a.current)===null||l===void 0?void 0:l.contains(i.target)}))return;n.setState({draggedTrackPos:[i.clientX,i.clientY]},function(){return n.onMove(i.clientX,i.clientY)})}else{var o=(0,ze.getClosestThumbIndex)(n.thumbRefs.map(function(a){return a.current}),i.clientX,i.clientY,n.props.direction);(s=n.thumbRefs[o].current)===null||s===void 0||s.focus(),n.setState({draggedThumbIndex:o},function(){return n.onMove(i.clientX,i.clientY)})}},n.onResize=function(){(0,ze.translateThumbs)(n.getThumbs(),n.getOffsets(),n.props.rtl),n.calculateMarkOffsets()},n.onTouchStartTrack=function(i){var s;if(i.persist(),n.addTouchEvents(i.nativeEvent),n.props.values.length>1&&n.props.draggableTrack){if(n.thumbRefs.some(function(a){var l;return(l=a.current)===null||l===void 0?void 0:l.contains(i.target)}))return;n.setState({draggedTrackPos:[i.touches[0].clientX,i.touches[0].clientY]},function(){return n.onMove(i.touches[0].clientX,i.touches[0].clientY)})}else{var o=(0,ze.getClosestThumbIndex)(n.thumbRefs.map(function(a){return a.current}),i.touches[0].clientX,i.touches[0].clientY,n.props.direction);(s=n.thumbRefs[o].current)===null||s===void 0||s.focus(),n.setState({draggedThumbIndex:o},function(){return n.onMove(i.touches[0].clientX,i.touches[0].clientY)})}},n.onMouseOrTouchStart=function(i){if(!n.props.disabled){var s=(0,ze.isTouchEvent)(i);if(!(!s&&i.button!==0)){var o=n.getTargetIndex(i);o!==-1&&(s?n.addTouchEvents(i):n.addMouseEvents(i),n.setState({draggedThumbIndex:o,thumbZIndexes:n.state.thumbZIndexes.map(function(a,l){return l===o?Math.max.apply(Math,n.state.thumbZIndexes):a<=n.state.thumbZIndexes[o]?a:a-1})}))}}},n.onMouseMove=function(i){i.preventDefault(),n.onMove(i.clientX,i.clientY)},n.onTouchMove=function(i){i.preventDefault(),n.onMove(i.touches[0].clientX,i.touches[0].clientY)},n.onKeyDown=function(i){var s=n.props,o=s.values,a=s.onChange,l=s.step,u=s.rtl,c=s.direction,d=n.state.isChanged,h=n.getTargetIndex(i.nativeEvent),f=u||c===_t.Direction.Left||c===_t.Direction.Down?-1:1;h!==-1&&(wU.includes(i.key)?(i.preventDefault(),n.setState({draggedThumbIndex:h,isChanged:!0}),a((0,ze.replaceAt)(o,h,n.normalizeValue(o[h]+f*(i.key==="PageUp"?l*10:l),h)))):CU.includes(i.key)?(i.preventDefault(),n.setState({draggedThumbIndex:h,isChanged:!0}),a((0,ze.replaceAt)(o,h,n.normalizeValue(o[h]-f*(i.key==="PageDown"?l*10:l),h)))):i.key==="Tab"?n.setState({draggedThumbIndex:-1},function(){d&&n.fireOnFinalChange()}):d&&n.fireOnFinalChange())},n.onKeyUp=function(i){var s=n.state.isChanged;n.setState({draggedThumbIndex:-1},function(){s&&n.fireOnFinalChange()})},n.onMove=function(i,s){var o=n.state,a=o.draggedThumbIndex,l=o.draggedTrackPos,u=n.props,c=u.direction,d=u.min,h=u.max,f=u.onChange,p=u.values,m=u.step,S=u.rtl;if(a===-1&&l[0]===-1&&l[1]===-1)return null;var w=n.trackRef.current;if(!w)return null;var g=w.getBoundingClientRect(),y=(0,ze.isVertical)(c)?g.height:g.width;if(l[0]!==-1&&l[1]!==-1){var C=i-l[0],x=s-l[1],I=0;switch(c){case _t.Direction.Right:case _t.Direction.Left:I=C/y*(h-d);break;case _t.Direction.Down:case _t.Direction.Up:I=x/y*(h-d);break;default:(0,ze.assertUnreachable)(c)}if(S&&(I*=-1),Math.abs(I)>=m/2){for(var E=0;E<n.thumbRefs.length;E++){if(p[E]===h&&Math.sign(I)===1||p[E]===d&&Math.sign(I)===-1)return;var A=p[E]+I;A>h?I=h-p[E]:A<d&&(I=d-p[E])}for(var R=p.slice(0),E=0;E<n.thumbRefs.length;E++)R=(0,ze.replaceAt)(R,E,n.normalizeValue(p[E]+I,E));n.setState({draggedTrackPos:[i,s]}),f(R)}}else{var F=0;switch(c){case _t.Direction.Right:F=(i-g.left)/y*(h-d)+d;break;case _t.Direction.Left:F=(y-(i-g.left))/y*(h-d)+d;break;case _t.Direction.Down:F=(s-g.top)/y*(h-d)+d;break;case _t.Direction.Up:F=(y-(s-g.top))/y*(h-d)+d;break;default:(0,ze.assertUnreachable)(c)}S&&(F=h+d-F),Math.abs(p[a]-F)>=m/2&&f((0,ze.replaceAt)(p,a,n.normalizeValue(F,a)))}},n.normalizeValue=function(i,s){var o=n.props,a=o.min,l=o.max,u=o.step,c=o.allowOverlap,d=o.values;return(0,ze.normalizeValue)(i,s,a,l,u,c,d)},n.onEnd=function(i){if(i.preventDefault(),document.removeEventListener("mousemove",n.schdOnMouseMove),document.removeEventListener("touchmove",n.schdOnTouchMove),document.removeEventListener("mouseup",n.schdOnEnd),document.removeEventListener("touchend",n.schdOnEnd),document.removeEventListener("touchcancel",n.schdOnEnd),n.state.draggedThumbIndex===-1&&n.state.draggedTrackPos[0]===-1&&n.state.draggedTrackPos[1]===-1)return null;n.setState({draggedThumbIndex:-1,draggedTrackPos:[-1,-1]},function(){n.fireOnFinalChange()})},n.fireOnFinalChange=function(){n.setState({isChanged:!1});var i=n.props,s=i.onFinalChange,o=i.values;s&&s(o)},n.updateMarkRefs=function(i){if(!i.renderMark){n.numOfMarks=void 0,n.markRefs=void 0;return}n.numOfMarks=(i.max-i.min)/n.props.step,n.markRefs=[];for(var s=0;s<n.numOfMarks+1;s++)n.markRefs[s]=yl.createRef()},n.calculateMarkOffsets=function(){if(!(!n.props.renderMark||!n.trackRef||!n.numOfMarks||!n.markRefs||n.trackRef.current===null)){for(var i=window.getComputedStyle(n.trackRef.current),s=parseInt(i.width,10),o=parseInt(i.height,10),a=parseInt(i.paddingLeft,10),l=parseInt(i.paddingTop,10),u=[],c=0;c<n.numOfMarks+1;c++){var d=9999,h=9999;if(n.markRefs[c].current){var f=n.markRefs[c].current.getBoundingClientRect();d=f.height,h=f.width}n.props.direction===_t.Direction.Left||n.props.direction===_t.Direction.Right?u.push([Math.round(s/n.numOfMarks*c+a-h/2),-Math.round((d-o)/2)]):u.push([Math.round(o/n.numOfMarks*c+l-d/2),-Math.round((h-s)/2)])}n.setState({markOffsets:u})}},t.step===0)throw new Error('"step" property should be a positive number');return n.schdOnMouseMove=(0,ze.schd)(n.onMouseMove),n.schdOnTouchMove=(0,ze.schd)(n.onTouchMove),n.schdOnEnd=(0,ze.schd)(n.onEnd),n.thumbRefs=t.values.map(function(){return yl.createRef()}),n.updateMarkRefs(t),n}return e.prototype.componentDidMount=function(){var t=this,n=this.props,i=n.values,s=n.min,o=n.step;this.resizeObserver=window.ResizeObserver?new window.ResizeObserver(this.onResize):{observe:function(){return window.addEventListener("resize",t.onResize)},unobserve:function(){return window.removeEventListener("resize",t.onResize)}},document.addEventListener("touchstart",this.onMouseOrTouchStart,{passive:!1}),document.addEventListener("mousedown",this.onMouseOrTouchStart,{passive:!1}),!this.props.allowOverlap&&(0,ze.checkInitialOverlap)(this.props.values),this.props.values.forEach(function(a){return(0,ze.checkBoundaries)(a,t.props.min,t.props.max)}),this.resizeObserver.observe(this.trackRef.current),(0,ze.translateThumbs)(this.getThumbs(),this.getOffsets(),this.props.rtl),this.calculateMarkOffsets(),i.forEach(function(a){(0,ze.isStepDivisible)(s,a,o)||console.warn("The `values` property is in conflict with the current `step`, `min`, and `max` properties. Please provide values that are accessible using the min, max, and step values.")})},e.prototype.componentDidUpdate=function(t,n){var i=this.props,s=i.max,o=i.min,a=i.step,l=i.values,u=i.rtl;(t.max!==s||t.min!==o||t.step!==a)&&this.updateMarkRefs(this.props),(0,ze.translateThumbs)(this.getThumbs(),this.getOffsets(),u),(t.max!==s||t.min!==o||t.step!==a||n.markOffsets.length!==this.state.markOffsets.length)&&(this.calculateMarkOffsets(),l.forEach(function(c){(0,ze.isStepDivisible)(o,c,a)||console.warn("The `values` property is in conflict with the current `step`, `min`, and `max` properties. Please provide values that are accessible using the min, max, and step values.")}))},e.prototype.componentWillUnmount=function(){var t={passive:!1};document.removeEventListener("mousedown",this.onMouseOrTouchStart,t),document.removeEventListener("mousemove",this.schdOnMouseMove),document.removeEventListener("touchmove",this.schdOnTouchMove),document.removeEventListener("touchstart",this.onMouseOrTouchStart),document.removeEventListener("mouseup",this.schdOnEnd),document.removeEventListener("touchend",this.schdOnEnd),this.resizeObserver.unobserve(this.trackRef.current)},e.prototype.render=function(){var t=this,n=this.props,i=n.label,s=n.labelledBy,o=n.renderTrack,a=n.renderThumb,l=n.renderMark,u=l===void 0?function(){return null}:l,c=n.values,d=n.min,h=n.max,f=n.allowOverlap,p=n.disabled,m=this.state,S=m.draggedThumbIndex,w=m.thumbZIndexes,g=m.markOffsets;return o({props:{style:{transform:"scale(1)",cursor:S>-1?"grabbing":this.props.draggableTrack?(0,ze.isVertical)(this.props.direction)?"ns-resize":"ew-resize":c.length===1&&!p?"pointer":"inherit"},onMouseDown:p?ze.voidFn:this.onMouseDownTrack,onTouchStart:p?ze.voidFn:this.onTouchStartTrack,ref:this.trackRef},isDragged:this.state.draggedThumbIndex>-1,disabled:p,children:iy(iy([],g.map(function(y,C,x){return u({props:{style:t.props.direction===_t.Direction.Left||t.props.direction===_t.Direction.Right?{position:"absolute",left:"".concat(y[0],"px"),marginTop:"".concat(y[1],"px")}:{position:"absolute",top:"".concat(y[0],"px"),marginLeft:"".concat(y[1],"px")},key:"mark".concat(C),ref:t.markRefs[C]},index:C})}),!0),c.map(function(y,C){var x=t.state.draggedThumbIndex===C;return a({index:C,value:y,isDragged:x,props:{style:{position:"absolute",zIndex:w[C],cursor:p?"inherit":x?"grabbing":"grab",userSelect:"none",touchAction:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none"},key:C,tabIndex:p?void 0:0,"aria-valuemax":f?h:c[C+1]||h,"aria-valuemin":f?d:c[C-1]||d,"aria-valuenow":y,draggable:!1,ref:t.thumbRefs[C],"aria-label":i,"aria-labelledby":s,role:"slider",onKeyDown:p?ze.voidFn:t.onKeyDown,onKeyUp:p?ze.voidFn:t.onKeyUp}})}),!0)})},e.defaultProps={label:"Accessibility label",labelledBy:null,step:1,direction:_t.Direction.Right,rtl:!1,disabled:!1,allowOverlap:!1,draggableTrack:!1,min:0,max:100},e}(yl.Component);Zf.default=bU;(function(r){var e=Nr&&Nr.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(r,"__esModule",{value:!0}),r.checkValuesAgainstBoundaries=r.relativeValue=r.useThumbOverlap=r.Direction=r.getTrackBackground=r.Range=void 0;var t=e(Zf);r.Range=t.default;var n=qf;Object.defineProperty(r,"getTrackBackground",{enumerable:!0,get:function(){return n.getTrackBackground}}),Object.defineProperty(r,"useThumbOverlap",{enumerable:!0,get:function(){return n.useThumbOverlap}}),Object.defineProperty(r,"relativeValue",{enumerable:!0,get:function(){return n.relativeValue}}),Object.defineProperty(r,"checkValuesAgainstBoundaries",{enumerable:!0,get:function(){return n.checkValuesAgainstBoundaries}});var i=Co;Object.defineProperty(r,"Direction",{enumerable:!0,get:function(){return i.Direction}})})(zC);const Yr={fontSize:12,color:"#9aa7b2"},sy={background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:10};function Zo(r,e,t){return Math.max(e,Math.min(t,r))}function oy(r,e){const t=r.replace("#",""),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),s=parseInt(t.slice(4,6),16);return`rgba(${n},${i},${s},${Zo(e,0,1)})`}function SU(r){const e=["#66d9ef","#a6e22e","#fd971f","#e6db74","#f92672","#ae81ff","#2aa198"];return e[Math.abs(r)%e.length]}function DC(r,e){const t=(r??"").trim();return t.length?t:e}function xU(r,e){return r.map(t=>{const n=e.get(t);return n?{id:t,name:DC(n.name,`Layer ${t}`),z:n.z,layer:{id:n.id,name:n.name,z:n.z,origin:n.origin,width:n.width,height:n.height}}:null}).filter(Boolean)}function IU({user:r,selectedDisplayId:e,selectedLayerIds:t,onSelectLayer:n,onSelectDisplay:i,setVisibleLayers:s}){var C;const o=N.useMemo(()=>r.displays.filter(x=>x.id!==255),[r.displays]),[a,l]=N.useState(null),[u,c]=N.useState([0,0]),d=N.useRef(null),h=N.useMemo(()=>{var E,A,R;const x=(E=o.find(F=>F.id===e))==null?void 0:E.id;if(x!=null)return x;const I=(A=o.find(F=>F.id===a))==null?void 0:A.id;return I??((R=o[0])==null?void 0:R.id)??null},[a,o,e]),f=N.useMemo(()=>h==null?null:o.find(x=>x.id===h)??null,[o,h]),p=N.useMemo(()=>{var I,E;if(h==null)return null;const x=(E=(I=r.displayComposite)==null?void 0:I[h])==null?void 0:E.layerIdsTopToBottom;return x&&x.length?x:null},[h,r.displayComposite]),m=N.useMemo(()=>{const x=new Map;for(const I of r.layers)x.set(I.id,{id:I.id,name:I.name,z:I.z,origin:I.origin,width:I.width,height:I.height});return x},[r.layers]),S=N.useMemo(()=>{var z,P;if(h==null)return[];const x=(P=(z=r.displayComposite)==null?void 0:z[h])==null?void 0:P.layerIdsTopToBottom;if(x&&x.length)return xU(x,m);if(!f)return[];const I=f.origin.x,E=f.origin.y,A=I+f.size.x,R=E+f.size.y,F=[];for(const O of r.layers){const L=O.origin.x,V=O.origin.y,X=O.origin.x+O.width,T=O.origin.y+O.height;A<=L||I>=X||R<=V||E>=T||F.push({id:O.id,name:DC(O.name,`Layer ${O.id}`),z:O.z,layer:O})}return F.sort((O,L)=>L.z-O.z),F},[h,f,m,r.displayComposite,r.layers]);N.useEffect(()=>{const x=S.length;if(!x){c([0,0]);return}const I=Math.max(0,x-1);c([0,I])},[h,S.length]);const w=N.useMemo(()=>{const x=Math.max(0,S.length-1);let I=Zo(u[0],0,x),E=Zo(u[1],0,x);return I>E&&([I,E]=[E,I]),[I,E]},[S.length,u]),g=N.useMemo(()=>{if(!S.length)return S;const[x,I]=w;return S.slice(x,I+1)},[S,w]);N.useEffect(()=>{if(!s)return;if(!S.length){s(null);return}const[x,I]=w;if(x===0&&I===S.length-1){s(null);return}s(g.map(A=>A.id))},[S.length,w,s,g]);const y=N.useMemo(()=>{if(!f)return null;const x=g;if(!S.length)return{visible:[],minY:f.origin.y,maxY:f.origin.y+f.size.y,range:[0,0]};const[I,E]=w,A=x;let R=f.origin.y,F=f.origin.y+f.size.y;for(const z of A){const P=z.layer;P&&(R=Math.min(R,P.origin.y),F=Math.max(F,P.origin.y+P.height))}return{visible:A,minY:R,maxY:F,range:[I,E]}},[f,S.length,w,g]);return N.useEffect(()=>{const x=d.current;if(!x||!f||!y)return;const I=x.getContext("2d");if(!I)return;const E=window.devicePixelRatio||1,A=x.clientWidth,R=x.clientHeight,F=Math.max(1,Math.floor(A*E)),z=Math.max(1,Math.floor(R*E));(x.width!==F||x.height!==z)&&(x.width=F,x.height=z),I.setTransform(E,0,0,E,0,0),I.clearRect(0,0,A,R);const P=14,O=Math.max(1,A-P*2),L=Math.max(1,R-P*2),V=y.minY,X=y.maxY,T=Math.max(1,X-V),_=f.origin.x,j=f.origin.x+f.size.x,G=Math.max(1,j-_),ee=xe=>P+(xe-_)/G*O,q=xe=>xe/G*O,K=xe=>P+(xe-V)/T*L,oe=xe=>xe/T*L;I.fillStyle="rgba(0,0,0,0.20)",I.fillRect(0,0,A,R);const ve=ee(f.origin.x),ge=K(f.origin.y),Ce=q(f.size.x),ct=oe(f.size.y);I.strokeStyle="rgba(255,120,120,0.75)",I.lineWidth=1,I.strokeRect(ve,ge,Ce,ct),I.fillStyle="rgba(255,120,120,0.08)",I.fillRect(ve,ge,Ce,ct);const dt=y.visible;for(let xe=dt.length-1;xe>=0;xe--){const et=dt[xe],Ke=et.layer;if(!Ke)continue;const qe=ee(Ke.origin.x),At=K(Ke.origin.y),wt=Math.max(2,q(Ke.width)),Ft=Math.max(2,oe(Ke.height)),cr=SU(et.id),tt=t.includes(et.id);I.fillStyle=oy(cr,1),I.strokeStyle=oy(cr,tt?.95:.55),I.lineWidth=tt?2:1,I.fillRect(qe,At,wt,Ft),I.strokeRect(qe,At,wt,Ft),I.save(),I.beginPath(),I.rect(qe,At,wt,Ft),I.clip(),I.fillStyle="rgba(15,15,15,0.95)",I.font="12px Segoe UI, sans-serif";const kt=[`${et.name}`,`id ${et.id} • z ${et.z}`,`pos ${Ke.origin.x},${Ke.origin.y}`,`size ${Ke.width}×${Ke.height}`],nt=14;let Cr=At+16;const Se=qe+8;for(let Re=0;Re<kt.length&&!(Cr>At+Ft-4);Re++){const pe=kt[Re];I.fillText(pe,Se,Cr),Cr+=nt}I.restore()}dt.length===0&&(I.fillStyle="rgba(154,167,178,0.9)",I.font="12px Segoe UI, sans-serif",I.fillText("No layers in this range",P+8,P+18))},[f,t,y]),k.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",minHeight:0},children:[k.jsxs("div",{style:{padding:"10px 12px",borderBottom:"1px solid #2f2f2f",background:"#1b1d22",display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[k.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#e6e6e6"},children:"Composer"}),k.jsx("div",{style:Yr,children:"Side stack per display (core-derived)"})]}),k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[k.jsx("div",{style:Yr,children:"Display"}),k.jsx("select",{value:h??"",onChange:x=>{const I=x.target.value===""?null:Number(x.target.value);l(I),I!=null&&i(I)},style:{height:28,background:"#252526",color:"#cccccc",border:"1px solid #3c3c3c",borderRadius:8,padding:"0 8px",fontSize:12,outline:"none"},children:o.map(x=>k.jsx("option",{value:x.id,children:x.id},x.id))})]})]}),k.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:12,background:"#14161a"},children:h==null?k.jsx("div",{style:{...Yr,padding:16},children:"No display."}):k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 280px",gap:12,alignItems:"start"},children:[k.jsxs("div",{style:{...sy,padding:12,display:"flex",flexDirection:"column",gap:10},children:[k.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between"},children:[k.jsx("div",{style:{fontWeight:700,color:"#e6e6e6"},children:"Cut-away"}),k.jsx("div",{style:Yr,children:f?`origin ${f.origin.x},${f.origin.y} • size ${f.size.x}×${f.size.y}`:""})]}),f&&k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[k.jsx("div",{style:Yr,children:"Z range"}),k.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{padding:"6px 0"},children:k.jsx(zC.Range,{step:1,min:0,max:Math.max(0,S.length-1),values:(()=>{const x=Math.max(0,S.length-1),I=x-w[1],E=x-w[0];return[I,E]})(),onChange:x=>{const I=Math.max(0,S.length-1),E=Math.round(x[0]??0),A=Math.round(x[1]??0),R=Zo(I-A,0,I),F=Zo(I-E,0,I);c([R,F])},renderTrack:({props:x,children:I})=>k.jsxs("div",{...x,style:{...x.style,height:6,width:"100%",borderRadius:999,background:"rgba(255,255,255,0.10)",border:"1px solid rgba(255,255,255,0.12)",position:"relative"},children:[(()=>{const E=Math.max(1,S.length-1),A=(E-w[1])/E,R=(E-w[0])/E,F=A*100,z=R*100;return k.jsx("div",{style:{position:"absolute",left:`${Math.min(F,z)}%`,width:`${Math.max(0,Math.abs(z-F))}%`,top:-1,bottom:-1,borderRadius:999,background:"linear-gradient(90deg, rgba(102,217,239,0.70), rgba(253,151,31,0.70))",boxShadow:"0 0 0 1px rgba(0,0,0,0.18) inset"}})})(),I]}),renderThumb:({props:x,index:I})=>k.jsx("div",{...x,style:{...x.style,height:14,width:14,borderRadius:999,background:I===0?"#66d9ef":"#fd971f",border:"1px solid rgba(0,0,0,0.35)",boxShadow:"0 2px 10px rgba(0,0,0,0.35)"},title:I===0?"Bottom handle":"Top handle"})})}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10},children:[k.jsx("div",{style:Yr,children:"BOTTOM"}),k.jsxs("div",{style:Yr,children:[S.length?`${w[0]} → ${w[1]}`:"—",S.length?` • ${g.length}/${S.length}`:""]}),k.jsx("div",{style:Yr,children:"TOP"})]})]})]}),k.jsx("div",{style:{position:"relative",flex:1,minHeight:260},children:k.jsx("canvas",{ref:d,style:{width:"100%",height:"100%",display:"block",borderRadius:10,background:"rgba(0,0,0,0.12)",cursor:"default",pointerEvents:"none",maxWidth:800,margin:"0 auto"}})})]}),k.jsxs("div",{style:{...sy,padding:12},children:[k.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between"},children:[k.jsx("div",{style:{fontWeight:700,color:"#e6e6e6"},children:"Side stack"}),k.jsxs("div",{style:Yr,children:[g.length," / ",S.length," layers"]})]}),p&&k.jsxs("div",{style:{...Yr,marginTop:6},children:["core order: top→bottom • [",p.join(", "),"]"]}),k.jsxs("div",{style:{marginTop:10,display:"flex",flexDirection:"column",gap:8},children:[S.map((x,I)=>{const E=t.includes(x.id),A=I>=w[0]&&I<=w[1];return k.jsx("button",{onClick:R=>{n(x.id,{metaKey:R.metaKey,ctrlKey:R.ctrlKey});const F=S.findIndex(z=>z.id===x.id);F>=0&&c([F,F])},style:{textAlign:"left",width:"100%",background:E?"rgba(102, 217, 239, 0.10)":A?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",border:E?"1px solid rgba(102, 217, 239, 0.65)":A?"1px solid rgba(255,255,255,0.10)":"1px solid rgba(255,255,255,0.06)",borderRadius:10,padding:"8px 10px",cursor:"pointer",color:A?"#e6e6e6":"rgba(230,230,230,0.55)"},title:"Select layer",children:k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10},children:[k.jsx("div",{style:{fontWeight:650,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.name}),k.jsxs("div",{style:{...Yr,whiteSpace:"nowrap"},children:["z=",x.z]})]})},x.id)}),S.length===0&&k.jsx("div",{style:{...Yr,padding:10},children:"No layers."}),((C=r.displayComposite)==null?void 0:C[h])==null&&k.jsx("div",{style:{...Yr,paddingTop:8},children:"Using fallback intersection (core composition not present)."})]})]})]})})]})}function kU({centerTab:r,setCenterTab:e,centerPanelRef:t,centerSize:n,worldLayers:i,worldDisplays:s,selectedLayerIds:o,setVisibleLayers:a,selectedDisplayId:l,focusRect:u,focusKey:c,onSelectLayer:d,onSelectDisplay:h,assetsSnapshot:f,primaryUser:p,isFloating:m,sortedTraffic:S,topTraffic:w,chartData:g,topKeys:y,keyToLabel:C,keyToColor:x,tickRate:I,hoveredTrafficKey:E,setHoveredTrafficKey:A}){return k.jsxs("div",{style:{background:"#1e1e1e",padding:0,minHeight:0,overflow:"hidden",display:"flex",flexDirection:"column"},children:[k.jsx("div",{style:{display:"flex",alignItems:"center",gap:2,padding:"4px 6px 0",background:"#252526",borderBottom:"1px solid #3c3c3c"},children:[{id:"grid",label:"World"},{id:"assets",label:"Assets"},{id:"network",label:"Network Details"},{id:"composer",label:"Composer"},{id:"renderer",label:"Renderer"}].map(R=>{const F=r===R.id;return k.jsx("button",{onClick:()=>e(R.id),style:{border:"1px solid #3c3c3c",borderBottom:F?"1px solid #1e1e1e":"1px solid #3c3c3c",background:F?"#1e1e1e":"#2d2d2d",color:"#cccccc",padding:"4px 10px",cursor:"pointer",fontSize:12,borderRadius:"4px 4px 0 0",marginBottom:"-1px"},children:R.label},R.id)})}),k.jsxs("div",{ref:t,style:{position:"relative",flex:1,minHeight:0,overflow:"hidden",background:"#1e1e1e"},children:[r==="grid"&&k.jsx(pU,{layers:i,displays:s,width:n.width,height:n.height,selectedLayerIds:o,selectedDisplayId:l,focusRect:u,focusKey:c,onSelectLayer:d,onSelectDisplay:h,onToolRectCommit:R=>{window.dispatchEvent(new window.CustomEvent("__utsp_debug_display255_rect",{detail:R}))}}),r==="composer"&&p&&k.jsx(IU,{user:p,selectedDisplayId:l,selectedLayerIds:o,onSelectLayer:d,onSelectDisplay:h,setVisibleLayers:a}),r==="composer"&&!p&&k.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"#9aa7b2",fontSize:13,background:"#111"},children:"No user in snapshot."}),r==="assets"&&k.jsx(mM,{assetsSnapshot:f}),r==="renderer"&&!m&&k.jsx("div",{style:{position:"absolute",inset:0,background:"#111"}}),r==="renderer"&&m&&k.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"#bbbbbb",fontSize:13,background:"#111",textAlign:"center",padding:24,lineHeight:1.5},children:'Press "Embed" on the floating renderer window to dock it here.'}),r==="network"&&k.jsx(fU,{sortedTraffic:S,topTraffic:w,chartData:g,topKeys:y,keyToLabel:C,keyToColor:x,tickRate:I,hoveredTrafficKey:E,setHoveredTrafficKey:A})]})]})}function EU(r){var d,h;const{enabled:e,snapshot:t,layers:n}=r,[i,s]=N.useState([]),o=N.useRef(null),a=N.useRef(0),l=N.useMemo(()=>{let f=0;for(let p=0;p<n.length;p++){const m=n[p].bytesPerSec1s;typeof m=="number"&&(f+=m)}return f},[n]);N.useEffect(()=>{e&&s(f=>f.length>0?f:[{time:"—",total:0}])},[e]),N.useEffect(()=>{var y,C;if(!e)return;const f=((y=t==null?void 0:t.tick)==null?void 0:y.tickRate)??((C=t==null?void 0:t.tick)==null?void 0:C.tps)??60,p=Math.max(1,Math.round(f*10)),m=performance.now?performance.now():Date.now(),S=Math.max(1,Math.round(1e3/f));if(m-a.current<S)return;a.current=m;const g={time:new Date().toLocaleTimeString("en-US",{hour12:!1,minute:"2-digit",second:"2-digit"}),total:l};s(x=>{if(o.current!==f)return o.current=f,[g];const I=x.length===0?[g]:[...x,g];return I.length>p?I.slice(I.length-p):I})},[e,l,t]);const u=o.current??((d=t==null?void 0:t.tick)==null?void 0:d.tickRate)??((h=t==null?void 0:t.tick)==null?void 0:h.tps)??60,c=N.useMemo(()=>{for(let f=0;f<i.length;f++)if(Number(i[f].total??0)>0)return!0;return!1},[i]);return{tickRate:u,data:i,hasData:c,latestBps:l}}function MU({primaryUser:r,tickRate:e,snapshot:t,assetsSnapshot:n}){const{totalBytesAll:i,totalBytesAssets:s,totalBytesNonAssets:o,totalBpsNonAssets:a}=N.useMemo(()=>{var y;const u=(r==null?void 0:r.layers)??[],c=(r==null?void 0:r.miscTraffic)??{},d=(r==null?void 0:r.displayTraffic)??{};let h=0,f=0;for(let C=0;C<u.length;C++){const x=u[C];typeof x.bytesTotal=="number"&&(h+=x.bytesTotal),typeof x.bytesPerSec1s=="number"&&(f+=x.bytesPerSec1s)}for(const C of Object.values(c))typeof(C==null?void 0:C.total)=="number"&&(h+=C.total),typeof(C==null?void 0:C.bytesPerSec1s)=="number"&&(f+=C.bytesPerSec1s);for(const C of Object.values(d))typeof(C==null?void 0:C.total)=="number"&&(h+=C.total),typeof(C==null?void 0:C.bytesPerSec1s)=="number"&&(f+=C.bytesPerSec1s);const p=Array.isArray(n==null?void 0:n.audio)?n.audio:[];let m=0;for(let C=0;C<p.length;C++){const x=(y=p[C])==null?void 0:y.originalSize;typeof x=="number"&&Number.isFinite(x)&&x>0&&(m+=x)}const S=Math.max(0,h),w=m>0?m:void 0;return{totalBytesAll:w!=null?w+S:S,totalBytesAssets:w,totalBytesNonAssets:S,totalBpsNonAssets:Math.max(0,f)}},[r,t,n]),{data:l}=EU({enabled:!0,snapshot:t,layers:(r==null?void 0:r.layers)??[]});return k.jsxs("div",{style:{borderLeft:"1px solid #3c3c3c",background:"#252526",padding:0,minHeight:0,display:"flex",flexDirection:"column"},children:[k.jsx("div",{style:{padding:"8px 12px",borderBottom:"1px solid #3c3c3c"},children:k.jsx("div",{style:{fontSize:11,color:"#bbbbbb",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Network"})}),k.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:10},children:[k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Total assets"}),k.jsx("div",{style:{fontSize:12,color:"#cccccc"},children:Kr(s)})]}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Total (non-assets)"}),k.jsx("div",{style:{fontSize:12,color:"#cccccc"},children:Kr(o)})]}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Total"}),k.jsx("div",{style:{fontSize:12,color:"#cccccc"},children:Kr(i)})]}),k.jsx("div",{style:{height:1,background:"#3c3c3c",opacity:.5}}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Per second"}),k.jsxs("div",{style:{fontSize:12,color:"#cccccc"},children:[Kr(a),"/s"]})]}),k.jsxs("div",{style:{width:"100%",height:160,border:"1px solid #3c3c3c",background:"#111",padding:"8px 10px 10px",boxSizing:"border-box"},children:[k.jsx("div",{style:{marginBottom:6,color:"#aaa",fontSize:12},children:"Bandwidth (total)"}),k.jsx(BC,{data:l,seriesKeys:["total"],seriesLabels:{total:"Total"},colors:["#4fc1ff"],height:120,tickRate:e,windowSeconds:10})]})]})]})}function ay({enabled:r,initialRect:e,minSize:t}){const[n,i]=N.useState(e),[s,o]=N.useState(!1),a=N.useRef({x:0,y:0}),l=N.useRef({resizing:!1,startX:0,startY:0,startW:0,startH:0});return N.useEffect(()=>{if(!r)return;const d=()=>{i(h=>{const p=Math.max(t.width,window.innerWidth-16),m=Math.max(t.height,window.innerHeight-8*2),S=Math.min(Math.max(t.width,h.width),p),w=Math.min(Math.max(t.height,h.height),m),g=Math.min(Math.max(8,h.x),Math.max(8,window.innerWidth-8-S)),y=Math.min(Math.max(8,h.y),Math.max(8,window.innerHeight-8-w));return{x:g,y,width:S,height:w}})};return d(),window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)},[r,t.height,t.width]),N.useEffect(()=>{if(!r)return;const d=f=>{if(s){i(p=>({...p,x:Math.max(0,f.clientX-a.current.x),y:Math.max(0,f.clientY-a.current.y)}));return}if(l.current.resizing){const p=f.clientX-l.current.startX,m=f.clientY-l.current.startY;i(S=>({...S,width:Math.max(t.width,l.current.startW+p),height:Math.max(t.height,l.current.startH+m)}))}},h=()=>{o(!1),l.current.resizing=!1};return window.addEventListener("mousemove",d),window.addEventListener("mouseup",h),()=>{window.removeEventListener("mousemove",d),window.removeEventListener("mouseup",h)}},[r,s,t.height,t.width]),{rect:n,setRect:i,isDragging:s,startDrag:(d,h)=>{r&&(o(!0),i(f=>(a.current={x:d-f.x,y:h-f.y},f)))},startResize:(d,h)=>{r&&i(f=>(l.current={resizing:!0,startX:d,startY:h,startW:f.width,startH:f.height},f))}}}function ly(r){const[e,t]=N.useState({width:600,height:400}),[n,i]=N.useState({left:0,top:0}),[s,o]=N.useState(null);return N.useLayoutEffect(()=>{const a=r.current??null;o(l=>l===a?l:a)},[r]),N.useEffect(()=>{const a=s;if(!a)return;const l=()=>{const c=a.getBoundingClientRect();i({left:c.left,top:c.top})},u=new ResizeObserver(c=>{const d=c[0];d&&(t({width:d.contentRect.width,height:d.contentRect.height}),l())});return u.observe(a),l(),window.addEventListener("resize",l),()=>{window.removeEventListener("resize",l),u.disconnect()}},[s]),{size:e,rect:n}}function UU(r,e){const[t,n]=N.useState(null),[i,s]=N.useState([]),[o,a]=N.useState(null),[l,u]=N.useState(0),c=N.useMemo(()=>r?r.layers.map(y=>({id:y.id,x:y.origin.x,y:y.origin.y,width:y.width,height:y.height,color:i.includes(y.id)?"rgba(43, 140, 255, 0.7)":void 0})):[],[r,i]),d=N.useMemo(()=>r?r.displays.map(y=>({id:y.id,x:y.origin.x,y:y.origin.y,width:y.size.x,height:y.size.y})):[],[r]),h=N.useMemo(()=>o!=null?c.find(y=>y.id===o)??null:t!=null?d.find(y=>y.id===t)??null:null,[o,t,d,c]),f=N.useMemo(()=>`${t??"none"}-${i.join(",")}-${l}`,[t,i,l]),p=y=>{r!=null&&r.displays.some(C=>C.id===y)&&(u(C=>C+1),n(y),s([]),a(null),e.setVisibleLayers(null))},m=y=>{const C=r==null?void 0:r.layers.find(x=>x.id===y);return C?{x:C.origin.x,y:C.origin.y,width:C.width,height:C.height}:null},S=(y,C)=>{if(e.setVisibleLayersDisplay255(y.length>0?y:null),C!=null){const x=m(C);x&&e.sendDisplayTransform(x)}},w=(y,C)=>{if(!(r!=null&&r.layers.some(I=>I.id===y)))return;const x=!!(C&&(C.metaKey||C.ctrlKey));u(I=>I+1),n(null),s(I=>{if(!x)return I.includes(y)?(a(null),S([],null),[]):(a(y),S([y],y),[y]);const E=I.includes(y)?I.filter(R=>R!==y):[...I,y],A=E.length>0?E[E.length-1]:null;return a(A),S(E,A),E})},g=(y,C)=>{if(!(r!=null&&r.layers.some(I=>I.id===y)))return;const x=!!(C&&(C.metaKey||C.ctrlKey));u(I=>I+1),n(null),s(I=>{if(!x)return I.includes(y)?(a(null),S([],null),[]):(a(y),S([y],y),[y]);const E=I.includes(y)?I.filter(R=>R!==y):[...I,y],A=E.length>0?E[E.length-1]:null;return a(A),S(E,A),E})};return N.useEffect(()=>{if(!r){n(null),s([]),a(null),e.setVisibleLayers(null),e.setVisibleLayersDisplay255(null);return}const y=new Set(r.layers.map(x=>x.id)),C=new Set(r.displays.map(x=>x.id));s(x=>{const I=x.filter(A=>y.has(A)),E=I.length>0?I[I.length-1]:null;return a(E),S(I,E),I}),n(x=>x!=null&&C.has(x)?x:null)},[r,e]),{selectedDisplayId:t,selectedLayerIds:i,lastSelectedLayerId:o,focusKey:f,focusRect:h,handleSelectDisplay:p,handleSelectLayer:w,handleSelectLayerDisplay255Only:g,setFocusNonce:u}}function AU(r){const{enabled:e,snapshot:t,topKeys:n,topTraffic:i}=r,[s,o]=N.useState([]),a=N.useRef(null),l=N.useRef(0),u=N.useRef(i);u.current=i;const c=N.useMemo(()=>n.join(","),[n]);N.useEffect(()=>{e&&o(f=>{if(f.length>0)return f;const p={time:"—"};for(let m=0;m<n.length;m++)p[n[m]]=0;return[p]})},[e,c]),N.useEffect(()=>{var C,x;if(!e||!t)return;const f=((C=t==null?void 0:t.tick)==null?void 0:C.tickRate)??((x=t==null?void 0:t.tick)==null?void 0:x.tps)??60,p=Math.max(1,Math.round(f*60)),m=performance.now?performance.now():Date.now(),S=Math.max(1,Math.round(1e3/f));if(m-l.current<S)return;l.current=m;const g={time:new Date().toLocaleTimeString("en-US",{hour12:!1,minute:"2-digit",second:"2-digit"})},y=u.current;for(let I=0;I<y.length;I++){const E=y[I];g[E.key]=E.bps??0}o(I=>{if(a.current!==f)return a.current=f,[g];const E=I.length===0?[g]:[...I,g];return E.length>p?E.slice(E.length-p):E})},[e,t,c]);const d=a.current??60,h=N.useMemo(()=>{if(!e)return[];const f=new Array(s.length);for(let p=0;p<s.length;p++){const m=s[p],S={time:m.time};for(let w=0;w<n.length;w++){const g=n[w];S[g]=Number(m[g]??0)}f[p]=S}return f},[e,s,n]);return{trafficHistory:s,tickRate:d,chartData:h}}const TU=r=>typeof r!="string"?"8-bit":r.includes("16")?"16-bit":"8-bit";function RU(r){var w;const{primaryUser:e,selection:t,selectedDisplayId:n,lastSelectedLayerId:i,selectedLayerIds:s}=r,o=N.useMemo(()=>((e==null?void 0:e.displays)??[]).map(y=>({id:y.id,x:y.origin.x,y:y.origin.y,width:y.size.x,height:y.size.y})),[e]),a=((w=e==null?void 0:e.layers)==null?void 0:w.length)??0,l=N.useMemo(()=>e?!t.selectedLayerIds.length&&!e?[]:e.layers.map(g=>({id:g.id,x:g.origin.x,y:g.origin.y,width:g.width,height:g.height,zIndex:g.z??0,name:g.name})):[],[e,t.selectedLayerIds.length]),u=N.useMemo(()=>{if(!e)return null;if(s.length){const g=e.layers.find(y=>y.id===i);return g?{type:"layer",item:g}:null}if(n!=null){const g=e.displays.find(y=>y.id===n);return g?{type:"display",item:g}:null}return null},[i,e,n,s.length]),c=N.useMemo(()=>{const y=((e==null?void 0:e.layers)??[]).filter(F=>typeof F.bytesPerSec1s=="number").map(F=>({key:`layer-${F.id}`,id:F.id,name:F.name,encoding:TU(F.charCodeMode),total:F.bytesTotal??0,bps:F.bytesPerSec1s??0,size:{x:F.width,y:F.height},position:{x:F.origin.x,y:F.origin.y},zIndex:F.z??0})),C=(e==null?void 0:e.miscTraffic)??{},x=F=>{switch(F){case"update.audioOrders":return"Audio";case"update.vibrationOrders":return"Vibration";case"update.macroOrders":return"Macro";case"update.postProcessOrders":return"PostProcess";default:return F}},I=Object.entries(C).map(([F,z],P)=>({key:`misc-${F}`,id:1e5+P,name:x(F),total:z.total??0,bps:z.bytesPerSec1s??0,size:{x:0,y:0},position:{x:0,y:0},zIndex:0})),E=((e==null?void 0:e.displays)??[]).filter(F=>F.id!==255),A=(e==null?void 0:e.displayTraffic)??{},R=E.map(F=>{const z=A[F.id];return{key:`display-${F.id}`,id:F.id,name:`Display ${F.id}`,total:(z==null?void 0:z.total)??0,bps:(z==null?void 0:z.bytesPerSec1s)??0,size:{x:F.size.x,y:F.size.y},position:{x:F.origin.x,y:F.origin.y},zIndex:0}}).filter(F=>typeof F.bps=="number");return[...y,...R,...I]},[e]),d=N.useMemo(()=>[...c].sort((g,y)=>y.total-g.total),[c]),h=N.useMemo(()=>d.slice(0,6),[d]),f=N.useMemo(()=>h.map(g=>g.key),[h]),p=N.useMemo(()=>Object.fromEntries(d.map(g=>[g.key,g.name??String(g.id)])),[d]),m=["#4fc1ff","#9cdcfe","#7bd389","#f9d85c","#f38ba8","#c586c0"],S=N.useMemo(()=>{const g={},y=new Set(d.map(x=>x.key)),C=x=>{let I=2166136261;for(let E=0;E<x.length;E++)I^=x.charCodeAt(E),I=Math.imul(I,16777619);return I>>>0};return y.forEach(x=>{const I=/^layer-(\d+)$/.exec(x),E=I?Number(I[1]):NaN,A=Number.isFinite(E)?E:C(x);g[x]=m[A%m.length]??"#4fc1ff"}),g},[d]);return{worldDisplays:o,worldLayers:l,layerCount:a,detailTarget:u,trafficItems:c,sortedTraffic:d,topTraffic:h,topKeys:f,keyToLabel:p,keyToColor:S}}function PU(r){const{runtimeClient:e,serverUrl:t,renderer:n,muted:i,snapshot:s}=r,o=N.useRef(null),a=N.useRef(null),l=N.useRef(null),[u,c]=N.useState({audio:[],atlases:[],palettes:[]}),d=N.useCallback(async()=>{const h=o.current,f=a.current;h&&(l.current=t,e.start({serverUrl:t,container:h,displayContainers:f?[{id:255,container:f}]:void 0,renderer:n,inputEnabled:!0,captureInput:!0}).catch(()=>{}))},[n,e,t]);return N.useEffect(()=>{const h=o.current,f=a.current;h&&l.current!==t&&(l.current=t,e.start({serverUrl:t,container:h,displayContainers:f?[{id:255,container:f}]:void 0,renderer:n,inputEnabled:!0,captureInput:!0}).catch(()=>{}))},[n,e,t]),N.useEffect(()=>{e.setMuted(i)},[i,e]),N.useEffect(()=>{c(e.getAssetsSnapshot())},[e,s]),{rendererContainerRef:o,debugDisplay255ContainerRef:a,connect:d,assetsSnapshot:u,setAssetsSnapshot:c}}function BU({connected:r,placement:e,headerHeight:t,frameRect:n,containerRef:i,onTogglePlacement:s,onStartDrag:o,onStartResize:a}){const l=e==="float";return k.jsxs("div",{style:{position:"fixed",left:n.x,top:n.y,width:n.width,height:n.height,zIndex:l?950:1,background:"#1a1a1a",border:"1px solid #3c3c3c",boxShadow:l?"0 8px 24px rgba(0,0,0,0.35)":"none",display:"flex",flexDirection:"column",userSelect:"none"},children:[k.jsxs("div",{style:{height:t,background:"#2d2d2d",borderBottom:"1px solid #3c3c3c",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px",fontSize:12,color:"#cccccc",cursor:l?"move":"default"},onMouseDown:u=>{l&&o(u.clientX,u.clientY)},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[k.jsx("div",{style:{width:8,height:8,borderRadius:4,background:r?"#4fc1ff":"#a0a0a0"}}),k.jsx("div",{children:"Debug View"})]}),k.jsx("button",{onClick:u=>{u.stopPropagation(),s()},style:{height:22,padding:"0 8px",border:"1px solid #3c3c3c",background:"#3c3c3c",color:"#ffffff",cursor:"pointer",fontSize:12},title:l?"Embed into layout":"Float window",children:l?"Embed":"Float"})]}),k.jsx("div",{ref:i,style:{flex:1,backgroundColor:"#0f0f0f",backgroundImage:"linear-gradient(45deg, rgba(255,255,255,0.05) 25%, transparent 25%),linear-gradient(-45deg, rgba(255,255,255,0.05) 25%, transparent 25%),linear-gradient(45deg, transparent 75%, rgba(255,255,255,0.05) 75%),linear-gradient(-45deg, transparent 75%, rgba(255,255,255,0.05) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0",overflow:"hidden",outline:"1px solid rgba(255,255,255,0.06)"}}),l&&k.jsx("div",{onMouseDown:u=>{u.stopPropagation(),a(u.clientX,u.clientY)},style:{position:"absolute",width:14,height:14,right:2,bottom:2,cursor:"nwse-resize",background:"#2d2d2d",border:"1px solid #3c3c3c",borderRadius:2}})]})}const vl=new aM;function zU(){var Cr;const[r,e]=N.useState(()=>{if(typeof window>"u")return"http://localhost:3200";const{protocol:Se,hostname:Re,port:pe}=window.location;return pe==="4173"||pe==="5173"?`${Se}//${Re}:3200`:`${Se}//${Re}${pe?`:${pe}`:""}`}),t=Ys(Se=>Se.lastSnapshot),n=Ys(Se=>Se.connected),[i,s]=N.useState(!1),[o,a]=N.useState("grid"),[l,u]=N.useState(null),[c,d]=N.useState("float"),[h,f]=N.useState({width:0,height:0}),[p,m]=N.useState("embedded"),[S,w]=N.useState("network"),g=28,y={width:220,height:160},C=c==="float",x=24,I={width:220,height:160},E=ay({enabled:C,initialRect:{x:12,y:80,width:360,height:220},minSize:y}),A=ay({enabled:p==="float",initialRect:{x:12,y:360,width:360,height:260},minSize:I}),R=((Cr=t==null?void 0:t.users)==null?void 0:Cr[0])??null,F=p==="float",z=UU(R,vl),P=z.selectedDisplayId,O=z.selectedLayerIds,L=z.lastSelectedLayerId,V=z.focusRect,X=z.focusKey,T=N.useRef(null),{rect:_,size:j}=ly(T),{worldDisplays:G,worldLayers:ee,detailTarget:q,sortedTraffic:K,topTraffic:oe,topKeys:ve,keyToLabel:ge,keyToColor:Ce}=RU({primaryUser:R,selection:z,selectedDisplayId:P,lastSelectedLayerId:L,selectedLayerIds:O}),{tickRate:ct,chartData:dt}=AU({enabled:!0,snapshot:t,topKeys:ve,topTraffic:oe}),{rendererContainerRef:xe,debugDisplay255ContainerRef:et,connect:Ke,assetsSnapshot:qe}=PU({runtimeClient:vl,serverUrl:r,renderer:Df.TerminalGL,muted:i,snapshot:t});N.useEffect(()=>{const Se="/logo_debugger.ico",Re=document.querySelector("link[rel='icon']");if(Re)Re.href=Se;else{const pe=document.createElement("link");pe.rel="icon",pe.href=Se,document.head.appendChild(pe)}},[]),N.useEffect(()=>{const Se=Re=>{const pe=Re.detail;pe&&vl.sendDisplayTransform(pe)};return window.addEventListener("__utsp_debug_display255_rect",Se),()=>window.removeEventListener("__utsp_debug_display255_rect",Se)},[]),N.useEffect(()=>{const Se=document.documentElement.style.overflow,Re=document.body.style.overflow,pe=document.documentElement.style.margin,ne=document.body.style.margin,$e=document.documentElement.style.padding,ht=document.body.style.padding;return document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.documentElement.style.margin="0",document.body.style.margin="0",document.documentElement.style.padding="0",document.body.style.padding="0",()=>{document.documentElement.style.overflow=Se,document.body.style.overflow=Re,document.documentElement.style.margin=pe,document.body.style.margin=ne,document.documentElement.style.padding=$e,document.body.style.padding=ht}},[]);const At=N.useRef(null),{size:wt,rect:Ft}=ly(At);N.useEffect(()=>{const Se=xe.current;if(!Se)return;const Re=new ResizeObserver(pe=>{const ne=pe[0];ne&&f({width:Math.round(ne.contentRect.width),height:Math.round(ne.contentRect.height)})});return Re.observe(Se),()=>Re.disconnect()},[]);const cr=wt.width,tt=wt.height,kt={left:C?E.rect.x:Ft.left,top:C?E.rect.y:Ft.top,width:C?E.rect.width:cr,height:C?E.rect.height:tt},nt=F?A.rect:{x:_.left??0,y:_.top??0,width:j.width||280,height:j.height||260};return k.jsxs("div",{style:{fontFamily:"'Segoe UI', 'Helvetica Neue', sans-serif",background:"#1e1e1e",color:"#cccccc",minHeight:"100vh",margin:0,display:"flex",flexDirection:"column"},children:[k.jsx(gM,{connected:n,serverUrl:r,onServerUrlChange:e,onReconnect:()=>{Ke()}}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"240px 1fr 280px",gap:0,padding:0,boxSizing:"border-box",flex:1,minHeight:0,overflow:"hidden"},children:[k.jsx("div",{style:{borderRight:"1px solid #3c3c3c",background:"#252526",display:"flex",flexDirection:"column",minHeight:0},children:k.jsx(pM,{primaryUser:R??null,selectedDisplayId:P,selectedLayerIds:O,onSelectDisplay:z.handleSelectDisplay,onSelectLayer:z.handleSelectLayerDisplay255Only})}),k.jsx(kU,{centerTab:o,setCenterTab:a,centerPanelRef:At,centerSize:wt,worldLayers:ee,worldDisplays:G,selectedLayerIds:O,setVisibleLayers:Se=>vl.setVisibleLayers(Se),selectedDisplayId:P,focusRect:V,focusKey:X,onSelectLayer:z.handleSelectLayer,onSelectDisplay:z.handleSelectDisplay,assetsSnapshot:qe,primaryUser:R,isFloating:C,sortedTraffic:K,topTraffic:oe,chartData:dt,topKeys:ve,keyToLabel:ge,keyToColor:Ce,tickRate:ct,hoveredTrafficKey:l,setHoveredTrafficKey:u}),k.jsxs("div",{style:{borderLeft:"1px solid #3c3c3c",background:"#252526",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto",overflowX:"hidden"},children:[k.jsx("div",{ref:T,style:{padding:0,borderBottom:"1px solid #3c3c3c",height:260,minHeight:260,width:"100%",boxSizing:"border-box"}}),k.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid #3c3c3c"},children:[{id:"network",label:"Network"},{id:"layer",label:"Selected Layer"}].map(Se=>{const Re=S===Se.id;return k.jsx("button",{onClick:()=>w(Se.id),style:{border:"1px solid #3c3c3c",background:Re?"#1e1e1e":"#2d2d2d",color:"#cccccc",padding:"4px 10px",cursor:"pointer",fontSize:12,borderRadius:6},children:Se.label},Se.id)})}),k.jsx("div",{style:{flex:1,minHeight:0},children:S==="network"?k.jsx(MU,{primaryUser:R,tickRate:ct,snapshot:t,assetsSnapshot:qe}):k.jsx("div",{style:{height:"100%",minHeight:0},children:k.jsx(dM,{detailTarget:q})})})]})]}),k.jsx(lM,{connected:n,muted:i,rendererPlacement:c,centerTab:o,frameRect:kt,rendererHeaderHeight:g,rendererContentSize:h,rendererContainerRef:xe,onTogglePlacement:()=>{d(Se=>{const Re=Se==="float"?"embedded":"float";return Re==="embedded"&&a("renderer"),Re})},onToggleMuted:()=>{s(Se=>!Se)},onStartDrag:(Se,Re)=>{E.startDrag(Se,Re)},onStartResize:(Se,Re)=>{E.startResize(Se,Re)}}),k.jsx(BU,{connected:n,placement:p,headerHeight:x,frameRect:nt,containerRef:et,onTogglePlacement:()=>m(Se=>Se==="float"?"embedded":"float"),onStartDrag:A.startDrag,onStartResize:A.startResize})]})}const OC=document.getElementById("root");if(!OC)throw new Error("Root container not found");td.createRoot(OC).render(k.jsx(Cy.StrictMode,{children:k.jsx(zU,{})}));
|
|
273
|
+
*/var zu=N,WE=YE;function GE(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var XE=typeof Object.is=="function"?Object.is:GE,KE=WE.useSyncExternalStore,ZE=zu.useRef,qE=zu.useEffect,QE=zu.useMemo,JE=zu.useDebugValue;Hw.useSyncExternalStoreWithSelector=function(r,e,t,n,i){var s=ZE(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=QE(function(){function l(f){if(!u){if(u=!0,c=f,f=n(f),i!==void 0&&o.hasValue){var p=o.value;if(i(p,f))return d=p}return d=f}if(p=d,XE(c,f))return p;var m=n(f);return i!==void 0&&i(p,m)?(c=f,p):(c=f,d=m)}var u=!1,c,d,h=t===void 0?null:t;return[function(){return l(e())},h===null?void 0:function(){return l(h())}]},[e,t,n,i]);var a=KE(r,s[0],s[1]);return qE(function(){o.hasValue=!0,o.value=a},[a]),JE(a),a};Vw.exports=Hw;var eM=Vw.exports;const tM=uy(eM),Ww={},{useDebugValue:rM}=Cy,{useSyncExternalStoreWithSelector:nM}=tM;let hm=!1;const iM=r=>r;function sM(r,e=iM,t){(Ww?"production":void 0)!=="production"&&t&&!hm&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),hm=!0);const n=nM(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return rM(n),n}const fm=r=>{(Ww?"production":void 0)!=="production"&&typeof r!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof r=="function"?OE(r):r,t=(n,i)=>sM(e,n,i);return Object.assign(t,e),t},oM=r=>r?fm(r):fm,Ys=oM(r=>({connected:!1,lastSnapshot:void 0,setConnected:e=>r({connected:e}),setSnapshot:e=>r({lastSnapshot:e})}));class aM{constructor(){Wi(this,"runtime",null);Wi(this,"layerTraffic",{});Wi(this,"miscTraffic",{});Wi(this,"displayTraffic",{});Wi(this,"visibleLayerIds",null);Wi(this,"visibleLayerIdsDisplay255",null)}setMuted(e){var n;const t=(n=this.runtime)==null?void 0:n.getAudioManager();t&&t.setMasterVolume(e?0:1)}setVisibleLayers(e){var i;this.visibleLayerIds=e&&e.length>0?[...e]:null;const t=(i=this.runtime)==null?void 0:i.getRendererManager(0);if(!t)return;if(this.visibleLayerIds==null){t.setLayerFilter(null);return}const n=new Set(this.visibleLayerIds);t.setLayerFilter(s=>n.has(s.getId()))}setVisibleLayersDisplay255(e){var i;this.visibleLayerIdsDisplay255=e&&e.length>0?[...e]:null;const t=(i=this.runtime)==null?void 0:i.getRendererManager(255);if(!t)return;if(this.visibleLayerIdsDisplay255==null){t.setLayerFilter(null);return}const n=new Set(this.visibleLayerIdsDisplay255);t.setLayerFilter(s=>n.has(s.getId()))}sendDisplayTransform(e){var t;(t=this.runtime)==null||t.sendBridge("__debug_display_255",{origin:{x:e.x,y:e.y},size:{x:e.width,y:e.height}})}async start(e){Ys.getState().setConnected(!1),this.runtime&&this.destroy();const t={mode:"socketio",socketio:{url:e.serverUrl},container:e.container,displayContainers:e.displayContainers,renderer:e.renderer??Of.TerminalGL,inputEnabled:e.inputEnabled??!0,captureInput:e.captureInput??!0,debug:!1,autoplay:!1};try{if(this.runtime=new TE(t),this.visibleLayerIds&&this.visibleLayerIds.length>0){const n=new Set(this.visibleLayerIds);this.runtime.getRendererManager().setLayerFilter(i=>n.has(i.getId()))}if(this.visibleLayerIdsDisplay255&&this.visibleLayerIdsDisplay255.length>0){const n=new Set(this.visibleLayerIdsDisplay255);this.runtime.getRendererManager(255).setLayerFilter(i=>n.has(i.getId()))}this.runtime.onBridge("__debug_meta",n=>{var i,s,o,a;try{let l=n;if(this.runtime&&n&&typeof n=="object"){try{this.layerTraffic=this.runtime.getLayerTrafficStats()}catch{this.layerTraffic={}}try{this.miscTraffic=((s=(i=this.runtime).getMiscTrafficStats)==null?void 0:s.call(i))??{}}catch{this.miscTraffic={}}try{this.displayTraffic=((a=(o=this.runtime).getDisplayTrafficStats)==null?void 0:a.call(o))??{}}catch{this.displayTraffic={}}const u=n;if(u.users&&Array.isArray(u.users))for(const c of u.users)c.layers&&Array.isArray(c.layers)&&(c.layers=c.layers.map(d=>{const h=this.layerTraffic[d.id];return h?{...d,bytesTotal:h.total,bytesPerSec1s:h.bytesPerSec1s}:d})),c.miscTraffic=this.miscTraffic,c.displayTraffic=this.displayTraffic;l=u}Ys.getState().setConnected(!0),Ys.getState().setSnapshot(l)}catch{}}),await this.runtime.start(),this.runtime.sendBridge("__debug_auth",{})}catch(n){throw Ys.getState().setConnected(!1),n}}destroy(){var e,t,n,i;if(this.runtime){try{(t=(e=this.runtime.getAudioManager())==null?void 0:e.stopAll)==null||t.call(e)}catch{}try{(i=(n=this.runtime).destroy)==null||i.call(n)}catch{}this.runtime=null}}getAssetsSnapshot(){var u;const e=this.runtime;if(!e)return{audio:[],atlases:[],palettes:[]};const t=e.getAudioManager(),n=(u=t==null?void 0:t.getSoundBank)==null?void 0:u.call(t),i=n?n.getAll().map(c=>({id:c.soundId,name:c.name,duration:c.duration,source:c.metadata.source,originalSize:c.metadata.originalSize,originalUrl:c.metadata.originalUrl})):[],s=e.getCore(),o=s.getImageFontRegistry(),a=o.getAllFonts().map(c=>({id:c.getFontId(),name:o.getFontName(c.getFontId())??`Font ${c.getFontId()}`,glyphSize:`${c.getGlyphWidth()}×${c.getGlyphHeight()}`,cellSize:`${c.getCellWidth()}×${c.getCellHeight()}`,atlasBlocks:c.getAtlasBlocks(),maxCharCode:c.getMaxCharCode()}));a.length===0&&a.push({id:0,name:"Default CP437 (builtin)",glyphSize:"8×8",cellSize:"8×8",atlasBlocks:1,maxCharCode:255});const l=[];for(let c=0;c<256;c++){if(!s.hasPaletteSlot(c))continue;const d=s.getPaletteFromSlot(c);l.push({slotId:c,colors:(d==null?void 0:d.size)??0})}return{audio:i,atlases:a,palettes:l}}}function lM({connected:r,muted:e,rendererPlacement:t,centerTab:n,frameRect:i,rendererHeaderHeight:s,rendererContentSize:o,rendererContainerRef:a,onTogglePlacement:l,onToggleMuted:u,onStartDrag:c,onStartResize:d}){const h=t==="float";return k.jsxs("div",{style:{position:"fixed",left:i.left,top:i.top,width:i.width,height:i.height,zIndex:h?1e3:10,background:"#1a1a1a",border:"1px solid #3c3c3c",boxShadow:h?"0 8px 24px rgba(0,0,0,0.45)":"none",userSelect:"none",pointerEvents:h||n==="renderer"?"auto":"none",display:h||n==="renderer"?"block":"none"},children:[k.jsxs("div",{style:{height:s,background:"#2d2d2d",borderBottom:"1px solid #3c3c3c",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px",cursor:h?"move":"default",fontSize:12,color:"#cccccc"},onMouseDown:f=>{h&&c(f.clientX,f.clientY)},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[k.jsx("div",{style:{width:8,height:8,borderRadius:4,background:r?"#4fc1ff":"#a0a0a0"}}),k.jsx("div",{children:"UTSP Client"}),k.jsxs("div",{style:{color:"#888888",fontSize:11},children:[o.width,"×",o.height," px"]})]}),k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,cursor:"default"},onMouseDown:f=>f.stopPropagation(),children:[k.jsx("button",{onClick:f=>{f.stopPropagation(),l()},style:{height:24,padding:"0 8px",border:"1px solid #3c3c3c",background:"#3c3c3c",color:"#ffffff",cursor:"pointer",fontSize:12},title:h?"Embed into layout":"Float window",children:h?"Embed":"Float"}),k.jsx("button",{onClick:f=>{f.stopPropagation(),u()},style:{width:28,height:24,border:"1px solid #3c3c3c",background:e?"#3c3c3c":"#0e639c",color:"#ffffff",cursor:"pointer",fontSize:12,display:"flex",alignItems:"center",justifyContent:"center",padding:0},title:e?"Unmute audio":"Mute audio",children:k.jsxs("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[k.jsx("path",{d:"M4 9v6h4l5 4V5L8 9H4z"}),!e&&k.jsx("path",{d:"M16 9a5 5 0 0 1 0 6"}),!e&&k.jsx("path",{d:"M18 5a9 9 0 0 1 0 14"}),e&&k.jsx("line",{x1:"17",y1:"9",x2:"21",y2:"13"}),e&&k.jsx("line",{x1:"21",y1:"9",x2:"17",y2:"13"})]})})]})]}),k.jsx("div",{ref:a,style:{position:"absolute",top:s,left:0,right:0,bottom:0,background:"#0d0d0d",overflow:"hidden",opacity:1,pointerEvents:"auto",outline:"1px solid #3c3c3c"},tabIndex:0,onMouseDown:f=>{var p;f.stopPropagation(),(p=a.current)==null||p.focus()}}),h&&k.jsx("div",{onMouseDown:f=>{f.stopPropagation(),d(f.clientX,f.clientY)},style:{position:"absolute",width:14,height:14,right:2,bottom:2,cursor:"nwse-resize",background:"#2d2d2d",border:"1px solid #3c3c3c",borderRadius:2}})]})}function Kr(r){if(r==null||Number.isNaN(r))return"—";const e=["B","KB","MB","GB"];let t=r,n=0;for(;t>=1024&&n<e.length-1;)t/=1024,n++;return`${t.toFixed(t>=10?0:1)} ${e[n]}`}function uM(r){return`${r.toFixed(2)} s`}const cM={muted:{background:"#1a1a1a",border:"#2f2f2f",color:"#cfcfcf"},info:{background:"#1a2531",border:"#2f4f6b",color:"#8dc8ff"},success:{background:"#182420",border:"#2b4d37",color:"#7dd19c"},warning:{background:"#292114",border:"#514021",color:"#eac172"}};function Lo({label:r,tone:e="muted"}){const t=cM[e];return k.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"1px 6px",borderRadius:6,fontSize:10,fontWeight:600,letterSpacing:"0.05px",background:t.background,border:`1px solid ${t.border}`,color:t.color},children:r})}function pm({children:r}){return k.jsx("div",{style:{border:"1px solid #2a2a2a",borderRadius:6,background:"#161616"},children:r})}function Xn({label:r,value:e,divider:t}){return k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"6px 8px",fontSize:11,color:"#d6d6d6",borderBottom:t?"1px solid #222":"none"},children:[k.jsx("span",{style:{color:"#9a9a9a",letterSpacing:"0.05px"},children:r}),k.jsx("span",{style:{fontWeight:600,textAlign:"right"},children:e})]})}function dM({detailTarget:r}){return k.jsxs("div",{style:{background:"transparent",padding:0,minHeight:0,display:"flex",flexDirection:"column"},children:[k.jsx("div",{style:{padding:"8px 12px",borderBottom:"1px solid #3c3c3c"},children:k.jsx("div",{style:{fontSize:11,color:"#bbbbbb",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Properties"})}),k.jsxs("div",{style:{padding:"8px 12px",flex:1,overflowY:"auto"},children:[!r&&k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Hover or select an item"}),(r==null?void 0:r.type)==="display"&&k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:6,padding:"2px 0"},children:[k.jsxs("div",{style:{color:"#e7f3ff",fontWeight:600},children:["Display ",r.item.id]}),k.jsx(Lo,{label:"Active",tone:"info"})]}),k.jsxs(pm,{children:[k.jsx(Xn,{label:"Origin",value:`(${r.item.origin.x}, ${r.item.origin.y})`,divider:!0}),k.jsx(Xn,{label:"Size",value:`${r.item.size.x} × ${r.item.size.y}`})]})]}),(r==null?void 0:r.type)==="layer"&&k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:6,padding:"2px 0"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[k.jsx("div",{style:{color:"#e7f3ff",fontWeight:700},children:r.item.name??"Layer"}),k.jsx(Lo,{label:`#${r.item.id}`,tone:"info"})]}),k.jsx(Lo,{label:`z ${r.item.z}`,tone:"muted"})]}),k.jsxs(pm,{children:[k.jsx(Xn,{label:"Mode",value:r.item.charCodeMode,divider:!0}),k.jsx(Xn,{label:"Orders",value:r.item.ordersCount,divider:!0}),k.jsx(Xn,{label:"Size",value:`${r.item.width} × ${r.item.height}`,divider:!0}),k.jsx(Xn,{label:"Origin",value:`(${r.item.origin.x}, ${r.item.origin.y})`,divider:!0}),k.jsx(Xn,{label:"Channel",value:r.item.mustBeReliable?k.jsx(Lo,{label:"Reliable",tone:"success"}):k.jsx(Lo,{label:"Volatile",tone:"muted"}),divider:!0}),r.item.bytesTotal!==void 0&&k.jsxs(k.Fragment,{children:[k.jsx(Xn,{label:"Total",value:Kr(r.item.bytesTotal),divider:!0}),k.jsx(Xn,{label:"Throughput",value:`${Kr(r.item.bytesPerSec1s)} /s`})]})]})]})]})]})}function gm({isSelected:r,onClick:e,children:t}){return k.jsx("div",{onClick:e,style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"2px 12px",cursor:"pointer",fontSize:12,background:r?"#094771":"transparent",color:r?"#ffffff":"#cccccc",userSelect:"none"},children:t})}function hM(r){return r<1e3?`${r} B`:r<1e6?`${(r/1e3).toFixed(2)} KB`:`${(r/1e6).toFixed(2)} MB`}const Ms={id:"1fr",net:"90px",gap:4};function fM({displays:r,layers:e,selectedDisplayId:t,selectedLayerIds:n,onSelectDisplay:i,onSelectLayer:s}){const o=new Set(n),[a,l]=N.useState("id"),[u,c]=N.useState("asc"),d=N.useMemo(()=>{const f=[...e];return f.sort((p,m)=>{const S=a==="id"?p.id:p.bytesTotal??0,w=a==="id"?m.id:m.bytesTotal??0,g=S===w?0:S<w?-1:1;return u==="asc"?g:-g}),f},[e,u,a]),h=f=>{l(p=>p===f?(c(m=>m==="asc"?"desc":"asc"),p):(c("asc"),f))};return k.jsxs("div",{style:{padding:"4px 0",overflowY:"auto",flex:1,display:"flex",flexDirection:"column",gap:0,userSelect:"none"},children:[r.length===0&&e.length===0&&k.jsx("div",{style:{fontSize:12,color:"#858585",padding:"4px 12px"},children:"No items"}),r.length>0&&k.jsxs(k.Fragment,{children:[k.jsx("div",{style:{fontSize:10,color:"#858585",padding:"6px 12px 2px",textTransform:"uppercase"},children:"Displays"}),r.map(f=>k.jsxs(gm,{isSelected:t===f.id,onClick:()=>i(f.id),children:[k.jsxs("span",{children:["Display ",f.id,f.id===255?" (debug)":""]}),k.jsxs("span",{style:{color:"#858585",fontSize:11},children:[f.size.x,"×",f.size.y]})]},`display-${f.id}`))]}),e.length>0&&k.jsxs(k.Fragment,{children:[k.jsx("div",{style:{fontSize:10,color:"#858585",padding:"8px 12px 4px",textTransform:"uppercase"},children:"Layers"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:`${Ms.id} ${Ms.net}`,alignItems:"center",columnGap:Ms.gap,padding:"0 12px 4px",fontSize:11,color:"#858585",userSelect:"none"},children:[k.jsxs("button",{type:"button",onClick:()=>h("id"),style:{all:"unset",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4,color:"#858585",justifySelf:"start",whiteSpace:"nowrap"},children:["ID",k.jsx("span",{style:{fontSize:10,opacity:a==="id"?1:.3},children:a==="id"?u==="asc"?"▲":"▼":"▲"})]}),k.jsxs("button",{type:"button",onClick:()=>h("net"),style:{all:"unset",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4,color:"#858585",justifySelf:"end",whiteSpace:"nowrap"},children:["Network",k.jsx("span",{style:{fontSize:10,opacity:a==="net"?1:.3},children:a==="net"?u==="asc"?"▲":"▼":"▲"})]})]}),d.map(f=>{const p=o.has(f.id),m=f.name?`${f.id}:${f.name}`:String(f.id);return k.jsx(gm,{isSelected:p,onClick:S=>s(f.id,S),children:k.jsxs("span",{style:{display:"grid",gridTemplateColumns:`${Ms.id} ${Ms.net}`,alignItems:"center",columnGap:Ms.gap,width:"100%"},children:[k.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:k.jsx("span",{style:{color:"inherit"},children:m})}),k.jsx("span",{style:{color:"#858585",fontSize:11,textAlign:"right",whiteSpace:"nowrap"},children:f.bytesTotal!==void 0&&hM(f.bytesTotal)})]})},`layer-${f.id}-${p}`)})]})]})}function pM({primaryUser:r,selectedDisplayId:e,selectedLayerIds:t,onSelectDisplay:n,onSelectLayer:i}){var s;return k.jsxs("div",{style:{borderRight:"1px solid #3c3c3c",background:"#252526",display:"flex",flexDirection:"column",minHeight:0},children:[k.jsx("div",{style:{padding:"8px 12px",borderBottom:"1px solid #3c3c3c"},children:k.jsx("div",{style:{fontSize:11,color:"#bbbbbb",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Explorer"})}),k.jsxs("div",{style:{padding:"4px 0",overflowY:"auto",flex:1,display:"flex",flexDirection:"column",gap:0,userSelect:"none"},children:[!r&&k.jsx("div",{style:{fontSize:12,color:"#858585",padding:"4px 12px"},children:"No items"}),r&&k.jsx(fM,{displays:(s=r.displays)==null?void 0:s.filter(o=>o.id!==255),layers:r.layers,selectedDisplayId:e,selectedLayerIds:t,onSelectDisplay:n,onSelectLayer:i})]})]})}function gM({connected:r,serverUrl:e,onServerUrlChange:t,onReconnect:n}){return k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",height:34,padding:"0 10px",borderBottom:"1px solid #3c3c3c",background:"#252526"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[k.jsx("img",{src:"/logo_debugger.png",alt:"UTSP logo",style:{width:18,height:18,objectFit:"contain"}}),k.jsx("div",{style:{fontSize:13,color:"#cccccc",fontWeight:600},children:"UTSP Visual Debugger"})]}),k.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,color:r?"#9adcff":"#bbbbbb"},children:[k.jsx("span",{style:{width:8,height:8,borderRadius:4,background:r?"#4fc1ff":"#a0a0a0",display:"inline-block"}}),k.jsx("span",{children:r?"Connected":"Disconnected"})]}),k.jsx("input",{value:e,onChange:i=>t(i.target.value),style:{width:220,padding:"4px 8px",borderRadius:0,border:"1px solid #3c3c3c",background:"#3c3c3c",color:"#cccccc",fontSize:12},placeholder:"http://localhost:3000"}),k.jsx("button",{onClick:n,style:{padding:"4px 10px",borderRadius:0,border:"1px solid #0e639c",background:"#0e639c",color:"#ffffff",fontWeight:500,cursor:"pointer",fontSize:12},children:"Reconnect"})]})]})}function Yc({title:r,headers:e,rows:t,emptyLabel:n}){const i=t.length>0;return k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{fontSize:12,color:"#bbbbbb"},children:r}),k.jsxs("div",{style:{border:"1px solid #3c3c3c",borderRadius:2,overflow:"hidden",background:"#1e1e1e"},children:[k.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.length}, minmax(0, 1fr))`,gap:0,background:"#252526",borderBottom:"1px solid #3c3c3c",fontSize:11,color:"#aaaaaa"},children:e.map(s=>k.jsx("div",{style:{padding:"6px 8px",whiteSpace:"nowrap"},children:s},s))}),!i&&k.jsx("div",{style:{padding:"8px 10px",color:"#858585",fontSize:12},children:n}),i&&k.jsx("div",{children:t.map((s,o)=>k.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.length}, minmax(0, 1fr))`,gap:0,borderTop:o===0?"none":"1px solid #2e2e2e",fontSize:12,color:"#cccccc"},children:s.map((a,l)=>k.jsx("div",{style:{padding:"6px 8px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:a,children:a},l))},`${r}-${o}`))})]})]})}function mM({assetsSnapshot:r}){return k.jsxs("div",{style:{height:"100%",overflow:"auto",padding:"8px 10px",display:"flex",flexDirection:"column",gap:12,color:"#cccccc",fontSize:12},children:[k.jsx(Yc,{title:"Audio",emptyLabel:"No audio loaded",headers:["Name","Source","Duration","Size","URL"],rows:r.audio.map(e=>[e.name,e.source,uM(e.duration),Kr(e.originalSize),e.originalUrl??"—"])}),k.jsx(Yc,{title:"Atlas",emptyLabel:"No atlas",headers:["ID","Name","Glyph","Cell","Blocks","Max char"],rows:r.atlases.map(e=>[String(e.id),e.name,e.glyphSize,e.cellSize,String(e.atlasBlocks),String(e.maxCharCode)])}),k.jsx(Yc,{title:"Palettes",emptyLabel:"No palette",headers:["Slot","Colors"],rows:r.palettes.map(e=>[String(e.slotId),String(e.colors)])})]})}const yM=!0,Gt="u-",vM="uplot",wM=Gt+"hz",CM=Gt+"vt",bM=Gt+"title",SM=Gt+"wrap",xM=Gt+"under",IM=Gt+"over",kM=Gt+"axis",Ji=Gt+"off",EM=Gt+"select",MM=Gt+"cursor-x",UM=Gt+"cursor-y",AM=Gt+"cursor-pt",TM=Gt+"legend",RM=Gt+"live",PM=Gt+"inline",BM=Gt+"series",zM=Gt+"marker",mm=Gt+"label",OM=Gt+"value",Go="width",Xo="height",_o="top",ym="bottom",Us="left",Wc="right",Df="#000",vm=Df+"0",Gc="mousemove",wm="mousedown",Xc="mouseup",Cm="mouseenter",bm="mouseleave",Sm="dblclick",DM="resize",FM="scroll",xm="change",uu="dppxchange",Ff="--",yo=typeof window<"u",gh=yo?document:null,Js=yo?window:null,LM=yo?navigator:null;let je,hl;function mh(){let r=devicePixelRatio;je!=r&&(je=r,hl&&vh(xm,hl,mh),hl=matchMedia(`(min-resolution: ${je-.001}dppx) and (max-resolution: ${je+.001}dppx)`),ss(xm,hl,mh),Js.dispatchEvent(new CustomEvent(uu)))}function Wr(r,e){if(e!=null){let t=r.classList;!t.contains(e)&&t.add(e)}}function yh(r,e){let t=r.classList;t.contains(e)&&t.remove(e)}function lt(r,e,t){r.style[e]=t+"px"}function Cn(r,e,t,n){let i=gh.createElement(r);return e!=null&&Wr(i,e),t!=null&&t.insertBefore(i,n),i}function on(r,e){return Cn("div",r,e)}const Im=new WeakMap;function _n(r,e,t,n,i){let s="translate("+e+"px,"+t+"px)",o=Im.get(r);s!=o&&(r.style.transform=s,Im.set(r,s),e<0||t<0||e>n||t>i?Wr(r,Ji):yh(r,Ji))}const km=new WeakMap;function Em(r,e,t){let n=e+t,i=km.get(r);n!=i&&(km.set(r,n),r.style.background=e,r.style.borderColor=t)}const Mm=new WeakMap;function Um(r,e,t,n){let i=e+""+t,s=Mm.get(r);i!=s&&(Mm.set(r,i),r.style.height=t+"px",r.style.width=e+"px",r.style.marginLeft=n?-e/2+"px":0,r.style.marginTop=n?-t/2+"px":0)}const Lf={passive:!0},_M={...Lf,capture:!0};function ss(r,e,t,n){e.addEventListener(r,t,n?_M:Lf)}function vh(r,e,t,n){e.removeEventListener(r,t,Lf)}yo&&mh();function In(r,e,t,n){let i;t=t||0,n=n||e.length-1;let s=n<=2147483647;for(;n-t>1;)i=s?t+n>>1:Qr((t+n)/2),e[i]<r?t=i:n=i;return r-e[t]<=e[n]-r?t:n}function Gw(r){return(t,n,i)=>{let s=-1,o=-1;for(let a=n;a<=i;a++)if(r(t[a])){s=a;break}for(let a=i;a>=n;a--)if(r(t[a])){o=a;break}return[s,o]}}const Xw=r=>r!=null,Kw=r=>r!=null&&r>0,Ou=Gw(Xw),$M=Gw(Kw);function NM(r,e,t,n=0,i=!1){let s=i?$M:Ou,o=i?Kw:Xw;[e,t]=s(r,e,t);let a=r[e],l=r[e];if(e>-1)if(n==1)a=r[e],l=r[t];else if(n==-1)a=r[t],l=r[e];else for(let u=e;u<=t;u++){let c=r[u];o(c)&&(c<a?a=c:c>l&&(l=c))}return[a??Qe,l??-Qe]}function Du(r,e,t,n){let i=Rm(r),s=Rm(e);r==e&&(i==-1?(r*=t,e/=t):(r/=t,e*=t));let o=t==10?ei:Zw,a=i==1?Qr:an,l=s==1?an:Qr,u=a(o(jt(r))),c=l(o(jt(e))),d=lo(t,u),h=lo(t,c);return t==10&&(u<0&&(d=Je(d,-u)),c<0&&(h=Je(h,-c))),n||t==2?(r=d*i,e=h*s):(r=eC(r,d),e=Fu(e,h)),[r,e]}function _f(r,e,t,n){let i=Du(r,e,t,n);return r==0&&(i[0]=0),e==0&&(i[1]=0),i}const $f=.1,Am={mode:3,pad:$f},ca={pad:0,soft:null,mode:0},VM={min:ca,max:ca};function cu(r,e,t,n){return Lu(t)?Tm(r,e,t):(ca.pad=t,ca.soft=n?0:null,ca.mode=n?3:0,Tm(r,e,VM))}function _e(r,e){return r??e}function HM(r,e,t){for(e=_e(e,0),t=_e(t,r.length-1);e<=t;){if(r[e]!=null)return!0;e++}return!1}function Tm(r,e,t){let n=t.min,i=t.max,s=_e(n.pad,0),o=_e(i.pad,0),a=_e(n.hard,-Qe),l=_e(i.hard,Qe),u=_e(n.soft,Qe),c=_e(i.soft,-Qe),d=_e(n.mode,0),h=_e(i.mode,0),f=e-r,p=ei(f),m=Mr(jt(r),jt(e)),S=ei(m),w=jt(S-p);(f<1e-24||w>10)&&(f=0,(r==0||e==0)&&(f=1e-24,d==2&&u!=Qe&&(s=0),h==2&&c!=-Qe&&(o=0)));let g=f||m||1e3,y=ei(g),C=lo(10,Qr(y)),x=g*(f==0?r==0?.1:1:s),I=Je(eC(r-x,C/10),24),E=r>=u&&(d==1||d==3&&I<=u||d==2&&I>=u)?u:Qe,A=Mr(a,I<E&&r>=E?E:En(E,I)),R=g*(f==0?e==0?.1:1:o),F=Je(Fu(e+R,C/10),24),z=e<=c&&(h==1||h==3&&F>=c||h==2&&F<=c)?c:-Qe,P=En(l,F>z&&e<=z?z:Mr(z,F));return A==P&&A==0&&(P=100),[A,P]}const jM=new Intl.NumberFormat(yo?LM.language:"en-US"),Nf=r=>jM.format(r),rn=Math,zl=rn.PI,jt=rn.abs,Qr=rn.floor,$t=rn.round,an=rn.ceil,En=rn.min,Mr=rn.max,lo=rn.pow,Rm=rn.sign,ei=rn.log10,Zw=rn.log2,YM=(r,e=1)=>rn.sinh(r)*e,Kc=(r,e=1)=>rn.asinh(r/e),Qe=1/0;function Pm(r){return(ei((r^r>>31)-(r>>31))|0)+1}function wh(r,e,t){return En(Mr(r,e),t)}function qw(r){return typeof r=="function"}function Pe(r){return qw(r)?r:()=>r}const WM=()=>{},Qw=r=>r,Jw=(r,e)=>e,GM=r=>null,Bm=r=>!0,zm=(r,e)=>r==e,XM=/\.\d*?(?=9{6,}|0{6,})/gm,ds=r=>{if(rC(r)||zi.has(r))return r;const e=`${r}`,t=e.match(XM);if(t==null)return r;let n=t[0].length-1;if(e.indexOf("e-")!=-1){let[i,s]=e.split("e");return+`${ds(i)}e${s}`}return Je(r,n)};function qi(r,e){return ds(Je(ds(r/e))*e)}function Fu(r,e){return ds(an(ds(r/e))*e)}function eC(r,e){return ds(Qr(ds(r/e))*e)}function Je(r,e=0){if(rC(r))return r;let t=10**e,n=r*t*(1+Number.EPSILON);return $t(n)/t}const zi=new Map;function tC(r){return((""+r).split(".")[1]||"").length}function Ta(r,e,t,n){let i=[],s=n.map(tC);for(let o=e;o<t;o++){let a=jt(o),l=Je(lo(r,o),a);for(let u=0;u<n.length;u++){let c=r==10?+`${n[u]}e${o}`:n[u]*l,d=(o>=0?0:a)+(o>=s[u]?0:s[u]),h=r==10?c:Je(c,d);i.push(h),zi.set(h,d)}}return i}const da={},Vf=[],uo=[null,null],mi=Array.isArray,rC=Number.isInteger,KM=r=>r===void 0;function Om(r){return typeof r=="string"}function Lu(r){let e=!1;if(r!=null){let t=r.constructor;e=t==null||t==Object}return e}function ZM(r){return r!=null&&typeof r=="object"}const qM=Object.getPrototypeOf(Uint8Array),nC="__proto__";function co(r,e=Lu){let t;if(mi(r)){let n=r.find(i=>i!=null);if(mi(n)||e(n)){t=Array(r.length);for(let i=0;i<r.length;i++)t[i]=co(r[i],e)}else t=r.slice()}else if(r instanceof qM)t=r.slice();else if(e(r)){t={};for(let n in r)n!=nC&&(t[n]=co(r[n],e))}else t=r;return t}function zt(r){let e=arguments;for(let t=1;t<e.length;t++){let n=e[t];for(let i in n)i!=nC&&(Lu(r[i])?zt(r[i],co(n[i])):r[i]=co(n[i]))}return r}const QM=0,JM=1,e5=2;function t5(r,e,t){for(let n=0,i,s=-1;n<e.length;n++){let o=e[n];if(o>s){for(i=o-1;i>=0&&r[i]==null;)r[i--]=null;for(i=o+1;i<t&&r[i]==null;)r[s=i++]=null}}}function r5(r,e){if(s5(r)){let o=r[0].slice();for(let a=1;a<r.length;a++)o.push(...r[a].slice(1));return o5(o[0])||(o=i5(o)),o}let t=new Set;for(let o=0;o<r.length;o++){let l=r[o][0],u=l.length;for(let c=0;c<u;c++)t.add(l[c])}let n=[Array.from(t).sort((o,a)=>o-a)],i=n[0].length,s=new Map;for(let o=0;o<i;o++)s.set(n[0][o],o);for(let o=0;o<r.length;o++){let a=r[o],l=a[0];for(let u=1;u<a.length;u++){let c=a[u],d=Array(i).fill(void 0),h=e?e[o][u]:JM,f=[];for(let p=0;p<c.length;p++){let m=c[p],S=s.get(l[p]);m===null?h!=QM&&(d[S]=m,h==e5&&f.push(S)):d[S]=m}t5(d,f,i),n.push(d)}}return n}const n5=typeof queueMicrotask>"u"?r=>Promise.resolve().then(r):queueMicrotask;function i5(r){let e=r[0],t=e.length,n=Array(t);for(let s=0;s<n.length;s++)n[s]=s;n.sort((s,o)=>e[s]-e[o]);let i=[];for(let s=0;s<r.length;s++){let o=r[s],a=Array(t);for(let l=0;l<t;l++)a[l]=o[n[l]];i.push(a)}return i}function s5(r){let e=r[0][0],t=e.length;for(let n=1;n<r.length;n++){let i=r[n][0];if(i.length!=t)return!1;if(i!=e){for(let s=0;s<t;s++)if(i[s]!=e[s])return!1}}return!0}function o5(r,e=100){const t=r.length;if(t<=1)return!0;let n=0,i=t-1;for(;n<=i&&r[n]==null;)n++;for(;i>=n&&r[i]==null;)i--;if(i<=n)return!0;const s=Mr(1,Qr((i-n+1)/e));for(let o=r[n],a=n+s;a<=i;a+=s){const l=r[a];if(l!=null){if(l<=o)return!1;o=l}}return!0}const iC=["January","February","March","April","May","June","July","August","September","October","November","December"],sC=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function oC(r){return r.slice(0,3)}const a5=sC.map(oC),l5=iC.map(oC),u5={MMMM:iC,MMM:l5,WWWW:sC,WWW:a5};function $o(r){return(r<10?"0":"")+r}function c5(r){return(r<10?"00":r<100?"0":"")+r}const d5={YYYY:r=>r.getFullYear(),YY:r=>(r.getFullYear()+"").slice(2),MMMM:(r,e)=>e.MMMM[r.getMonth()],MMM:(r,e)=>e.MMM[r.getMonth()],MM:r=>$o(r.getMonth()+1),M:r=>r.getMonth()+1,DD:r=>$o(r.getDate()),D:r=>r.getDate(),WWWW:(r,e)=>e.WWWW[r.getDay()],WWW:(r,e)=>e.WWW[r.getDay()],HH:r=>$o(r.getHours()),H:r=>r.getHours(),h:r=>{let e=r.getHours();return e==0?12:e>12?e-12:e},AA:r=>r.getHours()>=12?"PM":"AM",aa:r=>r.getHours()>=12?"pm":"am",a:r=>r.getHours()>=12?"p":"a",mm:r=>$o(r.getMinutes()),m:r=>r.getMinutes(),ss:r=>$o(r.getSeconds()),s:r=>r.getSeconds(),fff:r=>c5(r.getMilliseconds())};function Hf(r,e){e=e||u5;let t=[],n=/\{([a-z]+)\}|[^{]+/gi,i;for(;i=n.exec(r);)t.push(i[0][0]=="{"?d5[i[1]]:i[0]);return s=>{let o="";for(let a=0;a<t.length;a++)o+=typeof t[a]=="string"?t[a]:t[a](s,e);return o}}const h5=new Intl.DateTimeFormat().resolvedOptions().timeZone;function f5(r,e){let t;return e=="UTC"||e=="Etc/UTC"?t=new Date(+r+r.getTimezoneOffset()*6e4):e==h5?t=r:(t=new Date(r.toLocaleString("en-US",{timeZone:e})),t.setMilliseconds(r.getMilliseconds())),t}const aC=r=>r%1==0,du=[1,2,2.5,5],p5=Ta(10,-32,0,du),lC=Ta(10,0,32,du),g5=lC.filter(aC),Qi=p5.concat(lC),jf=`
|
|
274
|
+
`,uC="{YYYY}",Dm=jf+uC,cC="{M}/{D}",Ko=jf+cC,fl=Ko+"/{YY}",dC="{aa}",m5="{h}:{mm}",Rs=m5+dC,Fm=jf+Rs,Lm=":{ss}",We=null;function hC(r){let e=r*1e3,t=e*60,n=t*60,i=n*24,s=i*30,o=i*365,l=(r==1?Ta(10,0,3,du).filter(aC):Ta(10,-3,0,du)).concat([e,e*5,e*10,e*15,e*30,t,t*5,t*10,t*15,t*30,n,n*2,n*3,n*4,n*6,n*8,n*12,i,i*2,i*3,i*4,i*5,i*6,i*7,i*8,i*9,i*10,i*15,s,s*2,s*3,s*4,s*6,o,o*2,o*5,o*10,o*25,o*50,o*100]);const u=[[o,uC,We,We,We,We,We,We,1],[i*28,"{MMM}",Dm,We,We,We,We,We,1],[i,cC,Dm,We,We,We,We,We,1],[n,"{h}"+dC,fl,We,Ko,We,We,We,1],[t,Rs,fl,We,Ko,We,We,We,1],[e,Lm,fl+" "+Rs,We,Ko+" "+Rs,We,Fm,We,1],[r,Lm+".{fff}",fl+" "+Rs,We,Ko+" "+Rs,We,Fm,We,1]];function c(d){return(h,f,p,m,S,w)=>{let g=[],y=S>=o,C=S>=s&&S<o,x=d(p),I=Je(x*r,3),E=Zc(x.getFullYear(),y?0:x.getMonth(),C||y?1:x.getDate()),A=Je(E*r,3);if(C||y){let R=C?S/s:0,F=y?S/o:0,z=I==A?I:Je(Zc(E.getFullYear()+F,E.getMonth()+R,1)*r,3),P=new Date($t(z/r)),D=P.getFullYear(),L=P.getMonth();for(let V=0;z<=m;V++){let X=Zc(D+F*V,L+R*V,1),T=X-d(Je(X*r,3));z=Je((+X+T)*r,3),z<=m&&g.push(z)}}else{let R=S>=i?i:S,F=Qr(p)-Qr(I),z=A+F+Fu(I-A,R);g.push(z);let P=d(z),D=P.getHours()+P.getMinutes()/t+P.getSeconds()/n,L=S/n,V=h.axes[f]._space,X=w/V;for(;z=Je(z+S,r==1?0:3),!(z>m);)if(L>1){let T=Qr(Je(D+L,6))%24,G=d(z).getHours()-T;G>1&&(G=-1),z-=G*n,D=(D+L)%24;let ee=g[g.length-1];Je((z-ee)/S,3)*X>=.7&&g.push(z)}else g.push(z)}return g}}return[l,u,c]}const[y5,v5,w5]=hC(1),[C5,b5,S5]=hC(.001);Ta(2,-53,53,[1]);function _m(r,e){return r.map(t=>t.map((n,i)=>i==0||i==8||n==null?n:e(i==1||t[8]==0?n:t[1]+n)))}function $m(r,e){return(t,n,i,s,o)=>{let a=e.find(p=>o>=p[0])||e[e.length-1],l,u,c,d,h,f;return n.map(p=>{let m=r(p),S=m.getFullYear(),w=m.getMonth(),g=m.getDate(),y=m.getHours(),C=m.getMinutes(),x=m.getSeconds(),I=S!=l&&a[2]||w!=u&&a[3]||g!=c&&a[4]||y!=d&&a[5]||C!=h&&a[6]||x!=f&&a[7]||a[1];return l=S,u=w,c=g,d=y,h=C,f=x,I(m)})}}function x5(r,e){let t=Hf(e);return(n,i,s,o,a)=>i.map(l=>t(r(l)))}function Zc(r,e,t){return new Date(r,e,t)}function Nm(r,e){return e(r)}const I5="{YYYY}-{MM}-{DD} {h}:{mm}{aa}";function Vm(r,e){return(t,n,i,s)=>s==null?Ff:e(r(n))}function k5(r,e){let t=r.series[e];return t.width?t.stroke(r,e):t.points.width?t.points.stroke(r,e):null}function E5(r,e){return r.series[e].fill(r,e)}const M5={show:!0,live:!0,isolate:!1,mount:WM,markers:{show:!0,width:2,stroke:k5,fill:E5,dash:"solid"},idx:null,idxs:null,values:[]};function U5(r,e){let t=r.cursor.points,n=on(),i=t.size(r,e);lt(n,Go,i),lt(n,Xo,i);let s=i/-2;lt(n,"marginLeft",s),lt(n,"marginTop",s);let o=t.width(r,e,i);return o&<(n,"borderWidth",o),n}function A5(r,e){let t=r.series[e].points;return t._fill||t._stroke}function T5(r,e){let t=r.series[e].points;return t._stroke||t._fill}function R5(r,e){return r.series[e].points.size}const qc=[0,0];function P5(r,e,t){return qc[0]=e,qc[1]=t,qc}function pl(r,e,t,n=!0){return i=>{i.button==0&&(!n||i.target==e)&&t(i)}}function Qc(r,e,t,n=!0){return i=>{(!n||i.target==e)&&t(i)}}const B5={show:!0,x:!0,y:!0,lock:!1,move:P5,points:{one:!1,show:U5,size:R5,width:0,stroke:T5,fill:A5},bind:{mousedown:pl,mouseup:pl,click:pl,dblclick:pl,mousemove:Qc,mouseleave:Qc,mouseenter:Qc},drag:{setScale:!0,x:!0,y:!1,dist:0,uni:null,click:(r,e)=>{e.stopPropagation(),e.stopImmediatePropagation()},_x:!1,_y:!1},focus:{dist:(r,e,t,n,i)=>n-i,prox:-1,bias:0},hover:{skip:[void 0],prox:null,bias:0},left:-10,top:-10,idx:null,dataIdx:null,idxs:null,event:null},fC={show:!0,stroke:"rgba(0,0,0,0.07)",width:2},Yf=zt({},fC,{filter:Jw}),pC=zt({},Yf,{size:10}),gC=zt({},fC,{show:!1}),Wf='12px system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',mC="bold "+Wf,yC=1.5,Hm={show:!0,scale:"x",stroke:Df,space:50,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:mC,side:2,grid:Yf,ticks:pC,border:gC,font:Wf,lineGap:yC,rotate:0},z5="Value",O5="Time",jm={show:!0,scale:"x",auto:!1,sorted:1,min:Qe,max:-Qe,idxs:[]};function D5(r,e,t,n,i){return e.map(s=>s==null?"":Nf(s))}function F5(r,e,t,n,i,s,o){let a=[],l=zi.get(i)||0;t=o?t:Je(Fu(t,i),l);for(let u=t;u<=n;u=Je(u+i,l))a.push(Object.is(u,-0)?0:u);return a}function Ch(r,e,t,n,i,s,o){const a=[],l=r.scales[r.axes[e].scale].log,u=l==10?ei:Zw,c=Qr(u(t));i=lo(l,c),l==10&&(i=Qi[In(i,Qi)]);let d=t,h=i*l;l==10&&(h=Qi[In(h,Qi)]);do a.push(d),d=d+i,l==10&&!zi.has(d)&&(d=Je(d,zi.get(i))),d>=h&&(i=d,h=i*l,l==10&&(h=Qi[In(h,Qi)]));while(d<=n);return a}function L5(r,e,t,n,i,s,o){let l=r.scales[r.axes[e].scale].asinh,u=n>l?Ch(r,e,Mr(l,t),n,i):[l],c=n>=0&&t<=0?[0]:[];return(t<-l?Ch(r,e,Mr(l,-n),-t,i):[l]).reverse().map(h=>-h).concat(c,u)}const vC=/./,_5=/[12357]/,$5=/[125]/,Ym=/1/,bh=(r,e,t,n)=>r.map((i,s)=>e==4&&i==0||s%n==0&&t.test(i.toExponential()[i<0?1:0])?i:null);function N5(r,e,t,n,i){let s=r.axes[t],o=s.scale,a=r.scales[o],l=r.valToPos,u=s._space,c=l(10,o),d=l(9,o)-c>=u?vC:l(7,o)-c>=u?_5:l(5,o)-c>=u?$5:Ym;if(d==Ym){let h=jt(l(1,o)-c);if(h<u)return bh(e.slice().reverse(),a.distr,d,an(u/h)).reverse()}return bh(e,a.distr,d,1)}function V5(r,e,t,n,i){let s=r.axes[t],o=s.scale,a=s._space,l=r.valToPos,u=jt(l(1,o)-l(2,o));return u<a?bh(e.slice().reverse(),3,vC,an(a/u)).reverse():e}function H5(r,e,t,n){return n==null?Ff:e==null?"":Nf(e)}const Wm={show:!0,scale:"y",stroke:Df,space:30,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:mC,side:3,grid:Yf,ticks:pC,border:gC,font:Wf,lineGap:yC,rotate:0};function j5(r,e){let t=3+(r||1)*2;return Je(t*e,3)}function Y5(r,e){let{scale:t,idxs:n}=r.series[0],i=r._data[0],s=r.valToPos(i[n[0]],t,!0),o=r.valToPos(i[n[1]],t,!0),a=jt(o-s),l=r.series[e],u=a/(l.points.space*je);return n[1]-n[0]<=u}const Gm={scale:null,auto:!0,sorted:0,min:Qe,max:-Qe},wC=(r,e,t,n,i)=>i,Xm={show:!0,auto:!0,sorted:0,gaps:wC,alpha:1,facets:[zt({},Gm,{scale:"x"}),zt({},Gm,{scale:"y"})]},Km={scale:"y",auto:!0,sorted:0,show:!0,spanGaps:!1,gaps:wC,alpha:1,points:{show:Y5,filter:null},values:null,min:Qe,max:-Qe,idxs:[],path:null,clip:null};function W5(r,e,t,n,i){return t/10}const CC={time:yM,auto:!0,distr:1,log:10,asinh:1,min:null,max:null,dir:1,ori:0},G5=zt({},CC,{time:!1,ori:1}),Zm={};function bC(r,e){let t=Zm[r];return t||(t={key:r,plots:[],sub(n){t.plots.push(n)},unsub(n){t.plots=t.plots.filter(i=>i!=n)},pub(n,i,s,o,a,l,u){for(let c=0;c<t.plots.length;c++)t.plots[c]!=i&&t.plots[c].pub(n,i,s,o,a,l,u)}},r!=null&&(Zm[r]=t)),t}const ho=1,Sh=2;function ps(r,e,t){const n=r.mode,i=r.series[e],s=n==2?r._data[e]:r._data,o=r.scales,a=r.bbox;let l=s[0],u=n==2?s[1]:s[e],c=n==2?o[i.facets[0].scale]:o[r.series[0].scale],d=n==2?o[i.facets[1].scale]:o[i.scale],h=a.left,f=a.top,p=a.width,m=a.height,S=r.valToPosH,w=r.valToPosV;return c.ori==0?t(i,l,u,c,d,S,w,h,f,p,m,$u,vo,Vu,xC,kC):t(i,l,u,c,d,w,S,f,h,m,p,Nu,wo,Kf,IC,EC)}function Gf(r,e){let t=0,n=0,i=_e(r.bands,Vf);for(let s=0;s<i.length;s++){let o=i[s];o.series[0]==e?t=o.dir:o.series[1]==e&&(o.dir==1?n|=1:n|=2)}return[t,n==1?-1:n==2?1:n==3?2:0]}function X5(r,e,t,n,i){let s=r.mode,o=r.series[e],a=s==2?o.facets[1].scale:o.scale,l=r.scales[a];return i==-1?l.min:i==1?l.max:l.distr==3?l.dir==1?l.min:l.max:0}function ti(r,e,t,n,i,s){return ps(r,e,(o,a,l,u,c,d,h,f,p,m,S)=>{let w=o.pxRound;const g=u.dir*(u.ori==0?1:-1),y=u.ori==0?vo:wo;let C,x;g==1?(C=t,x=n):(C=n,x=t);let I=w(d(a[C],u,m,f)),E=w(h(l[C],c,S,p)),A=w(d(a[x],u,m,f)),R=w(h(s==1?c.max:c.min,c,S,p)),F=new Path2D(i);return y(F,A,R),y(F,I,R),y(F,I,E),F})}function _u(r,e,t,n,i,s){let o=null;if(r.length>0){o=new Path2D;const a=e==0?Vu:Kf;let l=t;for(let d=0;d<r.length;d++){let h=r[d];if(h[1]>h[0]){let f=h[0]-l;f>0&&a(o,l,n,f,n+s),l=h[1]}}let u=t+i-l,c=10;u>0&&a(o,l,n-c/2,u,n+s+c)}return o}function K5(r,e,t){let n=r[r.length-1];n&&n[0]==e?n[1]=t:r.push([e,t])}function Xf(r,e,t,n,i,s,o){let a=[],l=r.length;for(let u=i==1?t:n;u>=t&&u<=n;u+=i)if(e[u]===null){let d=u,h=u;if(i==1)for(;++u<=n&&e[u]===null;)h=u;else for(;--u>=t&&e[u]===null;)h=u;let f=s(r[d]),p=h==d?f:s(r[h]),m=d-i;f=o<=0&&m>=0&&m<l?s(r[m]):f;let w=h+i;p=o>=0&&w>=0&&w<l?s(r[w]):p,p>=f&&a.push([f,p])}return a}function qm(r){return r==0?Qw:r==1?$t:e=>qi(e,r)}function SC(r){let e=r==0?$u:Nu,t=r==0?(i,s,o,a,l,u)=>{i.arcTo(s,o,a,l,u)}:(i,s,o,a,l,u)=>{i.arcTo(o,s,l,a,u)},n=r==0?(i,s,o,a,l)=>{i.rect(s,o,a,l)}:(i,s,o,a,l)=>{i.rect(o,s,l,a)};return(i,s,o,a,l,u=0,c=0)=>{u==0&&c==0?n(i,s,o,a,l):(u=En(u,a/2,l/2),c=En(c,a/2,l/2),e(i,s+u,o),t(i,s+a,o,s+a,o+l,u),t(i,s+a,o+l,s,o+l,c),t(i,s,o+l,s,o,c),t(i,s,o,s+a,o,u),i.closePath())}}const $u=(r,e,t)=>{r.moveTo(e,t)},Nu=(r,e,t)=>{r.moveTo(t,e)},vo=(r,e,t)=>{r.lineTo(e,t)},wo=(r,e,t)=>{r.lineTo(t,e)},Vu=SC(0),Kf=SC(1),xC=(r,e,t,n,i,s)=>{r.arc(e,t,n,i,s)},IC=(r,e,t,n,i,s)=>{r.arc(t,e,n,i,s)},kC=(r,e,t,n,i,s,o)=>{r.bezierCurveTo(e,t,n,i,s,o)},EC=(r,e,t,n,i,s,o)=>{r.bezierCurveTo(t,e,i,n,o,s)};function MC(r){return(e,t,n,i,s)=>ps(e,t,(o,a,l,u,c,d,h,f,p,m,S)=>{let{pxRound:w,points:g}=o,y,C;u.ori==0?(y=$u,C=xC):(y=Nu,C=IC);const x=Je(g.width*je,3);let I=(g.size-g.width)/2*je,E=Je(I*2,3),A=new Path2D,R=new Path2D,{left:F,top:z,width:P,height:D}=e.bbox;Vu(R,F-E,z-E,P+E*2,D+E*2);const L=V=>{if(l[V]!=null){let X=w(d(a[V],u,m,f)),T=w(h(l[V],c,S,p));y(A,X+I,T),C(A,X,T,I,0,zl*2)}};if(s)s.forEach(L);else for(let V=n;V<=i;V++)L(V);return{stroke:x>0?A:null,fill:A,clip:R,flags:ho|Sh}})}function UC(r){return(e,t,n,i,s,o)=>{n!=i&&(s!=n&&o!=n&&r(e,t,n),s!=i&&o!=i&&r(e,t,i),r(e,t,o))}}const Z5=UC(vo),q5=UC(wo);function AC(r){const e=_e(r==null?void 0:r.alignGaps,0);return(t,n,i,s)=>ps(t,n,(o,a,l,u,c,d,h,f,p,m,S)=>{[i,s]=Ou(l,i,s);let w=o.pxRound,g=D=>w(d(D,u,m,f)),y=D=>w(h(D,c,S,p)),C,x;u.ori==0?(C=vo,x=Z5):(C=wo,x=q5);const I=u.dir*(u.ori==0?1:-1),E={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:ho},A=E.stroke;let R=!1;if(s-i>=m*4){let D=K=>t.posToVal(K,u.key,!0),L=null,V=null,X,T,_,j=g(a[I==1?i:s]),G=g(a[i]),ee=g(a[s]),q=D(I==1?G+1:ee-1);for(let K=I==1?i:s;K>=i&&K<=s;K+=I){let oe=a[K],ge=(I==1?oe<q:oe>q)?j:g(oe),Ce=l[K];ge==j?Ce!=null?(T=Ce,L==null?(C(A,ge,y(T)),X=L=V=T):T<L?L=T:T>V&&(V=T)):Ce===null&&(R=!0):(L!=null&&x(A,j,y(L),y(V),y(X),y(T)),Ce!=null?(T=Ce,C(A,ge,y(T)),L=V=X=T):(L=V=null,Ce===null&&(R=!0)),j=ge,q=D(j+I))}L!=null&&L!=V&&_!=j&&x(A,j,y(L),y(V),y(X),y(T))}else for(let D=I==1?i:s;D>=i&&D<=s;D+=I){let L=l[D];L===null?R=!0:L!=null&&C(A,g(a[D]),y(L))}let[z,P]=Gf(t,n);if(o.fill!=null||z!=0){let D=E.fill=new Path2D(A),L=o.fillTo(t,n,o.min,o.max,z),V=y(L),X=g(a[i]),T=g(a[s]);I==-1&&([T,X]=[X,T]),C(D,T,V),C(D,X,V)}if(!o.spanGaps){let D=[];R&&D.push(...Xf(a,l,i,s,I,g,e)),E.gaps=D=o.gaps(t,n,i,s,D),E.clip=_u(D,u.ori,f,p,m,S)}return P!=0&&(E.band=P==2?[ti(t,n,i,s,A,-1),ti(t,n,i,s,A,1)]:ti(t,n,i,s,A,P)),E})}function Q5(r){const e=_e(r.align,1),t=_e(r.ascDesc,!1),n=_e(r.alignGaps,0),i=_e(r.extend,!1);return(s,o,a,l)=>ps(s,o,(u,c,d,h,f,p,m,S,w,g,y)=>{[a,l]=Ou(d,a,l);let C=u.pxRound,{left:x,width:I}=s.bbox,E=G=>C(p(G,h,g,S)),A=G=>C(m(G,f,y,w)),R=h.ori==0?vo:wo;const F={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:ho},z=F.stroke,P=h.dir*(h.ori==0?1:-1);let D=A(d[P==1?a:l]),L=E(c[P==1?a:l]),V=L,X=L;i&&e==-1&&(X=x,R(z,X,D)),R(z,L,D);for(let G=P==1?a:l;G>=a&&G<=l;G+=P){let ee=d[G];if(ee==null)continue;let q=E(c[G]),K=A(ee);e==1?R(z,q,D):R(z,V,K),R(z,q,K),D=K,V=q}let T=V;i&&e==1&&(T=x+I,R(z,T,D));let[_,j]=Gf(s,o);if(u.fill!=null||_!=0){let G=F.fill=new Path2D(z),ee=u.fillTo(s,o,u.min,u.max,_),q=A(ee);R(G,T,q),R(G,X,q)}if(!u.spanGaps){let G=[];G.push(...Xf(c,d,a,l,P,E,n));let ee=u.width*je/2,q=t||e==1?ee:-ee,K=t||e==-1?-ee:ee;G.forEach(oe=>{oe[0]+=q,oe[1]+=K}),F.gaps=G=u.gaps(s,o,a,l,G),F.clip=_u(G,h.ori,S,w,g,y)}return j!=0&&(F.band=j==2?[ti(s,o,a,l,z,-1),ti(s,o,a,l,z,1)]:ti(s,o,a,l,z,j)),F})}function Qm(r,e,t,n,i,s,o=Qe){if(r.length>1){let a=null;for(let l=0,u=1/0;l<r.length;l++)if(e[l]!==void 0){if(a!=null){let c=jt(r[l]-r[a]);c<u&&(u=c,o=jt(t(r[l],n,i,s)-t(r[a],n,i,s)))}a=l}}return o}function J5(r){r=r||da;const e=_e(r.size,[.6,Qe,1]),t=r.align||0,n=r.gap||0;let i=r.radius;i=i==null?[0,0]:typeof i=="number"?[i,0]:i;const s=Pe(i),o=1-e[0],a=_e(e[1],Qe),l=_e(e[2],1),u=_e(r.disp,da),c=_e(r.each,f=>{}),{fill:d,stroke:h}=u;return(f,p,m,S)=>ps(f,p,(w,g,y,C,x,I,E,A,R,F,z)=>{let P=w.pxRound,D=t,L=n*je,V=a*je,X=l*je,T,_;C.ori==0?[T,_]=s(f,p):[_,T]=s(f,p);const j=C.dir*(C.ori==0?1:-1);let G=C.ori==0?Vu:Kf,ee=C.ori==0?c:(ne,$e,ft,Q,W,le,ye)=>{c(ne,$e,ft,W,Q,ye,le)},q=_e(f.bands,Vf).find(ne=>ne.series[0]==p),K=q!=null?q.dir:0,oe=w.fillTo(f,p,w.min,w.max,K),ve=P(E(oe,x,z,R)),ge,Ce,dt,ht=F,xe=P(w.width*je),et=!1,Ke=null,qe=null,At=null,wt=null;d!=null&&(xe==0||h!=null)&&(et=!0,Ke=d.values(f,p,m,S),qe=new Map,new Set(Ke).forEach(ne=>{ne!=null&&qe.set(ne,new Path2D)}),xe>0&&(At=h.values(f,p,m,S),wt=new Map,new Set(At).forEach(ne=>{ne!=null&&wt.set(ne,new Path2D)})));let{x0:Ft,size:cr}=u;if(Ft!=null&&cr!=null){D=1,g=Ft.values(f,p,m,S),Ft.unit==2&&(g=g.map(ft=>f.posToVal(A+ft*F,C.key,!0)));let ne=cr.values(f,p,m,S);cr.unit==2?Ce=ne[0]*F:Ce=I(ne[0],C,F,A)-I(0,C,F,A),ht=Qm(g,y,I,C,F,A,ht),dt=ht-Ce+L}else ht=Qm(g,y,I,C,F,A,ht),dt=ht*o+L,Ce=ht-dt;dt<1&&(dt=0),xe>=Ce/2&&(xe=0),dt<5&&(P=Qw);let tt=dt>0,kt=ht-dt-(tt?xe:0);Ce=P(wh(kt,X,V)),ge=(D==0?Ce/2:D==j?0:Ce)-D*j*((D==0?L/2:0)+(tt?xe/2:0));const nt={stroke:null,fill:null,clip:null,band:null,gaps:null,flags:0},Cr=et?null:new Path2D;let Se=null;if(q!=null)Se=f.data[q.series[1]];else{let{y0:ne,y1:$e}=u;ne!=null&&$e!=null&&(y=$e.values(f,p,m,S),Se=ne.values(f,p,m,S))}let Re=T*Ce,pe=_*Ce;for(let ne=j==1?m:S;ne>=m&&ne<=S;ne+=j){let $e=y[ne];if($e==null)continue;if(Se!=null){let Ee=Se[ne]??0;if($e-Ee==0)continue;ve=E(Ee,x,z,R)}let ft=C.distr!=2||u!=null?g[ne]:ne,Q=I(ft,C,F,A),W=E(_e($e,oe),x,z,R),le=P(Q-ge),ye=P(Mr(W,ve)),de=P(En(W,ve)),Ue=ye-de;if($e!=null){let Ee=$e<0?pe:Re,Me=$e<0?Re:pe;et?(xe>0&&At[ne]!=null&&G(wt.get(At[ne]),le,de+Qr(xe/2),Ce,Mr(0,Ue-xe),Ee,Me),Ke[ne]!=null&&G(qe.get(Ke[ne]),le,de+Qr(xe/2),Ce,Mr(0,Ue-xe),Ee,Me)):G(Cr,le,de+Qr(xe/2),Ce,Mr(0,Ue-xe),Ee,Me),ee(f,p,ne,le-xe/2,de,Ce+xe,Ue)}}return xe>0?nt.stroke=et?wt:Cr:et||(nt._fill=w.width==0?w._fill:w._stroke??w._fill,nt.width=0),nt.fill=et?qe:Cr,nt})}function eU(r,e){const t=_e(e==null?void 0:e.alignGaps,0);return(n,i,s,o)=>ps(n,i,(a,l,u,c,d,h,f,p,m,S,w)=>{[s,o]=Ou(u,s,o);let g=a.pxRound,y=T=>g(h(T,c,S,p)),C=T=>g(f(T,d,w,m)),x,I,E;c.ori==0?(x=$u,E=vo,I=kC):(x=Nu,E=wo,I=EC);const A=c.dir*(c.ori==0?1:-1);let R=y(l[A==1?s:o]),F=R,z=[],P=[];for(let T=A==1?s:o;T>=s&&T<=o;T+=A)if(u[T]!=null){let j=l[T],G=y(j);z.push(F=G),P.push(C(u[T]))}const D={stroke:r(z,P,x,E,I,g),fill:null,clip:null,band:null,gaps:null,flags:ho},L=D.stroke;let[V,X]=Gf(n,i);if(a.fill!=null||V!=0){let T=D.fill=new Path2D(L),_=a.fillTo(n,i,a.min,a.max,V),j=C(_);E(T,F,j),E(T,R,j)}if(!a.spanGaps){let T=[];T.push(...Xf(l,u,s,o,A,y,t)),D.gaps=T=a.gaps(n,i,s,o,T),D.clip=_u(T,c.ori,p,m,S,w)}return X!=0&&(D.band=X==2?[ti(n,i,s,o,L,-1),ti(n,i,s,o,L,1)]:ti(n,i,s,o,L,X)),D})}function tU(r){return eU(rU,r)}function rU(r,e,t,n,i,s){const o=r.length;if(o<2)return null;const a=new Path2D;if(t(a,r[0],e[0]),o==2)n(a,r[1],e[1]);else{let l=Array(o),u=Array(o-1),c=Array(o-1),d=Array(o-1);for(let h=0;h<o-1;h++)c[h]=e[h+1]-e[h],d[h]=r[h+1]-r[h],u[h]=c[h]/d[h];l[0]=u[0];for(let h=1;h<o-1;h++)u[h]===0||u[h-1]===0||u[h-1]>0!=u[h]>0?l[h]=0:(l[h]=3*(d[h-1]+d[h])/((2*d[h]+d[h-1])/u[h-1]+(d[h]+2*d[h-1])/u[h]),isFinite(l[h])||(l[h]=0));l[o-1]=u[o-2];for(let h=0;h<o-1;h++)i(a,r[h]+d[h]/3,e[h]+l[h]*d[h]/3,r[h+1]-d[h]/3,e[h+1]-l[h+1]*d[h]/3,r[h+1],e[h+1])}return a}const xh=new Set;function Jm(){for(let r of xh)r.syncRect(!0)}yo&&(ss(DM,Js,Jm),ss(FM,Js,Jm,!0),ss(uu,Js,()=>{yr.pxRatio=je}));const nU=AC(),iU=MC();function ey(r,e,t,n){return(n?[r[0],r[1]].concat(r.slice(2)):[r[0]].concat(r.slice(1))).map((s,o)=>Ih(s,o,e,t))}function sU(r,e){return r.map((t,n)=>n==0?{}:zt({},e,t))}function Ih(r,e,t,n){return zt({},e==0?t:n,r)}function TC(r,e,t){return e==null?uo:[e,t]}const oU=TC;function aU(r,e,t){return e==null?uo:cu(e,t,$f,!0)}function RC(r,e,t,n){return e==null?uo:Du(e,t,r.scales[n].log,!1)}const lU=RC;function PC(r,e,t,n){return e==null?uo:_f(e,t,r.scales[n].log,!1)}const uU=PC;function cU(r,e,t,n,i){let s=Mr(Pm(r),Pm(e)),o=e-r,a=In(i/n*o,t);do{let l=t[a],u=n*l/o;if(u>=i&&s+(l<5?zi.get(l):0)<=17)return[l,u]}while(++a<t.length);return[0,0]}function ty(r){let e,t;return r=r.replace(/(\d+)px/,(n,i)=>(e=$t((t=+i)*je))+"px"),[r,e,t]}function dU(r){r.show&&[r.font,r.labelFont].forEach(e=>{let t=Je(e[2]*je,1);e[0]=e[0].replace(/[0-9.]+px/,t+"px"),e[1]=t})}function yr(r,e,t){const n={mode:_e(r.mode,1)},i=n.mode;function s(v,b,M,U){let B=b.valToPct(v);return U+M*(b.dir==-1?1-B:B)}function o(v,b,M,U){let B=b.valToPct(v);return U+M*(b.dir==-1?B:1-B)}function a(v,b,M,U){return b.ori==0?s(v,b,M,U):o(v,b,M,U)}n.valToPosH=s,n.valToPosV=o;let l=!1;n.status=0;const u=n.root=on(vM);if(r.id!=null&&(u.id=r.id),Wr(u,r.class),r.title){let v=on(bM,u);v.textContent=r.title}const c=Cn("canvas"),d=n.ctx=c.getContext("2d"),h=on(SM,u);ss("click",h,v=>{v.target===p&&(it!=bs||gt!=Ss)&&sr.click(n,v)},!0);const f=n.under=on(xM,h);h.appendChild(c);const p=n.over=on(IM,h);r=co(r);const m=+_e(r.pxAlign,1),S=qm(m);(r.plugins||[]).forEach(v=>{v.opts&&(r=v.opts(n,r)||r)});const w=r.ms||.001,g=n.series=i==1?ey(r.series||[],jm,Km,!1):sU(r.series||[null],Xm),y=n.axes=ey(r.axes||[],Hm,Wm,!0),C=n.scales={},x=n.bands=r.bands||[];x.forEach(v=>{v.fill=Pe(v.fill||null),v.dir=_e(v.dir,-1)});const I=i==2?g[1].facets[0].scale:g[0].scale,E={axes:YC,series:$C},A=(r.drawOrder||["axes","series"]).map(v=>E[v]);function R(v){const b=v.distr==3?M=>ei(M>0?M:v.clamp(n,M,v.min,v.max,v.key)):v.distr==4?M=>Kc(M,v.asinh):v.distr==100?M=>v.fwd(M):M=>M;return M=>{let U=b(M),{_min:B,_max:$}=v,Y=$-B;return(U-B)/Y}}function F(v){let b=C[v];if(b==null){let M=(r.scales||da)[v]||da;if(M.from!=null){F(M.from);let U=zt({},C[M.from],M,{key:v});U.valToPct=R(U),C[v]=U}else{b=C[v]=zt({},v==I?CC:G5,M),b.key=v;let U=b.time,B=b.range,$=mi(B);if((v!=I||i==2&&!U)&&($&&(B[0]==null||B[1]==null)&&(B={min:B[0]==null?Am:{mode:1,hard:B[0],soft:B[0]},max:B[1]==null?Am:{mode:1,hard:B[1],soft:B[1]}},$=!1),!$&&Lu(B))){let Y=B;B=(Z,re,ae)=>re==null?uo:cu(re,ae,Y)}b.range=Pe(B||(U?oU:v==I?b.distr==3?lU:b.distr==4?uU:TC:b.distr==3?RC:b.distr==4?PC:aU)),b.auto=Pe($?!1:b.auto),b.clamp=Pe(b.clamp||W5),b._min=b._max=null,b.valToPct=R(b)}}}F("x"),F("y"),i==1&&g.forEach(v=>{F(v.scale)}),y.forEach(v=>{F(v.scale)});for(let v in r.scales)F(v);const z=C[I],P=z.distr;let D,L;z.ori==0?(Wr(u,wM),D=s,L=o):(Wr(u,CM),D=o,L=s);const V={};for(let v in C){let b=C[v];(b.min!=null||b.max!=null)&&(V[v]={min:b.min,max:b.max},b.min=b.max=null)}const X=r.tzDate||(v=>new Date($t(v/w))),T=r.fmtDate||Hf,_=w==1?w5(X):S5(X),j=$m(X,_m(w==1?v5:b5,T)),G=Vm(X,Nm(I5,T)),ee=[],q=n.legend=zt({},M5,r.legend),K=n.cursor=zt({},B5,{drag:{y:i==2}},r.cursor),oe=q.show,ve=K.show,ge=q.markers;q.idxs=ee,ge.width=Pe(ge.width),ge.dash=Pe(ge.dash),ge.stroke=Pe(ge.stroke),ge.fill=Pe(ge.fill);let Ce,dt,ht,xe=[],et=[],Ke,qe=!1,At={};if(q.live){const v=g[1]?g[1].values:null;qe=v!=null,Ke=qe?v(n,1,0):{_:0};for(let b in Ke)At[b]=Ff}if(oe)if(Ce=Cn("table",TM,u),ht=Cn("tbody",null,Ce),q.mount(n,Ce),qe){dt=Cn("thead",null,Ce,ht);let v=Cn("tr",null,dt);Cn("th",null,v);for(var wt in Ke)Cn("th",mm,v).textContent=wt}else Wr(Ce,PM),q.live&&Wr(Ce,RM);const Ft={show:!0},cr={show:!1};function tt(v,b){if(b==0&&(qe||!q.live||i==2))return uo;let M=[],U=Cn("tr",BM,ht,ht.childNodes[b]);Wr(U,v.class),v.show||Wr(U,Ji);let B=Cn("th",null,U);if(ge.show){let Z=on(zM,B);if(b>0){let re=ge.width(n,b);re&&(Z.style.border=re+"px "+ge.dash(n,b)+" "+ge.stroke(n,b)),Z.style.background=ge.fill(n,b)}}let $=on(mm,B);v.label instanceof HTMLElement?$.appendChild(v.label):$.textContent=v.label,b>0&&(ge.show||($.style.color=v.width>0?ge.stroke(n,b):ge.fill(n,b)),nt("click",B,Z=>{if(K._lock)return;Br(Z);let re=g.indexOf(v);if((Z.ctrlKey||Z.metaKey)!=q.isolate){let ae=g.some((ue,he)=>he>0&&he!=re&&ue.show);g.forEach((ue,he)=>{he>0&&zn(he,ae?he==re?Ft:cr:Ft,!0,Bt.setSeries)})}else zn(re,{show:!v.show},!0,Bt.setSeries)},!1),Tn&&nt(Cm,B,Z=>{K._lock||(Br(Z),zn(g.indexOf(v),Is,!0,Bt.setSeries))},!1));for(var Y in Ke){let Z=Cn("td",OM,U);Z.textContent="--",M.push(Z)}return[U,M]}const kt=new Map;function nt(v,b,M,U=!0){const B=kt.get(b)||{},$=K.bind[v](n,b,M,U);$&&(ss(v,b,B[v]=$),kt.set(b,B))}function Cr(v,b,M){const U=kt.get(b)||{};for(let B in U)(v==null||B==v)&&(vh(B,b,U[B]),delete U[B]);v==null&&kt.delete(b)}let Se=0,Re=0,pe=0,ne=0,$e=0,ft=0,Q=$e,W=ft,le=pe,ye=ne,de=0,Ue=0,Ee=0,Me=0;n.bbox={};let Ne=!1,we=!1,De=!1,Tt=!1,pt=!1,Ve=!1;function Xt(v,b,M){(M||v!=n.width||b!=n.height)&&Lt(v,b),ys(!1),De=!0,we=!0,vs()}function Lt(v,b){n.width=Se=pe=v,n.height=Re=ne=b,$e=ft=0,Fe(),$i();let M=n.bbox;de=M.left=qi($e*je,.5),Ue=M.top=qi(ft*je,.5),Ee=M.width=qi(pe*je,.5),Me=M.height=qi(ne*je,.5)}const ai=3;function Li(){let v=!1,b=0;for(;!v;){b++;let M=HC(b),U=jC(b);v=b==ai||M&&U,v||(Lt(n.width,n.height),we=!0)}}function _i({width:v,height:b}){Xt(v,b)}n.setSize=_i;function Fe(){let v=!1,b=!1,M=!1,U=!1;y.forEach((B,$)=>{if(B.show&&B._show){let{side:Y,_size:Z}=B,re=Y%2,ae=B.label!=null?B.labelSize:0,ue=Z+ae;ue>0&&(re?(pe-=ue,Y==3?($e+=ue,U=!0):M=!0):(ne-=ue,Y==0?(ft+=ue,v=!0):b=!0))}}),Vi[0]=v,Vi[1]=M,Vi[2]=b,Vi[3]=U,pe-=li[1]+li[3],$e+=li[3],ne-=li[2]+li[0],ft+=li[0]}function $i(){let v=$e+pe,b=ft+ne,M=$e,U=ft;function B($,Y){switch($){case 1:return v+=Y,v-Y;case 2:return b+=Y,b-Y;case 3:return M-=Y,M+Y;case 0:return U-=Y,U+Y}}y.forEach(($,Y)=>{if($.show&&$._show){let Z=$.side;$._pos=B(Z,$._size),$.label!=null&&($._lpos=B(Z,$.labelSize))}})}if(K.dataIdx==null){let v=K.hover,b=v.skip=new Set(v.skip??[]);b.add(void 0);let M=v.prox=Pe(v.prox),U=v.bias??(v.bias=0);K.dataIdx=(B,$,Y,Z)=>{if($==0)return Y;let re=Y,ae=M(B,$,Y,Z)??Qe,ue=ae>=0&&ae<Qe,he=z.ori==0?pe:ne,Ie=K.left,He=e[0],Le=e[$];if(b.has(Le[Y])){re=null;let Ae=null,be=null,me;if(U==0||U==-1)for(me=Y;Ae==null&&me-- >0;)b.has(Le[me])||(Ae=me);if(U==0||U==1)for(me=Y;be==null&&me++<Le.length;)b.has(Le[me])||(be=me);if(Ae!=null||be!=null)if(ue){let ot=Ae==null?-1/0:D(He[Ae],z,he,0),Et=be==null?1/0:D(He[be],z,he,0),er=Ie-ot,Ze=Et-Ie;er<=Ze?er<=ae&&(re=Ae):Ze<=ae&&(re=be)}else re=be==null?Ae:Ae==null?be:Y-Ae<=be-Y?Ae:be}else ue&&jt(Ie-D(He[Y],z,he,0))>ae&&(re=null);return re}}const Br=v=>{K.event=v};K.idxs=ee,K._lock=!1;let Ct=K.points;Ct.show=Pe(Ct.show),Ct.size=Pe(Ct.size),Ct.stroke=Pe(Ct.stroke),Ct.width=Pe(Ct.width),Ct.fill=Pe(Ct.fill);const dr=n.focus=zt({},r.focus||{alpha:.3},K.focus),Tn=dr.prox>=0,Rn=Tn&&Ct.one;let hr=[],Pn=[],Bn=[];function gs(v,b){let M=Ct.show(n,b);if(M instanceof HTMLElement)return Wr(M,AM),Wr(M,v.class),_n(M,-10,-10,pe,ne),p.insertBefore(M,hr[b]),M}function Pt(v,b){if(i==1||b>0){let M=i==1&&C[v.scale].time,U=v.value;v.value=M?Om(U)?Vm(X,Nm(U,T)):U||G:U||H5,v.label=v.label||(M?O5:z5)}if(Rn||b>0){v.width=v.width==null?1:v.width,v.paths=v.paths||nU||GM,v.fillTo=Pe(v.fillTo||X5),v.pxAlign=+_e(v.pxAlign,m),v.pxRound=qm(v.pxAlign),v.stroke=Pe(v.stroke||null),v.fill=Pe(v.fill||null),v._stroke=v._fill=v._paths=v._focus=null;let M=j5(Mr(1,v.width),1),U=v.points=zt({},{size:M,width:Mr(1,M*.2),stroke:v.stroke,space:M*2,paths:iU,_stroke:null,_fill:null},v.points);U.show=Pe(U.show),U.filter=Pe(U.filter),U.fill=Pe(U.fill),U.stroke=Pe(U.stroke),U.paths=Pe(U.paths),U.pxAlign=v.pxAlign}if(oe){let M=tt(v,b);xe.splice(b,0,M[0]),et.splice(b,0,M[1]),q.values.push(null)}if(ve){ee.splice(b,0,null);let M=null;Rn?b==0&&(M=gs(v,b)):b>0&&(M=gs(v,b)),hr.splice(b,0,M),Pn.splice(b,0,0),Bn.splice(b,0,0)}Jt("addSeries",b)}function bt(v,b){b=b??g.length,v=i==1?Ih(v,b,jm,Km):Ih(v,b,{},Xm),g.splice(b,0,v),Pt(g[b],b)}n.addSeries=bt;function Ni(v){if(g.splice(v,1),oe){q.values.splice(v,1),et.splice(v,1);let b=xe.splice(v,1)[0];Cr(null,b.firstChild),b.remove()}ve&&(ee.splice(v,1),hr.splice(v,1)[0].remove(),Pn.splice(v,1),Bn.splice(v,1)),Jt("delSeries",v)}n.delSeries=Ni;const Vi=[!1,!1,!1,!1];function FC(v,b){if(v._show=v.show,v.show){let M=v.side%2,U=C[v.scale];U==null&&(v.scale=M?g[1].scale:I,U=C[v.scale]);let B=U.time;v.size=Pe(v.size),v.space=Pe(v.space),v.rotate=Pe(v.rotate),mi(v.incrs)&&v.incrs.forEach(Y=>{!zi.has(Y)&&zi.set(Y,tC(Y))}),v.incrs=Pe(v.incrs||(U.distr==2?g5:B?w==1?y5:C5:Qi)),v.splits=Pe(v.splits||(B&&U.distr==1?_:U.distr==3?Ch:U.distr==4?L5:F5)),v.stroke=Pe(v.stroke),v.grid.stroke=Pe(v.grid.stroke),v.ticks.stroke=Pe(v.ticks.stroke),v.border.stroke=Pe(v.border.stroke);let $=v.values;v.values=mi($)&&!mi($[0])?Pe($):B?mi($)?$m(X,_m($,T)):Om($)?x5(X,$):$||j:$||D5,v.filter=Pe(v.filter||(U.distr>=3&&U.log==10?N5:U.distr==3&&U.log==2?V5:Jw)),v.font=ty(v.font),v.labelFont=ty(v.labelFont),v._size=v.size(n,null,b,0),v._space=v._rotate=v._incrs=v._found=v._splits=v._values=null,v._size>0&&(Vi[b]=!0,v._el=on(kM,h))}}function bo(v,b,M,U){let[B,$,Y,Z]=M,re=b%2,ae=0;return re==0&&(Z||$)&&(ae=b==0&&!B||b==2&&!Y?$t(Hm.size/3):0),re==1&&(B||Y)&&(ae=b==1&&!$||b==3&&!Z?$t(Wm.size/2):0),ae}const Qf=n.padding=(r.padding||[bo,bo,bo,bo]).map(v=>Pe(_e(v,bo))),li=n._padding=Qf.map((v,b)=>v(n,b,Vi,0));let ir,Kt=null,Zt=null;const La=i==1?g[0].idxs:null;let gn=null,So=!1;function Jf(v,b){if(e=v??[],n.data=n._data=e,i==2){ir=0;for(let M=1;M<g.length;M++)ir+=e[M][0].length}else{e.length==0&&(n.data=n._data=e=[[]]),gn=e[0],ir=gn.length;let M=e;if(P==2){M=e.slice();let U=M[0]=Array(ir);for(let B=0;B<ir;B++)U[B]=B}n._data=e=M}if(ys(!0),Jt("setData"),P==2&&(De=!0),b!==!1){let M=z;M.auto(n,So)?Hu():ci(I,M.min,M.max),Tt=Tt||K.left>=0,Ve=!0,vs()}}n.setData=Jf;function Hu(){So=!0;let v,b;i==1&&(ir>0?(Kt=La[0]=0,Zt=La[1]=ir-1,v=e[0][Kt],b=e[0][Zt],P==2?(v=Kt,b=Zt):v==b&&(P==3?[v,b]=Du(v,v,z.log,!1):P==4?[v,b]=_f(v,v,z.log,!1):z.time?b=v+$t(86400/w):[v,b]=cu(v,b,$f,!0))):(Kt=La[0]=v=null,Zt=La[1]=b=null)),ci(I,v,b)}let _a,ms,ju,Yu,Wu,Gu,Xu,Ku,Zu,zr;function ep(v,b,M,U,B,$){v??(v=vm),M??(M=Vf),U??(U="butt"),B??(B=vm),$??($="round"),v!=_a&&(d.strokeStyle=_a=v),B!=ms&&(d.fillStyle=ms=B),b!=ju&&(d.lineWidth=ju=b),$!=Wu&&(d.lineJoin=Wu=$),U!=Gu&&(d.lineCap=Gu=U),M!=Yu&&d.setLineDash(Yu=M)}function tp(v,b,M,U){b!=ms&&(d.fillStyle=ms=b),v!=Xu&&(d.font=Xu=v),M!=Ku&&(d.textAlign=Ku=M),U!=Zu&&(d.textBaseline=Zu=U)}function qu(v,b,M,U,B=0){if(U.length>0&&v.auto(n,So)&&(b==null||b.min==null)){let $=_e(Kt,0),Y=_e(Zt,U.length-1),Z=M.min==null?NM(U,$,Y,B,v.distr==3):[M.min,M.max];v.min=En(v.min,M.min=Z[0]),v.max=Mr(v.max,M.max=Z[1])}}const rp={min:null,max:null};function LC(){for(let U in C){let B=C[U];V[U]==null&&(B.min==null||V[I]!=null&&B.auto(n,So))&&(V[U]=rp)}for(let U in C){let B=C[U];V[U]==null&&B.from!=null&&V[B.from]!=null&&(V[U]=rp)}V[I]!=null&&ys(!0);let v={};for(let U in V){let B=V[U];if(B!=null){let $=v[U]=co(C[U],ZM);if(B.min!=null)zt($,B);else if(U!=I||i==2)if(ir==0&&$.from==null){let Y=$.range(n,null,null,U);$.min=Y[0],$.max=Y[1]}else $.min=Qe,$.max=-Qe}}if(ir>0){g.forEach((U,B)=>{if(i==1){let $=U.scale,Y=V[$];if(Y==null)return;let Z=v[$];if(B==0){let re=Z.range(n,Z.min,Z.max,$);Z.min=re[0],Z.max=re[1],Kt=In(Z.min,e[0]),Zt=In(Z.max,e[0]),Zt-Kt>1&&(e[0][Kt]<Z.min&&Kt++,e[0][Zt]>Z.max&&Zt--),U.min=gn[Kt],U.max=gn[Zt]}else U.show&&U.auto&&qu(Z,Y,U,e[B],U.sorted);U.idxs[0]=Kt,U.idxs[1]=Zt}else if(B>0&&U.show&&U.auto){let[$,Y]=U.facets,Z=$.scale,re=Y.scale,[ae,ue]=e[B],he=v[Z],Ie=v[re];he!=null&&qu(he,V[Z],$,ae,$.sorted),Ie!=null&&qu(Ie,V[re],Y,ue,Y.sorted),U.min=Y.min,U.max=Y.max}});for(let U in v){let B=v[U],$=V[U];if(B.from==null&&($==null||$.min==null)){let Y=B.range(n,B.min==Qe?null:B.min,B.max==-Qe?null:B.max,U);B.min=Y[0],B.max=Y[1]}}}for(let U in v){let B=v[U];if(B.from!=null){let $=v[B.from];if($.min==null)B.min=B.max=null;else{let Y=B.range(n,$.min,$.max,U);B.min=Y[0],B.max=Y[1]}}}let b={},M=!1;for(let U in v){let B=v[U],$=C[U];if($.min!=B.min||$.max!=B.max){$.min=B.min,$.max=B.max;let Y=$.distr;$._min=Y==3?ei($.min):Y==4?Kc($.min,$.asinh):Y==100?$.fwd($.min):$.min,$._max=Y==3?ei($.max):Y==4?Kc($.max,$.asinh):Y==100?$.fwd($.max):$.max,b[U]=M=!0}}if(M){g.forEach((U,B)=>{i==2?B>0&&b.y&&(U._paths=null):b[U.scale]&&(U._paths=null)});for(let U in b)De=!0,Jt("setScale",U);ve&&K.left>=0&&(Tt=Ve=!0)}for(let U in V)V[U]=null}function _C(v){let b=wh(Kt-1,0,ir-1),M=wh(Zt+1,0,ir-1);for(;v[b]==null&&b>0;)b--;for(;v[M]==null&&M<ir-1;)M++;return[b,M]}function $C(){if(ir>0){let v=g.some(b=>b._focus)&&zr!=dr.alpha;v&&(d.globalAlpha=zr=dr.alpha),g.forEach((b,M)=>{if(M>0&&b.show&&(np(M,!1),np(M,!0),b._paths==null)){let U=zr;zr!=b.alpha&&(d.globalAlpha=zr=b.alpha);let B=i==2?[0,e[M][0].length-1]:_C(e[M]);b._paths=b.paths(n,M,B[0],B[1]),zr!=U&&(d.globalAlpha=zr=U)}}),g.forEach((b,M)=>{if(M>0&&b.show){let U=zr;zr!=b.alpha&&(d.globalAlpha=zr=b.alpha),b._paths!=null&&ip(M,!1);{let B=b._paths!=null?b._paths.gaps:null,$=b.points.show(n,M,Kt,Zt,B),Y=b.points.filter(n,M,$,B);($||Y)&&(b.points._paths=b.points.paths(n,M,Kt,Zt,Y),ip(M,!0))}zr!=U&&(d.globalAlpha=zr=U),Jt("drawSeries",M)}}),v&&(d.globalAlpha=zr=1)}}function np(v,b){let M=b?g[v].points:g[v];M._stroke=M.stroke(n,v),M._fill=M.fill(n,v)}function ip(v,b){let M=b?g[v].points:g[v],{stroke:U,fill:B,clip:$,flags:Y,_stroke:Z=M._stroke,_fill:re=M._fill,_width:ae=M.width}=M._paths;ae=Je(ae*je,3);let ue=null,he=ae%2/2;b&&re==null&&(re=ae>0?"#fff":Z);let Ie=M.pxAlign==1&&he>0;if(Ie&&d.translate(he,he),!b){let He=de-ae/2,Le=Ue-ae/2,Ae=Ee+ae,be=Me+ae;ue=new Path2D,ue.rect(He,Le,Ae,be)}b?Qu(Z,ae,M.dash,M.cap,re,U,B,Y,$):NC(v,Z,ae,M.dash,M.cap,re,U,B,Y,ue,$),Ie&&d.translate(-he,-he)}function NC(v,b,M,U,B,$,Y,Z,re,ae,ue){let he=!1;re!=0&&x.forEach((Ie,He)=>{if(Ie.series[0]==v){let Le=g[Ie.series[1]],Ae=e[Ie.series[1]],be=(Le._paths||da).band;mi(be)&&(be=Ie.dir==1?be[0]:be[1]);let me,ot=null;Le.show&&be&&HM(Ae,Kt,Zt)?(ot=Ie.fill(n,He)||$,me=Le._paths.clip):be=null,Qu(b,M,U,B,ot,Y,Z,re,ae,ue,me,be),he=!0}}),he||Qu(b,M,U,B,$,Y,Z,re,ae,ue)}const sp=ho|Sh;function Qu(v,b,M,U,B,$,Y,Z,re,ae,ue,he){ep(v,b,M,U,B),(re||ae||he)&&(d.save(),re&&d.clip(re),ae&&d.clip(ae)),he?(Z&sp)==sp?(d.clip(he),ue&&d.clip(ue),Na(B,Y),$a(v,$,b)):Z&Sh?(Na(B,Y),d.clip(he),$a(v,$,b)):Z&ho&&(d.save(),d.clip(he),ue&&d.clip(ue),Na(B,Y),d.restore(),$a(v,$,b)):(Na(B,Y),$a(v,$,b)),(re||ae||he)&&d.restore()}function $a(v,b,M){M>0&&(b instanceof Map?b.forEach((U,B)=>{d.strokeStyle=_a=B,d.stroke(U)}):b!=null&&v&&d.stroke(b))}function Na(v,b){b instanceof Map?b.forEach((M,U)=>{d.fillStyle=ms=U,d.fill(M)}):b!=null&&v&&d.fill(b)}function VC(v,b,M,U){let B=y[v],$;if(U<=0)$=[0,0];else{let Y=B._space=B.space(n,v,b,M,U),Z=B._incrs=B.incrs(n,v,b,M,U,Y);$=cU(b,M,Z,U,Y)}return B._found=$}function Ju(v,b,M,U,B,$,Y,Z,re,ae){let ue=Y%2/2;m==1&&d.translate(ue,ue),ep(Z,Y,re,ae,Z),d.beginPath();let he,Ie,He,Le,Ae=B+(U==0||U==3?-$:$);M==0?(Ie=B,Le=Ae):(he=B,He=Ae);for(let be=0;be<v.length;be++)b[be]!=null&&(M==0?he=He=v[be]:Ie=Le=v[be],d.moveTo(he,Ie),d.lineTo(He,Le));d.stroke(),m==1&&d.translate(-ue,-ue)}function HC(v){let b=!0;return y.forEach((M,U)=>{if(!M.show)return;let B=C[M.scale];if(B.min==null){M._show&&(b=!1,M._show=!1,ys(!1));return}else M._show||(b=!1,M._show=!0,ys(!1));let $=M.side,Y=$%2,{min:Z,max:re}=B,[ae,ue]=VC(U,Z,re,Y==0?pe:ne);if(ue==0)return;let he=B.distr==2,Ie=M._splits=M.splits(n,U,Z,re,ae,ue,he),He=B.distr==2?Ie.map(me=>gn[me]):Ie,Le=B.distr==2?gn[Ie[1]]-gn[Ie[0]]:ae,Ae=M._values=M.values(n,M.filter(n,He,U,ue,Le),U,ue,Le);M._rotate=$==2?M.rotate(n,Ae,U,ue):0;let be=M._size;M._size=an(M.size(n,Ae,U,v)),be!=null&&M._size!=be&&(b=!1)}),b}function jC(v){let b=!0;return Qf.forEach((M,U)=>{let B=M(n,U,Vi,v);B!=li[U]&&(b=!1),li[U]=B}),b}function YC(){for(let v=0;v<y.length;v++){let b=y[v];if(!b.show||!b._show)continue;let M=b.side,U=M%2,B,$,Y=b.stroke(n,v),Z=M==0||M==3?-1:1,[re,ae]=b._found;if(b.label!=null){let Sr=b.labelGap*Z,jr=$t((b._lpos+Sr)*je);tp(b.labelFont[0],Y,"center",M==2?_o:ym),d.save(),U==1?(B=$=0,d.translate(jr,$t(Ue+Me/2)),d.rotate((M==3?-zl:zl)/2)):(B=$t(de+Ee/2),$=jr);let Yi=qw(b.label)?b.label(n,v,re,ae):b.label;d.fillText(Yi,B,$),d.restore()}if(ae==0)continue;let ue=C[b.scale],he=U==0?Ee:Me,Ie=U==0?de:Ue,He=b._splits,Le=ue.distr==2?He.map(Sr=>gn[Sr]):He,Ae=ue.distr==2?gn[He[1]]-gn[He[0]]:re,be=b.ticks,me=b.border,ot=be.show?be.size:0,Et=$t(ot*je),er=$t((b.alignTo==2?b._size-ot-b.gap:b.gap)*je),Ze=b._rotate*-zl/180,Mt=S(b._pos*je),Vr=(Et+er)*Z,br=Mt+Vr;$=U==0?br:0,B=U==1?br:0;let nn=b.font[0],mn=b.align==1?Us:b.align==2?Wc:Ze>0?Us:Ze<0?Wc:U==0?"center":M==3?Wc:Us,Dn=Ze||U==1?"middle":M==2?_o:ym;tp(nn,Y,mn,Dn);let Hr=b.font[1]*b.lineGap,sn=He.map(Sr=>S(a(Sr,ue,he,Ie))),yn=b._values;for(let Sr=0;Sr<yn.length;Sr++){let jr=yn[Sr];if(jr!=null){U==0?B=sn[Sr]:$=sn[Sr],jr=""+jr;let Yi=jr.indexOf(`
|
|
275
|
+
`)==-1?[jr]:jr.split(/\n/gm);for(let xr=0;xr<Yi.length;xr++){let Ip=Yi[xr];Ze?(d.save(),d.translate(B,$+xr*Hr),d.rotate(Ze),d.fillText(Ip,0,0),d.restore()):d.fillText(Ip,B,$+xr*Hr)}}}be.show&&Ju(sn,be.filter(n,Le,v,ae,Ae),U,M,Mt,Et,Je(be.width*je,3),be.stroke(n,v),be.dash,be.cap);let Fn=b.grid;Fn.show&&Ju(sn,Fn.filter(n,Le,v,ae,Ae),U,U==0?2:1,U==0?Ue:de,U==0?Me:Ee,Je(Fn.width*je,3),Fn.stroke(n,v),Fn.dash,Fn.cap),me.show&&Ju([Mt],[1],U==0?1:0,U==0?1:2,U==1?Ue:de,U==1?Me:Ee,Je(me.width*je,3),me.stroke(n,v),me.dash,me.cap)}Jt("drawAxes")}function ys(v){g.forEach((b,M)=>{M>0&&(b._paths=null,v&&(i==1?(b.min=null,b.max=null):b.facets.forEach(U=>{U.min=null,U.max=null})))})}let Va=!1,ec=!1,xo=[];function WC(){ec=!1;for(let v=0;v<xo.length;v++)Jt(...xo[v]);xo.length=0}function vs(){Va||(n5(op),Va=!0)}function GC(v,b=!1){Va=!0,ec=b,v(n),op(),b&&xo.length>0&&queueMicrotask(WC)}n.batch=GC;function op(){if(Ne&&(LC(),Ne=!1),De&&(Li(),De=!1),we){if(lt(f,Us,$e),lt(f,_o,ft),lt(f,Go,pe),lt(f,Xo,ne),lt(p,Us,$e),lt(p,_o,ft),lt(p,Go,pe),lt(p,Xo,ne),lt(h,Go,Se),lt(h,Xo,Re),c.width=$t(Se*je),c.height=$t(Re*je),y.forEach(({_el:v,_show:b,_size:M,_pos:U,side:B})=>{if(v!=null)if(b){let $=B===3||B===0?M:0,Y=B%2==1;lt(v,Y?"left":"top",U-$),lt(v,Y?"width":"height",M),lt(v,Y?"top":"left",Y?ft:$e),lt(v,Y?"height":"width",Y?ne:pe),yh(v,Ji)}else Wr(v,Ji)}),_a=ms=ju=Wu=Gu=Xu=Ku=Zu=Yu=null,zr=1,Eo(!0),$e!=Q||ft!=W||pe!=le||ne!=ye){ys(!1);let v=pe/le,b=ne/ye;if(ve&&!Tt&&K.left>=0){K.left*=v,K.top*=b,ws&&_n(ws,$t(K.left),0,pe,ne),Cs&&_n(Cs,0,$t(K.top),pe,ne);for(let M=0;M<hr.length;M++){let U=hr[M];U!=null&&(Pn[M]*=v,Bn[M]*=b,_n(U,an(Pn[M]),an(Bn[M]),pe,ne))}}if(st.show&&!pt&&st.left>=0&&st.width>0){st.left*=v,st.width*=v,st.top*=b,st.height*=b;for(let M in oc)lt(xs,M,st[M])}Q=$e,W=ft,le=pe,ye=ne}Jt("setSize"),we=!1}Se>0&&Re>0&&(d.clearRect(0,0,c.width,c.height),Jt("drawClear"),A.forEach(v=>v()),Jt("draw")),st.show&&pt&&(Ha(st),pt=!1),ve&&Tt&&(ji(null,!0,!1),Tt=!1),q.show&&q.live&&Ve&&(ic(),Ve=!1),l||(l=!0,n.status=1,Jt("ready")),So=!1,Va=!1}n.redraw=(v,b)=>{De=b||!1,v!==!1?ci(I,z.min,z.max):vs()};function tc(v,b){let M=C[v];if(M.from==null){if(ir==0){let U=M.range(n,b.min,b.max,v);b.min=U[0],b.max=U[1]}if(b.min>b.max){let U=b.min;b.min=b.max,b.max=U}if(ir>1&&b.min!=null&&b.max!=null&&b.max-b.min<1e-16)return;v==I&&M.distr==2&&ir>0&&(b.min=In(b.min,e[0]),b.max=In(b.max,e[0]),b.min==b.max&&b.max++),V[v]=b,Ne=!0,vs()}}n.setScale=tc;let rc,nc,ws,Cs,ap,lp,bs,Ss,up,cp,it,gt,ui=!1;const sr=K.drag;let qt=sr.x,Qt=sr.y;ve&&(K.x&&(rc=on(MM,p)),K.y&&(nc=on(UM,p)),z.ori==0?(ws=rc,Cs=nc):(ws=nc,Cs=rc),it=K.left,gt=K.top);const st=n.select=zt({show:!0,over:!0,left:0,width:0,top:0,height:0},r.select),xs=st.show?on(EM,st.over?p:f):null;function Ha(v,b){if(st.show){for(let M in v)st[M]=v[M],M in oc&<(xs,M,v[M]);b!==!1&&Jt("setSelect")}}n.setSelect=Ha;function XC(v){if(g[v].show)oe&&yh(xe[v],Ji);else if(oe&&Wr(xe[v],Ji),ve){let M=Rn?hr[0]:hr[v];M!=null&&_n(M,-10,-10,pe,ne)}}function ci(v,b,M){tc(v,{min:b,max:M})}function zn(v,b,M,U){b.focus!=null&&JC(v),b.show!=null&&g.forEach((B,$)=>{$>0&&(v==$||v==null)&&(B.show=b.show,XC($),i==2?(ci(B.facets[0].scale,null,null),ci(B.facets[1].scale,null,null)):ci(B.scale,null,null),vs())}),M!==!1&&Jt("setSeries",v,b),U&&Mo("setSeries",n,v,b)}n.setSeries=zn;function KC(v,b){zt(x[v],b)}function ZC(v,b){v.fill=Pe(v.fill||null),v.dir=_e(v.dir,-1),b=b??x.length,x.splice(b,0,v)}function qC(v){v==null?x.length=0:x.splice(v,1)}n.addBand=ZC,n.setBand=KC,n.delBand=qC;function QC(v,b){g[v].alpha=b,ve&&hr[v]!=null&&(hr[v].style.opacity=b),oe&&xe[v]&&(xe[v].style.opacity=b)}let Wn,di,Hi;const Is={focus:!0};function JC(v){if(v!=Hi){let b=v==null,M=dr.alpha!=1;g.forEach((U,B)=>{if(i==1||B>0){let $=b||B==0||B==v;U._focus=b?null:$,M&&QC(B,$?1:dr.alpha)}}),Hi=v,M&&vs()}}oe&&Tn&&nt(bm,Ce,v=>{K._lock||(Br(v),Hi!=null&&zn(null,Is,!0,Bt.setSeries))});function On(v,b,M){let U=C[b];M&&(v=v/je-(U.ori==1?ft:$e));let B=pe;U.ori==1&&(B=ne,v=B-v),U.dir==-1&&(v=B-v);let $=U._min,Y=U._max,Z=v/B,re=$+(Y-$)*Z,ae=U.distr;return ae==3?lo(10,re):ae==4?YM(re,U.asinh):ae==100?U.bwd(re):re}function eb(v,b){let M=On(v,I,b);return In(M,e[0],Kt,Zt)}n.valToIdx=v=>In(v,e[0]),n.posToIdx=eb,n.posToVal=On,n.valToPos=(v,b,M)=>C[b].ori==0?s(v,C[b],M?Ee:pe,M?de:0):o(v,C[b],M?Me:ne,M?Ue:0),n.setCursor=(v,b,M)=>{it=v.left,gt=v.top,ji(null,b,M)};function dp(v,b){lt(xs,Us,st.left=v),lt(xs,Go,st.width=b)}function hp(v,b){lt(xs,_o,st.top=v),lt(xs,Xo,st.height=b)}let Io=z.ori==0?dp:hp,ko=z.ori==1?dp:hp;function tb(){if(oe&&q.live)for(let v=i==2?1:0;v<g.length;v++){if(v==0&&qe)continue;let b=q.values[v],M=0;for(let U in b)et[v][M++].firstChild.nodeValue=b[U]}}function ic(v,b){if(v!=null&&(v.idxs?v.idxs.forEach((M,U)=>{ee[U]=M}):KM(v.idx)||ee.fill(v.idx),q.idx=ee[0]),oe&&q.live){for(let M=0;M<g.length;M++)(M>0||i==1&&!qe)&&rb(M,ee[M]);tb()}Ve=!1,b!==!1&&Jt("setLegend")}n.setLegend=ic;function rb(v,b){let M=g[v],U=v==0&&P==2?gn:e[v],B;qe?B=M.values(n,v,b)??At:(B=M.value(n,b==null?null:U[b],v,b),B=B==null?At:{_:B}),q.values[v]=B}function ji(v,b,M){up=it,cp=gt,[it,gt]=K.move(n,it,gt),K.left=it,K.top=gt,ve&&(ws&&_n(ws,$t(it),0,pe,ne),Cs&&_n(Cs,0,$t(gt),pe,ne));let U,B=Kt>Zt;Wn=Qe,di=null;let $=z.ori==0?pe:ne,Y=z.ori==1?pe:ne;if(it<0||ir==0||B){U=K.idx=null;for(let Z=0;Z<g.length;Z++){let re=hr[Z];re!=null&&_n(re,-10,-10,pe,ne)}Tn&&zn(null,Is,!0,v==null&&Bt.setSeries),q.live&&(ee.fill(U),Ve=!0)}else{let Z,re,ae;i==1&&(Z=z.ori==0?it:gt,re=On(Z,I),U=K.idx=In(re,e[0],Kt,Zt),ae=D(e[0][U],z,$,0));let ue=-10,he=-10,Ie=0,He=0,Le=!0,Ae="",be="";for(let me=i==2?1:0;me<g.length;me++){let ot=g[me],Et=ee[me],er=Et==null?null:i==1?e[me][Et]:e[me][1][Et],Ze=K.dataIdx(n,me,U,re),Mt=Ze==null?null:i==1?e[me][Ze]:e[me][1][Ze];if(Ve=Ve||Mt!=er||Ze!=Et,ee[me]=Ze,me>0&&ot.show){let Vr=Ze==null?-10:Ze==U?ae:D(i==1?e[0][Ze]:e[me][0][Ze],z,$,0),br=Mt==null?-10:L(Mt,i==1?C[ot.scale]:C[ot.facets[1].scale],Y,0);if(Tn&&Mt!=null){let nn=z.ori==1?it:gt,mn=jt(dr.dist(n,me,Ze,br,nn));if(mn<Wn){let Dn=dr.bias;if(Dn!=0){let Hr=On(nn,ot.scale),sn=Mt>=0?1:-1,yn=Hr>=0?1:-1;yn==sn&&(yn==1?Dn==1?Mt>=Hr:Mt<=Hr:Dn==1?Mt<=Hr:Mt>=Hr)&&(Wn=mn,di=me)}else Wn=mn,di=me}}if(Ve||Rn){let nn,mn;z.ori==0?(nn=Vr,mn=br):(nn=br,mn=Vr);let Dn,Hr,sn,yn,Fn,Sr,jr=!0,Yi=Ct.bbox;if(Yi!=null){jr=!1;let xr=Yi(n,me);sn=xr.left,yn=xr.top,Dn=xr.width,Hr=xr.height}else sn=nn,yn=mn,Dn=Hr=Ct.size(n,me);if(Sr=Ct.fill(n,me),Fn=Ct.stroke(n,me),Rn)me==di&&Wn<=dr.prox&&(ue=sn,he=yn,Ie=Dn,He=Hr,Le=jr,Ae=Sr,be=Fn);else{let xr=hr[me];xr!=null&&(Pn[me]=sn,Bn[me]=yn,Um(xr,Dn,Hr,jr),Em(xr,Sr,Fn),_n(xr,an(sn),an(yn),pe,ne))}}}}if(Rn){let me=dr.prox,ot=Hi==null?Wn<=me:Wn>me||di!=Hi;if(Ve||ot){let Et=hr[0];Et!=null&&(Pn[0]=ue,Bn[0]=he,Um(Et,Ie,He,Le),Em(Et,Ae,be),_n(Et,an(ue),an(he),pe,ne))}}}if(st.show&&ui)if(v!=null){let[Z,re]=Bt.scales,[ae,ue]=Bt.match,[he,Ie]=v.cursor.sync.scales,He=v.cursor.drag;if(qt=He._x,Qt=He._y,qt||Qt){let{left:Le,top:Ae,width:be,height:me}=v.select,ot=v.scales[he].ori,Et=v.posToVal,er,Ze,Mt,Vr,br,nn=Z!=null&&ae(Z,he),mn=re!=null&&ue(re,Ie);nn&&qt?(ot==0?(er=Le,Ze=be):(er=Ae,Ze=me),Mt=C[Z],Vr=D(Et(er,he),Mt,$,0),br=D(Et(er+Ze,he),Mt,$,0),Io(En(Vr,br),jt(br-Vr))):Io(0,$),mn&&Qt?(ot==1?(er=Le,Ze=be):(er=Ae,Ze=me),Mt=C[re],Vr=L(Et(er,Ie),Mt,Y,0),br=L(Et(er+Ze,Ie),Mt,Y,0),ko(En(Vr,br),jt(br-Vr))):ko(0,Y)}else ac()}else{let Z=jt(up-ap),re=jt(cp-lp);if(z.ori==1){let Ie=Z;Z=re,re=Ie}qt=sr.x&&Z>=sr.dist,Qt=sr.y&&re>=sr.dist;let ae=sr.uni;ae!=null?qt&&Qt&&(qt=Z>=ae,Qt=re>=ae,!qt&&!Qt&&(re>Z?Qt=!0:qt=!0)):sr.x&&sr.y&&(qt||Qt)&&(qt=Qt=!0);let ue,he;qt&&(z.ori==0?(ue=bs,he=it):(ue=Ss,he=gt),Io(En(ue,he),jt(he-ue)),Qt||ko(0,Y)),Qt&&(z.ori==1?(ue=bs,he=it):(ue=Ss,he=gt),ko(En(ue,he),jt(he-ue)),qt||Io(0,$)),!qt&&!Qt&&(Io(0,0),ko(0,0))}if(sr._x=qt,sr._y=Qt,v==null){if(M){if(xp!=null){let[Z,re]=Bt.scales;Bt.values[0]=Z!=null?On(z.ori==0?it:gt,Z):null,Bt.values[1]=re!=null?On(z.ori==1?it:gt,re):null}Mo(Gc,n,it,gt,pe,ne,U)}if(Tn){let Z=M&&Bt.setSeries,re=dr.prox;Hi==null?Wn<=re&&zn(di,Is,!0,Z):Wn>re?zn(null,Is,!0,Z):di!=Hi&&zn(di,Is,!0,Z)}}Ve&&(q.idx=U,ic()),b!==!1&&Jt("setCursor")}let hi=null;Object.defineProperty(n,"rect",{get(){return hi==null&&Eo(!1),hi}});function Eo(v=!1){v?hi=null:(hi=p.getBoundingClientRect(),Jt("syncRect",hi))}function fp(v,b,M,U,B,$,Y){K._lock||ui&&v!=null&&v.movementX==0&&v.movementY==0||(sc(v,b,M,U,B,$,Y,!1,v!=null),v!=null?ji(null,!0,!0):ji(b,!0,!1))}function sc(v,b,M,U,B,$,Y,Z,re){if(hi==null&&Eo(!1),Br(v),v!=null)M=v.clientX-hi.left,U=v.clientY-hi.top;else{if(M<0||U<0){it=-10,gt=-10;return}let[ae,ue]=Bt.scales,he=b.cursor.sync,[Ie,He]=he.values,[Le,Ae]=he.scales,[be,me]=Bt.match,ot=b.axes[0].side%2==1,Et=z.ori==0?pe:ne,er=z.ori==1?pe:ne,Ze=ot?$:B,Mt=ot?B:$,Vr=ot?U:M,br=ot?M:U;if(Le!=null?M=be(ae,Le)?a(Ie,C[ae],Et,0):-10:M=Et*(Vr/Ze),Ae!=null?U=me(ue,Ae)?a(He,C[ue],er,0):-10:U=er*(br/Mt),z.ori==1){let nn=M;M=U,U=nn}}re&&(b==null||b.cursor.event.type==Gc)&&((M<=1||M>=pe-1)&&(M=qi(M,pe)),(U<=1||U>=ne-1)&&(U=qi(U,ne))),Z?(ap=M,lp=U,[bs,Ss]=K.move(n,M,U)):(it=M,gt=U)}const oc={width:0,height:0,left:0,top:0};function ac(){Ha(oc,!1)}let pp,gp,mp,yp;function vp(v,b,M,U,B,$,Y){ui=!0,qt=Qt=sr._x=sr._y=!1,sc(v,b,M,U,B,$,Y,!0,!1),v!=null&&(nt(Xc,gh,wp,!1),Mo(wm,n,bs,Ss,pe,ne,null));let{left:Z,top:re,width:ae,height:ue}=st;pp=Z,gp=re,mp=ae,yp=ue}function wp(v,b,M,U,B,$,Y){ui=sr._x=sr._y=!1,sc(v,b,M,U,B,$,Y,!1,!0);let{left:Z,top:re,width:ae,height:ue}=st,he=ae>0||ue>0,Ie=pp!=Z||gp!=re||mp!=ae||yp!=ue;if(he&&Ie&&Ha(st),sr.setScale&&he&&Ie){let He=Z,Le=ae,Ae=re,be=ue;if(z.ori==1&&(He=re,Le=ue,Ae=Z,be=ae),qt&&ci(I,On(He,I),On(He+Le,I)),Qt)for(let me in C){let ot=C[me];me!=I&&ot.from==null&&ot.min!=Qe&&ci(me,On(Ae+be,me),On(Ae,me))}ac()}else K.lock&&(K._lock=!K._lock,ji(b,!0,v!=null));v!=null&&(Cr(Xc,gh),Mo(Xc,n,it,gt,pe,ne,null))}function nb(v,b,M,U,B,$,Y){if(K._lock)return;Br(v);let Z=ui;if(ui){let re=!0,ae=!0,ue=10,he,Ie;z.ori==0?(he=qt,Ie=Qt):(he=Qt,Ie=qt),he&&Ie&&(re=it<=ue||it>=pe-ue,ae=gt<=ue||gt>=ne-ue),he&&re&&(it=it<bs?0:pe),Ie&&ae&&(gt=gt<Ss?0:ne),ji(null,!0,!0),ui=!1}it=-10,gt=-10,ee.fill(null),ji(null,!0,!0),Z&&(ui=Z)}function Cp(v,b,M,U,B,$,Y){K._lock||(Br(v),Hu(),ac(),v!=null&&Mo(Sm,n,it,gt,pe,ne,null))}function bp(){y.forEach(dU),Xt(n.width,n.height,!0)}ss(uu,Js,bp);const ks={};ks.mousedown=vp,ks.mousemove=fp,ks.mouseup=wp,ks.dblclick=Cp,ks.setSeries=(v,b,M,U)=>{let B=Bt.match[2];M=B(n,b,M),M!=-1&&zn(M,U,!0,!1)},ve&&(nt(wm,p,vp),nt(Gc,p,fp),nt(Cm,p,v=>{Br(v),Eo(!1)}),nt(bm,p,nb),nt(Sm,p,Cp),xh.add(n),n.syncRect=Eo);const ja=n.hooks=r.hooks||{};function Jt(v,b,M){ec?xo.push([v,b,M]):v in ja&&ja[v].forEach(U=>{U.call(null,n,b,M)})}(r.plugins||[]).forEach(v=>{for(let b in v.hooks)ja[b]=(ja[b]||[]).concat(v.hooks[b])});const Sp=(v,b,M)=>M,Bt=zt({key:null,setSeries:!1,filters:{pub:Bm,sub:Bm},scales:[I,g[1]?g[1].scale:null],match:[zm,zm,Sp],values:[null,null]},K.sync);Bt.match.length==2&&Bt.match.push(Sp),K.sync=Bt;const xp=Bt.key,lc=bC(xp);function Mo(v,b,M,U,B,$,Y){Bt.filters.pub(v,b,M,U,B,$,Y)&&lc.pub(v,b,M,U,B,$,Y)}lc.sub(n);function ib(v,b,M,U,B,$,Y){Bt.filters.sub(v,b,M,U,B,$,Y)&&ks[v](null,b,M,U,B,$,Y)}n.pub=ib;function sb(){lc.unsub(n),xh.delete(n),kt.clear(),vh(uu,Js,bp),u.remove(),Ce==null||Ce.remove(),Jt("destroy")}n.destroy=sb;function uc(){Jt("init",r,e),Jf(e||r.data,!1),V[I]?tc(I,V[I]):Hu(),pt=st.show&&(st.width>0||st.height>0),Tt=Ve=!0,Xt(r.width,r.height)}return g.forEach(Pt),y.forEach(FC),t?t instanceof HTMLElement?(t.appendChild(u),uc()):t(n,uc):uc(),n}yr.assign=zt;yr.fmtNum=Nf;yr.rangeNum=cu;yr.rangeLog=Du;yr.rangeAsinh=_f;yr.orient=ps;yr.pxRatio=je;yr.join=r5;yr.fmtDate=Hf,yr.tzDate=f5;yr.sync=bC;{yr.addGap=K5,yr.clipGaps=_u;let r=yr.paths={points:MC};r.linear=AC,r.stepped=Q5,r.bars=J5,r.spline=tU}function hU(r,e){const t=/^#([0-9a-fA-F]{6})([0-9a-fA-F]{2})?$/.exec(r.trim());return t?`#${t[1]}${e}`:r}function BC({data:r,seriesKeys:e,seriesLabels:t,colors:n,height:i=300,tickRate:s=60,windowSeconds:o=20,hoveredKey:a=null,onHoverKey:l}){const u=N.useRef(null),c=N.useRef(null),d=N.useRef(null),h=N.useMemo(()=>e.join("|"),[e]),f=N.useMemo(()=>{const w=Math.max(1,Math.round(o*s)),g=Math.max(0,r.length-w),y=r.slice(g),C=Math.max(0,w-y.length),x=new Array(w);for(let E=0;E<w;E++)x[E]=E;const I=e.map(()=>new Array(w).fill(0));for(let E=0;E<y.length;E++){const A=y[E],R=C+E;for(let F=0;F<e.length;F++){const z=e[F],P=Number(A[z]??0);I[F][R]=Number.isFinite(P)?P:0}}return{x,series:I,windowPoints:w}},[r,e,s,o]),p=N.useMemo(()=>[f.x,...f.series],[f]),m=N.useMemo(()=>{const w=typeof globalThis.devicePixelRatio=="number"?globalThis.devicePixelRatio:1,g=[{label:"t"},...e.map((y,C)=>{const x=n[C%n.length]??"#4fc1ff";return{label:t[y]??y,stroke:x,width:2,points:{show:!1}}})];return{width:800,height:i,pxAlign:0,pxRatio:w,padding:[10,10,10,10],scales:{x:{time:!1},y:{}},axes:[{stroke:"#555",grid:{stroke:"#222",width:1},size:0,values:(y,C)=>C.map(()=>"")},{stroke:"#555",grid:{stroke:"#222",width:1}}],series:g,legend:{show:!1},cursor:{drag:{x:!1,y:!1}},hooks:{setCursor:[y=>{var F;if(!l)return;const C=y.cursor.idx;if(C==null||C<0){d.current!==null&&(d.current=null,l(null));return}const x=y.cursor.top;if(x==null||!Number.isFinite(x)){d.current!==null&&(d.current=null,l(null));return}let I=null,E=Number.POSITIVE_INFINITY;for(let z=1;z<y.series.length;z++){const P=e[z-1],D=(F=y.data[z])==null?void 0:F[C];if(D==null||!Number.isFinite(D))continue;const L=y.valToPos(D,"y",!0),V=Math.abs(L-x);V<E&&(E=V,I=P)}const R=E<=12?I:null;d.current!==R&&(d.current=R,l(R))}]}}},[n,i,l,e,t]),S=N.useMemo(()=>e.map((w,g)=>{const y=n[g%n.length]??"#4fc1ff",C=a!=null&&a===w;return{stroke:a!=null&&a!==w?hU(y,"66"):y,width:C?3:2}}),[n,a,e]);return N.useEffect(()=>{var I;const w=u.current;if(!w)return;const g=()=>{l&&d.current!==null&&(d.current=null,l(null))};w.addEventListener("mouseleave",g),(I=c.current)==null||I.destroy(),c.current=null;const y=new yr(m,p,w);c.current=y;const C=new ResizeObserver(()=>{const E=w.getBoundingClientRect();y.setSize({width:Math.max(1,Math.floor(E.width)),height:i})});C.observe(w);const x=w.getBoundingClientRect();return y.setSize({width:Math.max(1,Math.floor(x.width)),height:i}),()=>{w.removeEventListener("mouseleave",g),C.disconnect(),y.destroy(),c.current=null}},[m,p,i,l,h]),N.useEffect(()=>{var w;(w=c.current)==null||w.setData(p)},[p]),N.useEffect(()=>{const w=c.current;if(w)for(let g=0;g<S.length;g++){const y=g+1,C=S[g],x=w.series[y];!x||!C||(x.stroke!==C.stroke||x.width!==C.width)&&w.setSeries(y,{stroke:C.stroke,width:C.width})}},[S]),k.jsx("div",{ref:u,style:{width:"100%",height:i}})}const Or=(r,e)=>r===e?0:r<e?-1:1,ry=(r,e)=>r.localeCompare(e,void 0,{numeric:!0}),gl=r=>(r??"").trim();function fU({sortedTraffic:r,topTraffic:e,chartData:t,topKeys:n,keyToLabel:i,keyToColor:s,tickRate:o,hoveredTrafficKey:a,setHoveredTrafficKey:l}){const[u,c]=N.useState("bps"),[d,h]=N.useState("desc"),[f,p]=N.useState("bps"),[m,S]=N.useState("desc"),[w,g]=N.useState("bps"),[y,C]=N.useState("desc"),x=T=>{if(T===u){h(_=>_==="asc"?"desc":"asc");return}c(T),h(T==="name"?"asc":"desc")},I=T=>{if(T===w){C(_=>_==="asc"?"desc":"asc");return}g(T),C(T==="name"?"asc":"desc")},E=T=>{if(T===f){S(_=>_==="asc"?"desc":"asc");return}p(T),S(T==="name"?"asc":"desc")},A=(T,_,j)=>{const G=j==="asc"?1:-1,ee=[...T];return ee.sort((q,K)=>{let oe=0;switch(_){case"id":oe=Or(q.id,K.id);break;case"name":{const ve=gl(q.name),ge=gl(K.name);oe=ry(ve,ge),oe===0&&(oe=Or(q.id,K.id));break}case"encoding":{const ve=gl(q.encoding),ge=gl(K.encoding);oe=ry(ve,ge),oe===0&&(oe=Or(q.id,K.id));break}case"bps":oe=Or(q.bps,K.bps),oe===0&&(oe=Or(q.total,K.total));break;case"total":oe=Or(q.total,K.total),oe===0&&(oe=Or(q.bps,K.bps));break;case"size":{const ve=q.size.x*q.size.y,ge=K.size.x*K.size.y;oe=Or(ve,ge),oe===0&&(oe=Or(q.id,K.id));break}case"position":{oe=Or(q.position.x,K.position.x),oe===0&&(oe=Or(q.position.y,K.position.y)),oe===0&&(oe=Or(q.id,K.id));break}case"zIndex":oe=Or(q.zIndex,K.zIndex),oe===0&&(oe=Or(q.id,K.id));break}return oe*G}),ee},R=N.useMemo(()=>r.filter(T=>T.key.startsWith("layer-")),[r]),F=N.useMemo(()=>r.filter(T=>T.key.startsWith("misc-")),[r]),z=N.useMemo(()=>r.filter(T=>T.key.startsWith("display-")),[r]),P=N.useMemo(()=>A(R,u,d),[R,d,u]),D=N.useMemo(()=>A(F,w,y),[F,y,w]),L=N.useMemo(()=>A(z,f,m),[z,m,f]),V={userSelect:"none",cursor:"pointer"},X=(T,_,j)=>T!==_?"":j==="asc"?" ▲":" ▼";return k.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",gap:12,padding:12,overflow:"auto",background:"#1b1b1b",color:"#cccccc"},children:[k.jsx("div",{style:{fontSize:13,color:"#e0e0e0",fontWeight:600},children:"Bandwidth"}),R.length===0&&F.length===0&&k.jsx("div",{style:{color:"#888",fontSize:12},children:"No bandwidth data yet. Move the client or send data to see traffic."}),R.length>0&&e.length>0&&k.jsxs("div",{style:{width:"100%",height:300,border:"1px solid #333",background:"#111",padding:"8px 12px 12px",boxSizing:"border-box"},children:[k.jsx("div",{style:{marginBottom:8,color:"#aaa",fontSize:12},children:"Lines — per-layer bandwidth (B/s, last samples)"}),k.jsx(BC,{data:t,seriesKeys:n,seriesLabels:i,colors:n.map(T=>s[T]??"#4fc1ff"),height:260,tickRate:o,windowSeconds:60,hoveredKey:a,onHoverKey:l})]}),R.length>0&&k.jsxs("div",{style:{border:"1px solid #333",background:"#111",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{color:"#aaa",fontSize:12,marginBottom:2},children:"Layers"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1.1fr 0.55fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,color:"#aaa",fontSize:12},children:[k.jsxs("div",{style:V,onClick:()=>x("id"),title:"Sort by ID",children:["ID",X("id",u,d)]}),k.jsxs("div",{style:V,onClick:()=>x("name"),title:"Sort by name",children:["Name",X("name",u,d)]}),k.jsxs("div",{style:V,onClick:()=>x("encoding"),title:"Sort by encoding",children:["Encoding",X("encoding",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("bps"),title:"Sort by Network/s",children:["Network/s",X("bps",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("total"),title:"Sort by Network",children:["Network",X("total",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("size"),title:"Sort by size",children:["Size",X("size",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("position"),title:"Sort by position",children:["Position",X("position",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("zIndex"),title:"Sort by zIndex",children:["zIndex",X("zIndex",u,d)]})]}),P.map(T=>k.jsxs("div",{onMouseEnter:()=>l(T.key),onMouseLeave:()=>l(null),style:{display:"grid",gridTemplateColumns:"70px 1.1fr 0.55fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,fontSize:12,color:a===T.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===T.key?"#1a1a1a":"transparent",outline:a===T.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:T.id}),k.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:2,marginRight:8,verticalAlign:"middle",background:s[T.key]??"#666",boxShadow:a===T.key?`0 0 0 1px #000, 0 0 0 2px ${s[T.key]??"#666"}`:"0 0 0 1px #000"}}),(()=>{var j;const _=((j=T.name)==null?void 0:j.trim())||`Layer ${T.id}`;return T.id===255?`${_} (debug)`:_})()]}),k.jsx("div",{style:{color:"#bbb"},children:T.encoding??""}),k.jsxs("div",{style:{textAlign:"right"},children:[Kr(T.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Kr(T.total)}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.size.x,"×",T.size.y]}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.position.x,"/",T.position.y]}),k.jsx("div",{style:{textAlign:"right",color:"#999"},children:T.zIndex})]},T.key))]}),z.length>0&&k.jsxs("div",{style:{border:"1px solid #333",background:"#111",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{color:"#aaa",fontSize:12,marginBottom:2},children:"Displays"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,color:"#aaa",fontSize:12},children:[k.jsxs("div",{style:V,onClick:()=>E("id"),title:"Sort by ID",children:["ID",X("id",f,m)]}),k.jsxs("div",{style:V,onClick:()=>E("name"),title:"Sort by name",children:["Name",X("name",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("bps"),title:"Sort by Network/s",children:["Network/s",X("bps",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("total"),title:"Sort by Network",children:["Network",X("total",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("size"),title:"Sort by size",children:["Size",X("size",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("position"),title:"Sort by position",children:["Position",X("position",f,m)]}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"zIndex"})]}),L.map(T=>{var _;return k.jsxs("div",{onMouseEnter:()=>l(T.key),onMouseLeave:()=>l(null),style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,fontSize:12,color:a===T.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===T.key?"#1a1a1a":"transparent",outline:a===T.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:T.id}),k.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:2,marginRight:8,verticalAlign:"middle",background:s[T.key]??"#666",boxShadow:a===T.key?`0 0 0 1px #000, 0 0 0 2px ${s[T.key]??"#666"}`:"0 0 0 1px #000"}}),((_=T.name)==null?void 0:_.trim())||`Display ${T.id}`]}),k.jsxs("div",{style:{textAlign:"right"},children:[Kr(T.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Kr(T.total)}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.size.x,"×",T.size.y]}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.position.x,"/",T.position.y]}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"})]},T.key)})]}),F.length>0&&k.jsxs("div",{style:{border:"1px solid #333",background:"#111",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{color:"#aaa",fontSize:12,marginBottom:2},children:"Updates (non-layer)"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,color:"#aaa",fontSize:12},children:[k.jsxs("div",{style:V,onClick:()=>I("id"),title:"Sort by ID",children:["ID",X("id",w,y)]}),k.jsxs("div",{style:V,onClick:()=>I("name"),title:"Sort by name",children:["Name",X("name",w,y)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>I("bps"),title:"Sort by Network/s",children:["Network/s",X("bps",w,y)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>I("total"),title:"Sort by Network",children:["Network",X("total",w,y)]}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"Size"}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"Position"}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"zIndex"})]}),D.map(T=>k.jsxs("div",{onMouseEnter:()=>l(T.key),onMouseLeave:()=>l(null),style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,fontSize:12,color:a===T.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===T.key?"#1a1a1a":"transparent",outline:a===T.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:T.id}),k.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:2,marginRight:8,verticalAlign:"middle",background:s[T.key]??"#666",boxShadow:a===T.key?`0 0 0 1px #000, 0 0 0 2px ${s[T.key]??"#666"}`:"0 0 0 1px #000"}}),T.name??"—"]}),k.jsxs("div",{style:{textAlign:"right"},children:[Kr(T.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Kr(T.total)}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"})]},T.key))]})]})}const tr=65536,Jc=.005,ed=32;function pU({layers:r,displays:e=[],width:t,height:n,hoveredLayerId:i=null,selectedLayerIds:s=null,hoveredDisplayId:o=null,selectedDisplayId:a=null,focusRect:l=null,focusKey:u="",onSelectLayer:c,onSelectDisplay:d,onToolRectCommit:h}){const f=N.useRef(null),[p,m]=N.useState(1),[S,w]=N.useState({x:0,y:0}),g=N.useRef(!1),y=N.useRef({x:0,y:0}),C=N.useRef(""),[x,I]=N.useState(!1),[E,A]=N.useState(null),[R,F]=N.useState(null),[z,P]=N.useState("none"),[D,L]=N.useState(null),V=N.useRef(null),[X,T]=N.useState(!1),_=N.useRef(!1),j=N.useRef(!1),G=N.useCallback((Q,W,le)=>{const ye=t/le,de=n/le,Ue=ye*.5,Ee=de*.5,Me=Math.max(0,tr-ye)+Ue,Ne=Math.max(0,tr-de)+Ee,we=-Ue,De=-Ee;return{x:Math.max(we,Math.min(Me,Q)),y:Math.max(De,Math.min(Ne,W))}},[t,n]),ee=N.useCallback(()=>{const Q=tr*p,W=tr*p,le=Q<t?(t-Q)/2:0,ye=W<n?(n-W)/2:0;return{toScreenX:Ne=>(Ne-S.x)*p+le,toScreenY:Ne=>(Ne-S.y)*p+ye,toWorldX:Ne=>(Ne-le)/p+S.x,toWorldY:Ne=>(Ne-ye)/p+S.y}},[n,S.x,S.y,p,t]),q=N.useCallback((Q,W)=>{let le=null;for(let ye=0;ye<r.length;ye++){const de=r[ye];if(Q<de.x||Q>de.x+de.width||W<de.y||W>de.y+de.height)continue;const Ue=de.zIndex??0;(!le||Ue>le.z)&&(le={id:de.id,z:Ue})}if(le)return{kind:"layer",id:le.id,zIndex:le.z};for(let ye=e.length-1;ye>=0;ye--){const de=e[ye];if(Q>=de.x&&Q<=de.x+de.width&&W>=de.y&&W<=de.y+de.height)return{kind:"display",id:de.id}}return null},[e,r]),K=N.useCallback((Q,W)=>{const le=[];for(let ye=0;ye<r.length;ye++){const de=r[ye];Q<de.x||Q>de.x+de.width||W<de.y||W>de.y+de.height||le.push({id:de.id,zIndex:de.zIndex??0,name:de.name})}return le.sort((ye,de)=>de.zIndex-ye.zIndex),le},[r]);N.useEffect(()=>{const Q=f.current;if(!Q)return;const W=Q.getContext("2d");if(!W)return;W.clearRect(0,0,t,n),W.fillStyle="#0a0e14",W.fillRect(0,0,t,n);const le=tr*p,ye=tr*p,de=le<t?(t-le)/2:0,Ue=ye<n?(n-ye)/2:0,Ee=we=>(we-S.x)*p+de,Me=we=>(we-S.y)*p+Ue;{const we=Ee(0),De=Ee(tr),Tt=Me(0),pt=Me(tr),Ve=Math.max(0,we),Xt=Math.min(t,De),Lt=Math.max(0,Tt),ai=Math.min(n,pt);if(!(Xt<=Ve||ai<=Lt)){const Li=[{step:1,alpha:.06,lineWidth:1,minGapPx:8},{step:16,alpha:.1,lineWidth:1,minGapPx:10},{step:256,alpha:.16,lineWidth:1.25,minGapPx:12},{step:4096,alpha:.22,lineWidth:1.5,minGapPx:14}];W.save(),W.beginPath(),W.rect(Ve,Lt,Xt-Ve,ai-Lt),W.clip();let _i=!1;for(const Fe of Li){if(Fe.step*p<Fe.minGapPx)continue;_i=!0,W.strokeStyle=`rgba(255,255,255,${Fe.alpha})`,W.lineWidth=Fe.lineWidth;const Br=bt=>(bt-de)/p+S.x,Ct=bt=>(bt-Ue)/p+S.y,dr=Math.max(0,Br(0)),Tn=Math.min(tr,Br(t)),Rn=Math.max(0,Ct(0)),hr=Math.min(tr,Ct(n)),Pn=Math.floor(dr/Fe.step)*Fe.step,Bn=Math.ceil(Tn/Fe.step)*Fe.step,gs=Math.floor(Rn/Fe.step)*Fe.step,Pt=Math.ceil(hr/Fe.step)*Fe.step;W.beginPath();for(let bt=Pn;bt<=Bn;bt+=Fe.step){if(bt<0||bt>tr)continue;const Ni=Ee(bt);W.moveTo(Ni,Lt),W.lineTo(Ni,ai)}for(let bt=gs;bt<=Pt;bt+=Fe.step){if(bt<0||bt>tr)continue;const Ni=Me(bt);W.moveTo(Ve,Ni),W.lineTo(Xt,Ni)}W.stroke()}if(!_i){const Fe=Li[Li.length-1];W.strokeStyle=`rgba(255,255,255,${Fe.alpha})`,W.lineWidth=Fe.lineWidth;const $i=Pt=>(Pt-de)/p+S.x,Br=Pt=>(Pt-Ue)/p+S.y,Ct=Math.max(0,$i(0)),dr=Math.min(tr,$i(t)),Tn=Math.max(0,Br(0)),Rn=Math.min(tr,Br(n)),hr=Math.floor(Ct/Fe.step)*Fe.step,Pn=Math.ceil(dr/Fe.step)*Fe.step,Bn=Math.floor(Tn/Fe.step)*Fe.step,gs=Math.ceil(Rn/Fe.step)*Fe.step;W.beginPath();for(let Pt=hr;Pt<=Pn;Pt+=Fe.step){if(Pt<0||Pt>tr)continue;const bt=Ee(Pt);W.moveTo(bt,Lt),W.lineTo(bt,ai)}for(let Pt=Bn;Pt<=gs;Pt+=Fe.step){if(Pt<0||Pt>tr)continue;const bt=Me(Pt);W.moveTo(Ve,bt),W.lineTo(Xt,bt)}W.stroke()}W.restore()}}const Ne=[...r].sort((we,De)=>(we.zIndex??0)-(De.zIndex??0));for(const we of Ne){const De=s!=null&&s.includes(we.id),Tt=i!=null&&we.id===i,pt=Ee(we.x),Ve=Me(we.y),Xt=we.width*p,Lt=we.height*p;if(pt+Xt<0||Ve+Lt<0||pt>t||Ve>n)continue;const ai=we.zIndex??0,Li=we.color??(De?"rgba(43, 140, 255, 0.60)":Tt?"rgba(102, 217, 239, 0.40)":"rgba(43, 140, 255, 0.42)");if(W.fillStyle=Li,W.fillRect(pt,Ve,Math.max(Xt,1),Math.max(Lt,1)),W.strokeStyle=De?"#66d9ef":Tt?"rgba(102, 217, 239, 0.70)":"rgba(255,255,255,0.30)",W.lineWidth=De?2:1,W.strokeRect(pt,Ve,Math.max(Xt,1),Math.max(Lt,1)),p>=3&&Xt>=40&&Lt>=16){W.font="11px monospace",W.textBaseline="top";const _i=`z=${ai}`,Fe=4,$i=3,Ct=W.measureText(_i).width+Fe*2,dr=14;W.fillStyle="rgba(0,0,0,0.55)",W.fillRect(pt+3,Ve+3,Ct,dr),W.fillStyle="rgba(255,255,255,0.85)",W.fillText(_i,pt+3+Fe,Ve+3+$i)}}for(const we of e){const De=a!=null&&we.id===a,Tt=o!=null&&we.id===o,pt=Ee(we.x),Ve=Me(we.y),Xt=we.width*p,Lt=we.height*p;pt+Xt<0||Ve+Lt<0||pt>t||Ve>n||(W.strokeStyle=De?"rgba(255, 120, 120, 1)":Tt?"rgba(255, 120, 120, 0.8)":"rgba(255, 80, 80, 0.9)",W.lineWidth=De?3:2,W.strokeRect(pt,Ve,Math.max(Xt,1),Math.max(Lt,1)))}if(D){const we=Ee(D.x),De=Me(D.y),Tt=D.width*p,pt=D.height*p;W.strokeStyle="rgba(43, 140, 255, 1)",W.lineWidth=2,W.setLineDash([6,4]),W.strokeRect(we,De,Math.max(Tt,1),Math.max(pt,1)),W.setLineDash([])}},[r,e,t,n,p,S,i,s,o,a,D]);const oe=N.useCallback((Q,W)=>{var we;const le=(we=f.current)==null?void 0:we.getBoundingClientRect();if(!le)return null;const ye=Q-le.left,de=W-le.top,{toWorldX:Ue,toWorldY:Ee}=ee(),Me=Ue(ye),Ne=Ee(de);return{x:Me,y:Ne}},[ee]),ve=N.useCallback((Q,W)=>{const le=Math.floor(Math.min(Q.x,W.x)),ye=Math.floor(Math.min(Q.y,W.y)),de=Math.ceil(Math.max(Q.x,W.x)),Ue=Math.ceil(Math.max(Q.y,W.y));return{x:le,y:ye,width:Math.max(1,de-le),height:Math.max(1,Ue-ye)}},[]);N.useEffect(()=>{if(!l){C.current="";return}const Q=`${u}-${l.id}-${l.x}-${l.y}-${l.width}-${l.height}-${t}-${n}`;if(Q===C.current)return;if(j.current){j.current=!1,C.current=Q;return}C.current=Q;const W=1.25,le=Math.max(Jc,Math.min(ed,Math.min(t/(l.width*W),n/(l.height*W)))),ye=t/le,de=n/le,Ue=l.x+l.width/2,Ee=l.y+l.height/2,Me=G(Ue-ye/2,Ee-de/2,le);m(le),w(Me)},[l,u,t,n,G]);const ge=N.useCallback(Q=>{var Lt;const W=(Lt=f.current)==null?void 0:Lt.getBoundingClientRect();if(!W)return;Q.preventDefault();const le=Q.clientX-W.left,ye=Q.clientY-W.top,{toWorldX:de,toWorldY:Ue}=ee(),Ee=de(le),Me=Ue(ye),Ne=Q.deltaY<0?1.15:1/1.15,we=Math.max(Jc,Math.min(ed,p*Ne)),De=tr*we,Tt=tr*we,pt=De<t?(t-De)/2:0,Ve=Tt<n?(n-Tt)/2:0,Xt=G(Ee-(le-pt)/we,Me-(ye-Ve)/we,we);m(we),w(Xt)},[G,ee,n,S,p,t]);N.useEffect(()=>{const Q=f.current;if(!Q)return;const W=le=>ge(le);return Q.addEventListener("wheel",W,{passive:!1}),()=>Q.removeEventListener("wheel",W)},[ge]);const Ce=N.useCallback(Q=>{g.current=!0,I(!0),y.current={x:Q.clientX,y:Q.clientY}},[]),dt=N.useCallback(()=>{g.current=!1,I(!1)},[]),ht=N.useCallback(()=>{g.current=!1,I(!1),A(null)},[]),xe=N.useCallback(Q=>{const W=oe(Q.clientX,Q.clientY);if(!W||z!=="rect"||!h)return;Q.preventDefault(),Q.stopPropagation(),_.current=!0;const le={x:Math.floor(W.x),y:Math.floor(W.y)};V.current={startWorld:le,moved:!1},T(!0),L({x:le.x,y:le.y,width:1,height:1})},[z,oe,h]),et=N.useCallback(Q=>{if(!V.current)return;const W=oe(Q.clientX,Q.clientY);if(!W)return;const le=ve(V.current.startWorld,W);if(!V.current.moved){const ye=Math.abs(W.x-V.current.startWorld.x),de=Math.abs(W.y-V.current.startWorld.y);(ye>0||de>0)&&(V.current.moved=!0)}L(le)},[oe,ve]),Ke=N.useCallback(()=>{!V.current||!D||(_.current=!0,h==null||h(D),j.current=!0,V.current=null,L(null),T(!1),P("none"))},[D,h]),qe=N.useCallback(Q=>{if(V.current){if(Q.preventDefault(),Q.stopPropagation(),!V.current.moved){_.current=!0,V.current=null,L(null),T(!1),P("none");return}Ke()}},[Ke]);N.useEffect(()=>{if(!X)return;const Q=le=>{et(le)},W=le=>{qe(le)};return window.addEventListener("mousemove",Q,!0),window.addEventListener("mouseup",W,!0),()=>{window.removeEventListener("mousemove",Q,!0),window.removeEventListener("mouseup",W,!0)}},[X,et,qe]),N.useEffect(()=>{if(!V.current)return;const Q=W=>{W.key==="Enter"&&Ke()};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[Ke]);const At=N.useCallback(Q=>{var we;if(V.current){et(Q);return}if(g.current){const De=Q.clientX-y.current.x,Tt=Q.clientY-y.current.y;y.current={x:Q.clientX,y:Q.clientY},w(pt=>G(pt.x-De/p,pt.y-Tt/p,p));return}const W=(we=f.current)==null?void 0:we.getBoundingClientRect();if(!W)return;const le=Q.clientX-W.left,ye=Q.clientY-W.top,{toWorldX:de,toWorldY:Ue}=ee(),Ee=Math.floor(de(le)),Me=Math.floor(Ue(ye)),Ne=q(Ee,Me);if(!Ne){A({kind:"layer",id:-1,world:{x:Ee,y:Me},screen:{x:le,y:ye}});return}A({kind:Ne.kind,id:Ne.id,world:{x:Ee,y:Me},screen:{x:le,y:ye}})},[G,ee,q,p]),wt=N.useCallback(Q=>{var De;if(_.current){_.current=!1;return}if(z==="rect"||V.current||x)return;const W=(De=f.current)==null?void 0:De.getBoundingClientRect();if(!W)return;const le=Q.clientX-W.left,ye=Q.clientY-W.top,{toWorldX:de,toWorldY:Ue}=ee(),Ee=Math.floor(de(le)),Me=Math.floor(Ue(ye)),Ne=K(Ee,Me);if(Ne.length>=2){F({open:!0,anchorScreen:{x:le,y:ye},world:{x:Ee,y:Me},layers:Ne});return}const we=q(Ee,Me);we&&(we.kind==="layer"&&(c==null||c(we.id,{metaKey:Q.metaKey,ctrlKey:Q.ctrlKey})),we.kind==="display"&&(d==null||d(we.id)))},[z,ee,q,K,x,d,c]);N.useEffect(()=>{const Q=W=>{W.key==="Escape"&&F(null)};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[]);const Ft=N.useCallback(()=>{m(1),w(G(0,0,1))},[G]),cr=N.useCallback(Q=>{var De;const W=(De=f.current)==null?void 0:De.getBoundingClientRect();if(!W)return;const le=W.width/2,ye=W.height/2,{toWorldX:de,toWorldY:Ue}=ee(),Ee=de(le),Me=Ue(ye),Ne=Math.max(Jc,Math.min(ed,p*Q)),we=G(Ee-le/Ne,Me-ye/Ne,Ne);m(Ne),w(we)},[G,ee,p]),tt=E&&E.id!==-1?E:null,kt=n<520?6:10,nt=Math.max(40,n-kt*2),Cr=88,Se=42,Re=nt<150,pe=nt<240,ne=nt<200,$e=Math.min(1,Math.max(.7,nt/(Re?64:Cr))),ft=Math.min(1,Math.max(.7,nt/Se));return k.jsxs("div",{style:{position:"absolute",inset:0},children:[k.jsx("canvas",{ref:f,width:t,height:n,style:{display:"block",cursor:z==="rect"?(V.current,"crosshair"):g.current?"grabbing":"grab"},onMouseDown:Q=>{if(z==="rect"&&h){xe(Q);return}Ce(Q)},onMouseMove:At,onMouseUp:Q=>{if(V.current){qe(Q);return}dt()},onMouseLeave:ht,onClick:wt}),k.jsxs("div",{style:{position:"absolute",right:kt,bottom:pe?void 0:kt,top:pe?kt:void 0,display:"flex",flexDirection:Re?"row":"column",alignItems:"center",gap:6,padding:6,background:"rgba(20, 22, 26, 0.85)",border:"1px solid rgba(255,255,255,0.14)",borderRadius:10,boxShadow:"0 10px 26px rgba(0,0,0,0.45)",pointerEvents:"auto",transform:$e===1?void 0:`scale(${$e})`,transformOrigin:pe?"top right":"bottom right",maxWidth:`calc(100% - ${kt*2}px)`},onMouseDown:Q=>Q.stopPropagation(),children:[k.jsx("button",{onClick:()=>{const Q=z==="rect"?"none":"rect";V.current=null,T(!1),P(Q)},style:{width:34,height:34,borderRadius:8,border:z==="rect"?"1px solid rgba(79, 193, 255, 0.9)":"1px solid rgba(255,255,255,0.18)",background:z==="rect"?"rgba(14, 99, 156, 0.7)":"rgba(255,255,255,0.06)",color:"#e6e6e6",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:0},title:z==="rect"?"Rectangle tool (active)":"Rectangle tool",children:k.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:k.jsx("rect",{x:"5",y:"7",width:"14",height:"10",rx:"1"})})}),k.jsx("button",{onClick:()=>{V.current=null,T(!1),P("none")},style:{width:34,height:34,borderRadius:8,border:"1px solid rgba(255,255,255,0.18)",background:z==="none"?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.06)",color:"#e6e6e6",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:0},title:"Drag/Pan",children:"↔"})]}),(R==null?void 0:R.open)&&R.layers.length>=2&&k.jsxs("div",{style:{position:"absolute",left:Math.min(t-220,R.anchorScreen.x+12),top:Math.min(n-260,R.anchorScreen.y-12),width:210,padding:8,background:"rgba(10, 12, 16, 0.94)",border:"1px solid rgba(255,255,255,0.14)",borderRadius:10,boxShadow:"0 10px 30px rgba(0,0,0,0.55)",color:"#e6e6e6",fontSize:12},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[k.jsx("div",{style:{fontWeight:700},children:"Stack"}),k.jsx("button",{onClick:()=>F(null),style:{...ml,padding:"2px 6px",borderRadius:8},title:"Close",children:"✕"})]}),k.jsxs("div",{style:{color:"#9aa7b2",marginTop:4},children:["World: ",R.world.x.toFixed(0),",",R.world.y.toFixed(0)]}),k.jsx("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:6,maxHeight:220,overflow:"auto",paddingRight:2},children:R.layers.map((Q,W)=>{var le;return k.jsx("button",{onClick:ye=>{c==null||c(Q.id,{metaKey:ye.metaKey,ctrlKey:ye.ctrlKey}),F(null)},style:{textAlign:"left",width:"100%",background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.10)",borderRadius:10,padding:"8px 10px",cursor:"pointer",color:"#e6e6e6",position:"relative"},title:"Select layer",children:k.jsxs("div",{style:{fontWeight:650},children:[(le=Q.name)!=null&&le.trim()?Q.name:`Layer ${Q.id}`," ",k.jsxs("span",{style:{color:"#9aa7b2",fontWeight:500},children:["z=",Q.zIndex]}),W===0&&k.jsx("span",{style:{marginLeft:6,color:"#66d9ef",fontWeight:650},children:"top"})]})},Q.id)})})]}),k.jsxs("div",{style:{position:"absolute",top:10,left:10,display:"flex",gap:6,padding:6,background:"rgba(15, 18, 24, 0.85)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,backdropFilter:"blur(6px)",fontSize:12,color:"#cfcfcf"},children:[k.jsx("button",{onClick:()=>cr(1.15),style:ml,title:"Zoom in",children:"+"}),k.jsx("button",{onClick:()=>cr(1/1.15),style:ml,title:"Zoom out",children:"−"}),k.jsx("button",{onClick:Ft,style:ml,title:"Reset view",children:"Reset"})]}),k.jsxs("div",{style:{position:"absolute",left:kt,bottom:ne?void 0:kt,top:ne?kt:void 0,padding:"6px 8px",background:"rgba(15, 18, 24, 0.75)",border:"1px solid rgba(255,255,255,0.10)",borderRadius:8,backdropFilter:"blur(6px)",fontSize:12,color:"#cfcfcf",transform:ft===1?void 0:`scale(${ft})`,transformOrigin:ne?"top left":"bottom left",maxWidth:`calc(100% - ${kt*2}px)`,overflow:"hidden",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{color:"#9aa7b2"},children:"Zoom:"})," ",p.toFixed(3),"x"," ",k.jsx("span",{style:{color:"#9aa7b2"},children:"| Offset:"})," (",S.x.toFixed(0),","," ",S.y.toFixed(0),")",E&&k.jsxs(k.Fragment,{children:[k.jsx("span",{style:{color:"#9aa7b2"},children:"| Mouse:"})," (",E.world.x.toFixed(0),",",E.world.y.toFixed(0),")"]})]}),tt&&k.jsxs("div",{style:{position:"absolute",left:Math.min(t-260,tt.screen.x+12),top:Math.min(n-80,tt.screen.y+12),width:240,padding:"8px 10px",background:"rgba(10, 12, 16, 0.92)",border:"1px solid rgba(255,255,255,0.14)",borderRadius:8,fontSize:12,color:"#e6e6e6",pointerEvents:"none"},children:[k.jsx("div",{style:{fontWeight:600,marginBottom:4},children:tt.kind==="layer"?`Layer ${tt.id}`:`Display ${tt.id}`}),tt.kind==="layer"&&typeof tt.zIndex=="number"&&k.jsxs("div",{style:{color:"#b7c0c8"},children:["zIndex: ",tt.zIndex]}),k.jsxs("div",{style:{color:"#b7c0c8"},children:["World: ",tt.world.x.toFixed(0),",",tt.world.y.toFixed(0)]}),k.jsxs("div",{style:{color:"#b7c0c8"},children:["Screen: ",tt.screen.x.toFixed(0),",",tt.screen.y.toFixed(0)]})]})]})}const ml={background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.14)",color:"#ddd",borderRadius:6,padding:"4px 8px",cursor:"pointer",lineHeight:1};var zC={},Zf={},qf={},Co={};Object.defineProperty(Co,"__esModule",{value:!0});Co.Direction=void 0;var ny;(function(r){r.Right="to right",r.Left="to left",r.Down="to bottom",r.Up="to top"})(ny||(Co.Direction=ny={}));(function(r){var e=Nr&&Nr.__spreadArray||function(P,D,L){if(L||arguments.length===2)for(var V=0,X=D.length,T;V<X;V++)(T||!(V in D))&&(T||(T=Array.prototype.slice.call(D,0,V)),T[V]=D[V]);return P.concat(T||Array.prototype.slice.call(D))};Object.defineProperty(r,"__esModule",{value:!0}),r.isIOS=r.useThumbOverlap=r.assertUnreachable=r.voidFn=r.getTrackBackground=r.replaceAt=r.schd=r.translate=r.getClosestThumbIndex=r.translateThumbs=r.getPaddingAndBorder=r.getMargin=r.checkInitialOverlap=r.checkValuesAgainstBoundaries=r.checkBoundaries=r.isVertical=r.relativeValue=r.normalizeValue=r.isStepDivisible=r.isTouchEvent=r.getStepDecimals=void 0;var t=N,n=Co,i=function(P){var D=P.toString().split(".")[1];return D?D.length:0};r.getStepDecimals=i;function s(P){return P.touches&&P.touches.length||P.changedTouches&&P.changedTouches.length}r.isTouchEvent=s;function o(P,D,L){var V=(D-P)/L,X=8,T=Number(V.toFixed(X));return parseInt(T.toString(),10)===T}r.isStepDivisible=o;function a(P,D,L,V,X,T,_){var j=1e11;if(P=Math.round(P*j)/j,!T){var G=_[D-1],ee=_[D+1];if(G&&G>P)return G;if(ee&&ee<P)return ee}if(P>V)return V;if(P<L)return L;var q=Math.floor(P*j-L*j)%Math.floor(X*j),K=Math.floor(P*j-Math.abs(q)),oe=q===0?P:K/j,ve=Math.abs(q/j)<X/2?oe:oe+X,ge=(0,r.getStepDecimals)(X);return parseFloat(ve.toFixed(ge))}r.normalizeValue=a;function l(P,D,L){return(P-D)/(L-D)}r.relativeValue=l;function u(P){return P===n.Direction.Up||P===n.Direction.Down}r.isVertical=u;function c(P,D,L){if(D>=L)throw new RangeError("min (".concat(D,") is equal/bigger than max (").concat(L,")"));if(P<D)throw new RangeError("value (".concat(P,") is smaller than min (").concat(D,")"));if(P>L)throw new RangeError("value (".concat(P,") is bigger than max (").concat(L,")"))}r.checkBoundaries=c;function d(P,D,L){return P<D?D:P>L?L:P}r.checkValuesAgainstBoundaries=d;function h(P){if(!(P.length<2)&&!P.slice(1).every(function(D,L){return P[L]<=D}))throw new RangeError("values={[".concat(P,"]} needs to be sorted when allowOverlap={false}"))}r.checkInitialOverlap=h;function f(P){var D=window.getComputedStyle(P);return{top:parseInt(D["margin-top"],10),bottom:parseInt(D["margin-bottom"],10),left:parseInt(D["margin-left"],10),right:parseInt(D["margin-right"],10)}}r.getMargin=f;function p(P){var D=window.getComputedStyle(P);return{top:parseInt(D["padding-top"],10)+parseInt(D["border-top-width"],10),bottom:parseInt(D["padding-bottom"],10)+parseInt(D["border-bottom-width"],10),left:parseInt(D["padding-left"],10)+parseInt(D["border-left-width"],10),right:parseInt(D["padding-right"],10)+parseInt(D["border-right-width"],10)}}r.getPaddingAndBorder=p;function m(P,D,L){var V=L?-1:1;P.forEach(function(X,T){return w(X,V*D[T].x,D[T].y)})}r.translateThumbs=m;function S(P,D,L,V){for(var X=0,T=F(P[0],D,L,V),_=1;_<P.length;_++){var j=F(P[_],D,L,V);j<T&&(T=j,X=_)}return X}r.getClosestThumbIndex=S;function w(P,D,L){P.style.transform="translate(".concat(D,"px, ").concat(L,"px)")}r.translate=w;var g=function(P){var D=[],L=null,V=function(){for(var X=[],T=0;T<arguments.length;T++)X[T]=arguments[T];D=X,!L&&(L=requestAnimationFrame(function(){L=null,P.apply(void 0,D)}))};return V};r.schd=g;function y(P,D,L){var V=P.slice(0);return V[D]=L,V}r.replaceAt=y;function C(P){var D=P.values,L=P.colors,V=P.min,X=P.max,T=P.direction,_=T===void 0?n.Direction.Right:T,j=P.rtl,G=j===void 0?!1:j;G&&_===n.Direction.Right?_=n.Direction.Left:G&&n.Direction.Left&&(_=n.Direction.Right);var ee=D.slice(0).sort(function(K,oe){return K-oe}).map(function(K){return(K-V)/(X-V)*100}),q=ee.reduce(function(K,oe,ve){return"".concat(K,", ").concat(L[ve]," ").concat(oe,"%, ").concat(L[ve+1]," ").concat(oe,"%")},"");return"linear-gradient(".concat(_,", ").concat(L[0]," 0%").concat(q,", ").concat(L[L.length-1]," 100%)")}r.getTrackBackground=C;function x(){}r.voidFn=x;function I(P){throw new Error("Didn't expect to get here")}r.assertUnreachable=I;var E=function(P,D,L,V,X){X===void 0&&(X=function(_){return _});var T=Math.ceil(e([P],Array.from(P.children),!0).reduce(function(_,j){var G=Math.ceil(j.getBoundingClientRect().width);if(j.innerText&&j.innerText.includes(L)&&j.childElementCount===0){var ee=j.cloneNode(!0);ee.innerHTML=X(D.toFixed(V)),ee.style.visibility="hidden",document.body.appendChild(ee),G=Math.ceil(ee.getBoundingClientRect().width),document.body.removeChild(ee)}return G>_?G:_},P.getBoundingClientRect().width));return T},A=function(P,D,L,V,X,T,_){_===void 0&&(_=function(ee){return ee});var j=[],G=function(ee){var q=E(L[ee],V[ee],X,T,_),K=D[ee].x;D.forEach(function(oe,ve){var ge=oe.x,Ce=E(L[ve],V[ve],X,T,_);ee!==ve&&(K>=ge&&K<=ge+Ce||K+q>=ge&&K+q<=ge+Ce)&&(j.includes(ve)||(j.push(ee),j.push(ve),j=e(e([],j,!0),[ee,ve],!1),G(ve)))})};return G(P),Array.from(new Set(j.sort()))},R=function(P,D,L,V,X,T){V===void 0&&(V=.1),X===void 0&&(X=" - "),T===void 0&&(T=function(ve){return ve});var _=(0,r.getStepDecimals)(V),j=(0,t.useState)({}),G=j[0],ee=j[1],q=(0,t.useState)(T(D[L].toFixed(_))),K=q[0],oe=q[1];return(0,t.useEffect)(function(){if(P){var ve=P.getThumbs();if(ve.length<1)return;var ge={},Ce=P.getOffsets(),dt=A(L,Ce,ve,D,X,_,T),ht=T(D[L].toFixed(_));if(dt.length){var xe=dt.reduce(function(wt,Ft,cr,tt){return wt.length?e(e([],wt,!0),[Ce[tt[cr]].x],!1):[Ce[tt[cr]].x]},[]);if(Math.min.apply(Math,xe)===Ce[L].x){var et=[];dt.forEach(function(wt){et.push(D[wt].toFixed(_))}),ht=Array.from(new Set(et.sort(function(wt,Ft){return parseFloat(wt)-parseFloat(Ft)}))).map(T).join(X);var Ke=Math.min.apply(Math,xe),qe=Math.max.apply(Math,xe),At=ve[dt[xe.indexOf(qe)]].getBoundingClientRect().width;ge.left="".concat(Math.abs(Ke-(qe+At))/2,"px"),ge.transform="translate(-50%, 0)"}else ge.visibility="hidden"}oe(ht),ee(ge)}},[P,D]),[K,G]};r.useThumbOverlap=R;function F(P,D,L,V){var X=P.getBoundingClientRect(),T=X.left,_=X.top,j=X.width,G=X.height;return u(V)?Math.abs(L-(_+G/2)):Math.abs(D-(T+j/2))}var z=function(){var P,D=((P=navigator.userAgentData)===null||P===void 0?void 0:P.platform)||navigator.platform;return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(D)||navigator.userAgent.includes("Mac")&&"ontouchend"in document};r.isIOS=z})(qf);var gU=Nr&&Nr.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),mU=Nr&&Nr.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),yU=Nr&&Nr.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),vU=Nr&&Nr.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&mU(e,r,t);return yU(e,r),e},iy=Nr&&Nr.__spreadArray||function(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return r.concat(s||Array.prototype.slice.call(e))};Object.defineProperty(Zf,"__esModule",{value:!0});var yl=vU(N),ze=qf,_t=Co,wU=["ArrowRight","ArrowUp","k","PageUp"],CU=["ArrowLeft","ArrowDown","j","PageDown"],bU=function(r){gU(e,r);function e(t){var n=r.call(this,t)||this;if(n.trackRef=yl.createRef(),n.thumbRefs=[],n.state={draggedTrackPos:[-1,-1],draggedThumbIndex:-1,thumbZIndexes:new Array(n.props.values.length).fill(0).map(function(i,s){return s}),isChanged:!1,markOffsets:[]},n.getOffsets=function(){var i=n.props,s=i.direction,o=i.values,a=i.min,l=i.max,u=n.trackRef.current;if(!u)return console.warn("No track element found."),[];var c=u.getBoundingClientRect(),d=(0,ze.getPaddingAndBorder)(u);return n.getThumbs().map(function(h,f){var p={x:0,y:0},m=h.getBoundingClientRect(),S=(0,ze.getMargin)(h);switch(s){case _t.Direction.Right:return p.x=(S.left+d.left)*-1,p.y=((m.height-c.height)/2+d.top)*-1,p.x+=c.width*(0,ze.relativeValue)(o[f],a,l)-m.width/2,p;case _t.Direction.Left:return p.x=(S.right+d.right)*-1,p.y=((m.height-c.height)/2+d.top)*-1,p.x+=c.width-c.width*(0,ze.relativeValue)(o[f],a,l)-m.width/2,p;case _t.Direction.Up:return p.x=((m.width-c.width)/2+S.left+d.left)*-1,p.y=-d.left,p.y+=c.height-c.height*(0,ze.relativeValue)(o[f],a,l)-m.height/2,p;case _t.Direction.Down:return p.x=((m.width-c.width)/2+S.left+d.left)*-1,p.y=-d.left,p.y+=c.height*(0,ze.relativeValue)(o[f],a,l)-m.height/2,p;default:return(0,ze.assertUnreachable)(s)}})},n.getThumbs=function(){return n.trackRef&&n.trackRef.current?Array.from(n.trackRef.current.children).filter(function(i){return i.hasAttribute("aria-valuenow")}):(console.warn("No thumbs found in the track container. Did you forget to pass & spread the `props` param in renderTrack?"),[])},n.getTargetIndex=function(i){return n.getThumbs().findIndex(function(s){return s===i.target||s.contains(i.target)})},n.addTouchEvents=function(i){document.addEventListener("touchmove",n.schdOnTouchMove,{passive:!1}),document.addEventListener("touchend",n.schdOnEnd,{passive:!1}),document.addEventListener("touchcancel",n.schdOnEnd,{passive:!1})},n.addMouseEvents=function(i){document.addEventListener("mousemove",n.schdOnMouseMove),document.addEventListener("mouseup",n.schdOnEnd)},n.onMouseDownTrack=function(i){var s;if(!(i.button!==0||(0,ze.isIOS)()))if(i.persist(),i.preventDefault(),n.addMouseEvents(i.nativeEvent),n.props.values.length>1&&n.props.draggableTrack){if(n.thumbRefs.some(function(a){var l;return(l=a.current)===null||l===void 0?void 0:l.contains(i.target)}))return;n.setState({draggedTrackPos:[i.clientX,i.clientY]},function(){return n.onMove(i.clientX,i.clientY)})}else{var o=(0,ze.getClosestThumbIndex)(n.thumbRefs.map(function(a){return a.current}),i.clientX,i.clientY,n.props.direction);(s=n.thumbRefs[o].current)===null||s===void 0||s.focus(),n.setState({draggedThumbIndex:o},function(){return n.onMove(i.clientX,i.clientY)})}},n.onResize=function(){(0,ze.translateThumbs)(n.getThumbs(),n.getOffsets(),n.props.rtl),n.calculateMarkOffsets()},n.onTouchStartTrack=function(i){var s;if(i.persist(),n.addTouchEvents(i.nativeEvent),n.props.values.length>1&&n.props.draggableTrack){if(n.thumbRefs.some(function(a){var l;return(l=a.current)===null||l===void 0?void 0:l.contains(i.target)}))return;n.setState({draggedTrackPos:[i.touches[0].clientX,i.touches[0].clientY]},function(){return n.onMove(i.touches[0].clientX,i.touches[0].clientY)})}else{var o=(0,ze.getClosestThumbIndex)(n.thumbRefs.map(function(a){return a.current}),i.touches[0].clientX,i.touches[0].clientY,n.props.direction);(s=n.thumbRefs[o].current)===null||s===void 0||s.focus(),n.setState({draggedThumbIndex:o},function(){return n.onMove(i.touches[0].clientX,i.touches[0].clientY)})}},n.onMouseOrTouchStart=function(i){if(!n.props.disabled){var s=(0,ze.isTouchEvent)(i);if(!(!s&&i.button!==0)){var o=n.getTargetIndex(i);o!==-1&&(s?n.addTouchEvents(i):n.addMouseEvents(i),n.setState({draggedThumbIndex:o,thumbZIndexes:n.state.thumbZIndexes.map(function(a,l){return l===o?Math.max.apply(Math,n.state.thumbZIndexes):a<=n.state.thumbZIndexes[o]?a:a-1})}))}}},n.onMouseMove=function(i){i.preventDefault(),n.onMove(i.clientX,i.clientY)},n.onTouchMove=function(i){i.preventDefault(),n.onMove(i.touches[0].clientX,i.touches[0].clientY)},n.onKeyDown=function(i){var s=n.props,o=s.values,a=s.onChange,l=s.step,u=s.rtl,c=s.direction,d=n.state.isChanged,h=n.getTargetIndex(i.nativeEvent),f=u||c===_t.Direction.Left||c===_t.Direction.Down?-1:1;h!==-1&&(wU.includes(i.key)?(i.preventDefault(),n.setState({draggedThumbIndex:h,isChanged:!0}),a((0,ze.replaceAt)(o,h,n.normalizeValue(o[h]+f*(i.key==="PageUp"?l*10:l),h)))):CU.includes(i.key)?(i.preventDefault(),n.setState({draggedThumbIndex:h,isChanged:!0}),a((0,ze.replaceAt)(o,h,n.normalizeValue(o[h]-f*(i.key==="PageDown"?l*10:l),h)))):i.key==="Tab"?n.setState({draggedThumbIndex:-1},function(){d&&n.fireOnFinalChange()}):d&&n.fireOnFinalChange())},n.onKeyUp=function(i){var s=n.state.isChanged;n.setState({draggedThumbIndex:-1},function(){s&&n.fireOnFinalChange()})},n.onMove=function(i,s){var o=n.state,a=o.draggedThumbIndex,l=o.draggedTrackPos,u=n.props,c=u.direction,d=u.min,h=u.max,f=u.onChange,p=u.values,m=u.step,S=u.rtl;if(a===-1&&l[0]===-1&&l[1]===-1)return null;var w=n.trackRef.current;if(!w)return null;var g=w.getBoundingClientRect(),y=(0,ze.isVertical)(c)?g.height:g.width;if(l[0]!==-1&&l[1]!==-1){var C=i-l[0],x=s-l[1],I=0;switch(c){case _t.Direction.Right:case _t.Direction.Left:I=C/y*(h-d);break;case _t.Direction.Down:case _t.Direction.Up:I=x/y*(h-d);break;default:(0,ze.assertUnreachable)(c)}if(S&&(I*=-1),Math.abs(I)>=m/2){for(var E=0;E<n.thumbRefs.length;E++){if(p[E]===h&&Math.sign(I)===1||p[E]===d&&Math.sign(I)===-1)return;var A=p[E]+I;A>h?I=h-p[E]:A<d&&(I=d-p[E])}for(var R=p.slice(0),E=0;E<n.thumbRefs.length;E++)R=(0,ze.replaceAt)(R,E,n.normalizeValue(p[E]+I,E));n.setState({draggedTrackPos:[i,s]}),f(R)}}else{var F=0;switch(c){case _t.Direction.Right:F=(i-g.left)/y*(h-d)+d;break;case _t.Direction.Left:F=(y-(i-g.left))/y*(h-d)+d;break;case _t.Direction.Down:F=(s-g.top)/y*(h-d)+d;break;case _t.Direction.Up:F=(y-(s-g.top))/y*(h-d)+d;break;default:(0,ze.assertUnreachable)(c)}S&&(F=h+d-F),Math.abs(p[a]-F)>=m/2&&f((0,ze.replaceAt)(p,a,n.normalizeValue(F,a)))}},n.normalizeValue=function(i,s){var o=n.props,a=o.min,l=o.max,u=o.step,c=o.allowOverlap,d=o.values;return(0,ze.normalizeValue)(i,s,a,l,u,c,d)},n.onEnd=function(i){if(i.preventDefault(),document.removeEventListener("mousemove",n.schdOnMouseMove),document.removeEventListener("touchmove",n.schdOnTouchMove),document.removeEventListener("mouseup",n.schdOnEnd),document.removeEventListener("touchend",n.schdOnEnd),document.removeEventListener("touchcancel",n.schdOnEnd),n.state.draggedThumbIndex===-1&&n.state.draggedTrackPos[0]===-1&&n.state.draggedTrackPos[1]===-1)return null;n.setState({draggedThumbIndex:-1,draggedTrackPos:[-1,-1]},function(){n.fireOnFinalChange()})},n.fireOnFinalChange=function(){n.setState({isChanged:!1});var i=n.props,s=i.onFinalChange,o=i.values;s&&s(o)},n.updateMarkRefs=function(i){if(!i.renderMark){n.numOfMarks=void 0,n.markRefs=void 0;return}n.numOfMarks=(i.max-i.min)/n.props.step,n.markRefs=[];for(var s=0;s<n.numOfMarks+1;s++)n.markRefs[s]=yl.createRef()},n.calculateMarkOffsets=function(){if(!(!n.props.renderMark||!n.trackRef||!n.numOfMarks||!n.markRefs||n.trackRef.current===null)){for(var i=window.getComputedStyle(n.trackRef.current),s=parseInt(i.width,10),o=parseInt(i.height,10),a=parseInt(i.paddingLeft,10),l=parseInt(i.paddingTop,10),u=[],c=0;c<n.numOfMarks+1;c++){var d=9999,h=9999;if(n.markRefs[c].current){var f=n.markRefs[c].current.getBoundingClientRect();d=f.height,h=f.width}n.props.direction===_t.Direction.Left||n.props.direction===_t.Direction.Right?u.push([Math.round(s/n.numOfMarks*c+a-h/2),-Math.round((d-o)/2)]):u.push([Math.round(o/n.numOfMarks*c+l-d/2),-Math.round((h-s)/2)])}n.setState({markOffsets:u})}},t.step===0)throw new Error('"step" property should be a positive number');return n.schdOnMouseMove=(0,ze.schd)(n.onMouseMove),n.schdOnTouchMove=(0,ze.schd)(n.onTouchMove),n.schdOnEnd=(0,ze.schd)(n.onEnd),n.thumbRefs=t.values.map(function(){return yl.createRef()}),n.updateMarkRefs(t),n}return e.prototype.componentDidMount=function(){var t=this,n=this.props,i=n.values,s=n.min,o=n.step;this.resizeObserver=window.ResizeObserver?new window.ResizeObserver(this.onResize):{observe:function(){return window.addEventListener("resize",t.onResize)},unobserve:function(){return window.removeEventListener("resize",t.onResize)}},document.addEventListener("touchstart",this.onMouseOrTouchStart,{passive:!1}),document.addEventListener("mousedown",this.onMouseOrTouchStart,{passive:!1}),!this.props.allowOverlap&&(0,ze.checkInitialOverlap)(this.props.values),this.props.values.forEach(function(a){return(0,ze.checkBoundaries)(a,t.props.min,t.props.max)}),this.resizeObserver.observe(this.trackRef.current),(0,ze.translateThumbs)(this.getThumbs(),this.getOffsets(),this.props.rtl),this.calculateMarkOffsets(),i.forEach(function(a){(0,ze.isStepDivisible)(s,a,o)||console.warn("The `values` property is in conflict with the current `step`, `min`, and `max` properties. Please provide values that are accessible using the min, max, and step values.")})},e.prototype.componentDidUpdate=function(t,n){var i=this.props,s=i.max,o=i.min,a=i.step,l=i.values,u=i.rtl;(t.max!==s||t.min!==o||t.step!==a)&&this.updateMarkRefs(this.props),(0,ze.translateThumbs)(this.getThumbs(),this.getOffsets(),u),(t.max!==s||t.min!==o||t.step!==a||n.markOffsets.length!==this.state.markOffsets.length)&&(this.calculateMarkOffsets(),l.forEach(function(c){(0,ze.isStepDivisible)(o,c,a)||console.warn("The `values` property is in conflict with the current `step`, `min`, and `max` properties. Please provide values that are accessible using the min, max, and step values.")}))},e.prototype.componentWillUnmount=function(){var t={passive:!1};document.removeEventListener("mousedown",this.onMouseOrTouchStart,t),document.removeEventListener("mousemove",this.schdOnMouseMove),document.removeEventListener("touchmove",this.schdOnTouchMove),document.removeEventListener("touchstart",this.onMouseOrTouchStart),document.removeEventListener("mouseup",this.schdOnEnd),document.removeEventListener("touchend",this.schdOnEnd),this.resizeObserver.unobserve(this.trackRef.current)},e.prototype.render=function(){var t=this,n=this.props,i=n.label,s=n.labelledBy,o=n.renderTrack,a=n.renderThumb,l=n.renderMark,u=l===void 0?function(){return null}:l,c=n.values,d=n.min,h=n.max,f=n.allowOverlap,p=n.disabled,m=this.state,S=m.draggedThumbIndex,w=m.thumbZIndexes,g=m.markOffsets;return o({props:{style:{transform:"scale(1)",cursor:S>-1?"grabbing":this.props.draggableTrack?(0,ze.isVertical)(this.props.direction)?"ns-resize":"ew-resize":c.length===1&&!p?"pointer":"inherit"},onMouseDown:p?ze.voidFn:this.onMouseDownTrack,onTouchStart:p?ze.voidFn:this.onTouchStartTrack,ref:this.trackRef},isDragged:this.state.draggedThumbIndex>-1,disabled:p,children:iy(iy([],g.map(function(y,C,x){return u({props:{style:t.props.direction===_t.Direction.Left||t.props.direction===_t.Direction.Right?{position:"absolute",left:"".concat(y[0],"px"),marginTop:"".concat(y[1],"px")}:{position:"absolute",top:"".concat(y[0],"px"),marginLeft:"".concat(y[1],"px")},key:"mark".concat(C),ref:t.markRefs[C]},index:C})}),!0),c.map(function(y,C){var x=t.state.draggedThumbIndex===C;return a({index:C,value:y,isDragged:x,props:{style:{position:"absolute",zIndex:w[C],cursor:p?"inherit":x?"grabbing":"grab",userSelect:"none",touchAction:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none"},key:C,tabIndex:p?void 0:0,"aria-valuemax":f?h:c[C+1]||h,"aria-valuemin":f?d:c[C-1]||d,"aria-valuenow":y,draggable:!1,ref:t.thumbRefs[C],"aria-label":i,"aria-labelledby":s,role:"slider",onKeyDown:p?ze.voidFn:t.onKeyDown,onKeyUp:p?ze.voidFn:t.onKeyUp}})}),!0)})},e.defaultProps={label:"Accessibility label",labelledBy:null,step:1,direction:_t.Direction.Right,rtl:!1,disabled:!1,allowOverlap:!1,draggableTrack:!1,min:0,max:100},e}(yl.Component);Zf.default=bU;(function(r){var e=Nr&&Nr.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(r,"__esModule",{value:!0}),r.checkValuesAgainstBoundaries=r.relativeValue=r.useThumbOverlap=r.Direction=r.getTrackBackground=r.Range=void 0;var t=e(Zf);r.Range=t.default;var n=qf;Object.defineProperty(r,"getTrackBackground",{enumerable:!0,get:function(){return n.getTrackBackground}}),Object.defineProperty(r,"useThumbOverlap",{enumerable:!0,get:function(){return n.useThumbOverlap}}),Object.defineProperty(r,"relativeValue",{enumerable:!0,get:function(){return n.relativeValue}}),Object.defineProperty(r,"checkValuesAgainstBoundaries",{enumerable:!0,get:function(){return n.checkValuesAgainstBoundaries}});var i=Co;Object.defineProperty(r,"Direction",{enumerable:!0,get:function(){return i.Direction}})})(zC);const Yr={fontSize:12,color:"#9aa7b2"},sy={background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:10};function Zo(r,e,t){return Math.max(e,Math.min(t,r))}function oy(r,e){const t=r.replace("#",""),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),s=parseInt(t.slice(4,6),16);return`rgba(${n},${i},${s},${Zo(e,0,1)})`}function SU(r){const e=["#66d9ef","#a6e22e","#fd971f","#e6db74","#f92672","#ae81ff","#2aa198"];return e[Math.abs(r)%e.length]}function OC(r,e){const t=(r??"").trim();return t.length?t:e}function xU(r,e){return r.map(t=>{const n=e.get(t);return n?{id:t,name:OC(n.name,`Layer ${t}`),z:n.z,layer:{id:n.id,name:n.name,z:n.z,origin:n.origin,width:n.width,height:n.height}}:null}).filter(Boolean)}function IU({user:r,selectedDisplayId:e,selectedLayerIds:t,onSelectLayer:n,onSelectDisplay:i,setVisibleLayers:s}){var C;const o=N.useMemo(()=>r.displays.filter(x=>x.id!==255),[r.displays]),[a,l]=N.useState(null),[u,c]=N.useState([0,0]),d=N.useRef(null),h=N.useMemo(()=>{var E,A,R;const x=(E=o.find(F=>F.id===e))==null?void 0:E.id;if(x!=null)return x;const I=(A=o.find(F=>F.id===a))==null?void 0:A.id;return I??((R=o[0])==null?void 0:R.id)??null},[a,o,e]),f=N.useMemo(()=>h==null?null:o.find(x=>x.id===h)??null,[o,h]),p=N.useMemo(()=>{var I,E;if(h==null)return null;const x=(E=(I=r.displayComposite)==null?void 0:I[h])==null?void 0:E.layerIdsTopToBottom;return x&&x.length?x:null},[h,r.displayComposite]),m=N.useMemo(()=>{const x=new Map;for(const I of r.layers)x.set(I.id,{id:I.id,name:I.name,z:I.z,origin:I.origin,width:I.width,height:I.height});return x},[r.layers]),S=N.useMemo(()=>{var z,P;if(h==null)return[];const x=(P=(z=r.displayComposite)==null?void 0:z[h])==null?void 0:P.layerIdsTopToBottom;if(x&&x.length)return xU(x,m);if(!f)return[];const I=f.origin.x,E=f.origin.y,A=I+f.size.x,R=E+f.size.y,F=[];for(const D of r.layers){const L=D.origin.x,V=D.origin.y,X=D.origin.x+D.width,T=D.origin.y+D.height;A<=L||I>=X||R<=V||E>=T||F.push({id:D.id,name:OC(D.name,`Layer ${D.id}`),z:D.z,layer:D})}return F.sort((D,L)=>L.z-D.z),F},[h,f,m,r.displayComposite,r.layers]);N.useEffect(()=>{const x=S.length;if(!x){c([0,0]);return}const I=Math.max(0,x-1);c([0,I])},[h,S.length]);const w=N.useMemo(()=>{const x=Math.max(0,S.length-1);let I=Zo(u[0],0,x),E=Zo(u[1],0,x);return I>E&&([I,E]=[E,I]),[I,E]},[S.length,u]),g=N.useMemo(()=>{if(!S.length)return S;const[x,I]=w;return S.slice(x,I+1)},[S,w]);N.useEffect(()=>{if(!s)return;if(!S.length){s(null);return}const[x,I]=w;if(x===0&&I===S.length-1){s(null);return}s(g.map(A=>A.id))},[S.length,w,s,g]);const y=N.useMemo(()=>{if(!f)return null;const x=g;if(!S.length)return{visible:[],minY:f.origin.y,maxY:f.origin.y+f.size.y,range:[0,0]};const[I,E]=w,A=x;let R=f.origin.y,F=f.origin.y+f.size.y;for(const z of A){const P=z.layer;P&&(R=Math.min(R,P.origin.y),F=Math.max(F,P.origin.y+P.height))}return{visible:A,minY:R,maxY:F,range:[I,E]}},[f,S.length,w,g]);return N.useEffect(()=>{const x=d.current;if(!x||!f||!y)return;const I=x.getContext("2d");if(!I)return;const E=window.devicePixelRatio||1,A=x.clientWidth,R=x.clientHeight,F=Math.max(1,Math.floor(A*E)),z=Math.max(1,Math.floor(R*E));(x.width!==F||x.height!==z)&&(x.width=F,x.height=z),I.setTransform(E,0,0,E,0,0),I.clearRect(0,0,A,R);const P=14,D=Math.max(1,A-P*2),L=Math.max(1,R-P*2),V=y.minY,X=y.maxY,T=Math.max(1,X-V),_=f.origin.x,j=f.origin.x+f.size.x,G=Math.max(1,j-_),ee=xe=>P+(xe-_)/G*D,q=xe=>xe/G*D,K=xe=>P+(xe-V)/T*L,oe=xe=>xe/T*L;I.fillStyle="rgba(0,0,0,0.20)",I.fillRect(0,0,A,R);const ve=ee(f.origin.x),ge=K(f.origin.y),Ce=q(f.size.x),dt=oe(f.size.y);I.strokeStyle="rgba(255,120,120,0.75)",I.lineWidth=1,I.strokeRect(ve,ge,Ce,dt),I.fillStyle="rgba(255,120,120,0.08)",I.fillRect(ve,ge,Ce,dt);const ht=y.visible;for(let xe=ht.length-1;xe>=0;xe--){const et=ht[xe],Ke=et.layer;if(!Ke)continue;const qe=ee(Ke.origin.x),At=K(Ke.origin.y),wt=Math.max(2,q(Ke.width)),Ft=Math.max(2,oe(Ke.height)),cr=SU(et.id),tt=t.includes(et.id);I.fillStyle=oy(cr,1),I.strokeStyle=oy(cr,tt?.95:.55),I.lineWidth=tt?2:1,I.fillRect(qe,At,wt,Ft),I.strokeRect(qe,At,wt,Ft),I.save(),I.beginPath(),I.rect(qe,At,wt,Ft),I.clip(),I.fillStyle="rgba(15,15,15,0.95)",I.font="12px Segoe UI, sans-serif";const kt=[`${et.name}`,`id ${et.id} • z ${et.z}`,`pos ${Ke.origin.x},${Ke.origin.y}`,`size ${Ke.width}×${Ke.height}`],nt=14;let Cr=At+16;const Se=qe+8;for(let Re=0;Re<kt.length&&!(Cr>At+Ft-4);Re++){const pe=kt[Re];I.fillText(pe,Se,Cr),Cr+=nt}I.restore()}ht.length===0&&(I.fillStyle="rgba(154,167,178,0.9)",I.font="12px Segoe UI, sans-serif",I.fillText("No layers in this range",P+8,P+18))},[f,t,y]),k.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",minHeight:0},children:[k.jsxs("div",{style:{padding:"10px 12px",borderBottom:"1px solid #2f2f2f",background:"#1b1d22",display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[k.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#e6e6e6"},children:"Composer"}),k.jsx("div",{style:Yr,children:"Side stack per display (core-derived)"})]}),k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[k.jsx("div",{style:Yr,children:"Display"}),k.jsx("select",{value:h??"",onChange:x=>{const I=x.target.value===""?null:Number(x.target.value);l(I),I!=null&&i(I)},style:{height:28,background:"#252526",color:"#cccccc",border:"1px solid #3c3c3c",borderRadius:8,padding:"0 8px",fontSize:12,outline:"none"},children:o.map(x=>k.jsx("option",{value:x.id,children:x.id},x.id))})]})]}),k.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:12,background:"#14161a"},children:h==null?k.jsx("div",{style:{...Yr,padding:16},children:"No display."}):k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 280px",gap:12,alignItems:"start"},children:[k.jsxs("div",{style:{...sy,padding:12,display:"flex",flexDirection:"column",gap:10},children:[k.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between"},children:[k.jsx("div",{style:{fontWeight:700,color:"#e6e6e6"},children:"Cut-away"}),k.jsx("div",{style:Yr,children:f?`origin ${f.origin.x},${f.origin.y} • size ${f.size.x}×${f.size.y}`:""})]}),f&&k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[k.jsx("div",{style:Yr,children:"Z range"}),k.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{padding:"6px 0"},children:k.jsx(zC.Range,{step:1,min:0,max:Math.max(0,S.length-1),values:(()=>{const x=Math.max(0,S.length-1),I=x-w[1],E=x-w[0];return[I,E]})(),onChange:x=>{const I=Math.max(0,S.length-1),E=Math.round(x[0]??0),A=Math.round(x[1]??0),R=Zo(I-A,0,I),F=Zo(I-E,0,I);c([R,F])},renderTrack:({props:x,children:I})=>k.jsxs("div",{...x,style:{...x.style,height:6,width:"100%",borderRadius:999,background:"rgba(255,255,255,0.10)",border:"1px solid rgba(255,255,255,0.12)",position:"relative"},children:[(()=>{const E=Math.max(1,S.length-1),A=(E-w[1])/E,R=(E-w[0])/E,F=A*100,z=R*100;return k.jsx("div",{style:{position:"absolute",left:`${Math.min(F,z)}%`,width:`${Math.max(0,Math.abs(z-F))}%`,top:-1,bottom:-1,borderRadius:999,background:"linear-gradient(90deg, rgba(102,217,239,0.70), rgba(253,151,31,0.70))",boxShadow:"0 0 0 1px rgba(0,0,0,0.18) inset"}})})(),I]}),renderThumb:({props:x,index:I})=>k.jsx("div",{...x,style:{...x.style,height:14,width:14,borderRadius:999,background:I===0?"#66d9ef":"#fd971f",border:"1px solid rgba(0,0,0,0.35)",boxShadow:"0 2px 10px rgba(0,0,0,0.35)"},title:I===0?"Bottom handle":"Top handle"})})}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10},children:[k.jsx("div",{style:Yr,children:"BOTTOM"}),k.jsxs("div",{style:Yr,children:[S.length?`${w[0]} → ${w[1]}`:"—",S.length?` • ${g.length}/${S.length}`:""]}),k.jsx("div",{style:Yr,children:"TOP"})]})]})]}),k.jsx("div",{style:{position:"relative",flex:1,minHeight:260},children:k.jsx("canvas",{ref:d,style:{width:"100%",height:"100%",display:"block",borderRadius:10,background:"rgba(0,0,0,0.12)",cursor:"default",pointerEvents:"none",maxWidth:800,margin:"0 auto"}})})]}),k.jsxs("div",{style:{...sy,padding:12},children:[k.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between"},children:[k.jsx("div",{style:{fontWeight:700,color:"#e6e6e6"},children:"Side stack"}),k.jsxs("div",{style:Yr,children:[g.length," / ",S.length," layers"]})]}),p&&k.jsxs("div",{style:{...Yr,marginTop:6},children:["core order: top→bottom • [",p.join(", "),"]"]}),k.jsxs("div",{style:{marginTop:10,display:"flex",flexDirection:"column",gap:8},children:[S.map((x,I)=>{const E=t.includes(x.id),A=I>=w[0]&&I<=w[1];return k.jsx("button",{onClick:R=>{n(x.id,{metaKey:R.metaKey,ctrlKey:R.ctrlKey});const F=S.findIndex(z=>z.id===x.id);F>=0&&c([F,F])},style:{textAlign:"left",width:"100%",background:E?"rgba(102, 217, 239, 0.10)":A?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",border:E?"1px solid rgba(102, 217, 239, 0.65)":A?"1px solid rgba(255,255,255,0.10)":"1px solid rgba(255,255,255,0.06)",borderRadius:10,padding:"8px 10px",cursor:"pointer",color:A?"#e6e6e6":"rgba(230,230,230,0.55)"},title:"Select layer",children:k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10},children:[k.jsx("div",{style:{fontWeight:650,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.name}),k.jsxs("div",{style:{...Yr,whiteSpace:"nowrap"},children:["z=",x.z]})]})},x.id)}),S.length===0&&k.jsx("div",{style:{...Yr,padding:10},children:"No layers."}),((C=r.displayComposite)==null?void 0:C[h])==null&&k.jsx("div",{style:{...Yr,paddingTop:8},children:"Using fallback intersection (core composition not present)."})]})]})]})})]})}function kU({centerTab:r,setCenterTab:e,centerPanelRef:t,centerSize:n,worldLayers:i,worldDisplays:s,selectedLayerIds:o,setVisibleLayers:a,selectedDisplayId:l,focusRect:u,focusKey:c,onSelectLayer:d,onSelectDisplay:h,assetsSnapshot:f,primaryUser:p,isFloating:m,sortedTraffic:S,topTraffic:w,chartData:g,topKeys:y,keyToLabel:C,keyToColor:x,tickRate:I,hoveredTrafficKey:E,setHoveredTrafficKey:A}){return k.jsxs("div",{style:{background:"#1e1e1e",padding:0,minHeight:0,overflow:"hidden",display:"flex",flexDirection:"column"},children:[k.jsx("div",{style:{display:"flex",alignItems:"center",gap:2,padding:"4px 6px 0",background:"#252526",borderBottom:"1px solid #3c3c3c"},children:[{id:"grid",label:"World"},{id:"assets",label:"Assets"},{id:"network",label:"Network Details"},{id:"composer",label:"Composer"},{id:"renderer",label:"Renderer"}].map(R=>{const F=r===R.id;return k.jsx("button",{onClick:()=>e(R.id),style:{border:"1px solid #3c3c3c",borderBottom:F?"1px solid #1e1e1e":"1px solid #3c3c3c",background:F?"#1e1e1e":"#2d2d2d",color:"#cccccc",padding:"4px 10px",cursor:"pointer",fontSize:12,borderRadius:"4px 4px 0 0",marginBottom:"-1px"},children:R.label},R.id)})}),k.jsxs("div",{ref:t,style:{position:"relative",flex:1,minHeight:0,overflow:"hidden",background:"#1e1e1e"},children:[r==="grid"&&k.jsx(pU,{layers:i,displays:s,width:n.width,height:n.height,selectedLayerIds:o,selectedDisplayId:l,focusRect:u,focusKey:c,onSelectLayer:d,onSelectDisplay:h,onToolRectCommit:R=>{window.dispatchEvent(new window.CustomEvent("__utsp_debug_display255_rect",{detail:R}))}}),r==="composer"&&p&&k.jsx(IU,{user:p,selectedDisplayId:l,selectedLayerIds:o,onSelectLayer:d,onSelectDisplay:h,setVisibleLayers:a}),r==="composer"&&!p&&k.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"#9aa7b2",fontSize:13,background:"#111"},children:"No user in snapshot."}),r==="assets"&&k.jsx(mM,{assetsSnapshot:f}),r==="renderer"&&!m&&k.jsx("div",{style:{position:"absolute",inset:0,background:"#111"}}),r==="renderer"&&m&&k.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"#bbbbbb",fontSize:13,background:"#111",textAlign:"center",padding:24,lineHeight:1.5},children:'Press "Embed" on the floating renderer window to dock it here.'}),r==="network"&&k.jsx(fU,{sortedTraffic:S,topTraffic:w,chartData:g,topKeys:y,keyToLabel:C,keyToColor:x,tickRate:I,hoveredTrafficKey:E,setHoveredTrafficKey:A})]})]})}function EU(r){var d,h;const{enabled:e,snapshot:t,layers:n}=r,[i,s]=N.useState([]),o=N.useRef(null),a=N.useRef(0),l=N.useMemo(()=>{let f=0;for(let p=0;p<n.length;p++){const m=n[p].bytesPerSec1s;typeof m=="number"&&(f+=m)}return f},[n]);N.useEffect(()=>{e&&s(f=>f.length>0?f:[{time:"—",total:0}])},[e]),N.useEffect(()=>{var y,C;if(!e)return;const f=((y=t==null?void 0:t.tick)==null?void 0:y.tickRate)??((C=t==null?void 0:t.tick)==null?void 0:C.tps)??60,p=Math.max(1,Math.round(f*10)),m=performance.now?performance.now():Date.now(),S=Math.max(1,Math.round(1e3/f));if(m-a.current<S)return;a.current=m;const g={time:new Date().toLocaleTimeString("en-US",{hour12:!1,minute:"2-digit",second:"2-digit"}),total:l};s(x=>{if(o.current!==f)return o.current=f,[g];const I=x.length===0?[g]:[...x,g];return I.length>p?I.slice(I.length-p):I})},[e,l,t]);const u=o.current??((d=t==null?void 0:t.tick)==null?void 0:d.tickRate)??((h=t==null?void 0:t.tick)==null?void 0:h.tps)??60,c=N.useMemo(()=>{for(let f=0;f<i.length;f++)if(Number(i[f].total??0)>0)return!0;return!1},[i]);return{tickRate:u,data:i,hasData:c,latestBps:l}}function MU({primaryUser:r,tickRate:e,snapshot:t,assetsSnapshot:n}){const{totalBytesAll:i,totalBytesAssets:s,totalBytesNonAssets:o,totalBpsNonAssets:a}=N.useMemo(()=>{var y;const u=(r==null?void 0:r.layers)??[],c=(r==null?void 0:r.miscTraffic)??{},d=(r==null?void 0:r.displayTraffic)??{};let h=0,f=0;for(let C=0;C<u.length;C++){const x=u[C];typeof x.bytesTotal=="number"&&(h+=x.bytesTotal),typeof x.bytesPerSec1s=="number"&&(f+=x.bytesPerSec1s)}for(const C of Object.values(c))typeof(C==null?void 0:C.total)=="number"&&(h+=C.total),typeof(C==null?void 0:C.bytesPerSec1s)=="number"&&(f+=C.bytesPerSec1s);for(const C of Object.values(d))typeof(C==null?void 0:C.total)=="number"&&(h+=C.total),typeof(C==null?void 0:C.bytesPerSec1s)=="number"&&(f+=C.bytesPerSec1s);const p=Array.isArray(n==null?void 0:n.audio)?n.audio:[];let m=0;for(let C=0;C<p.length;C++){const x=(y=p[C])==null?void 0:y.originalSize;typeof x=="number"&&Number.isFinite(x)&&x>0&&(m+=x)}const S=Math.max(0,h),w=m>0?m:void 0;return{totalBytesAll:w!=null?w+S:S,totalBytesAssets:w,totalBytesNonAssets:S,totalBpsNonAssets:Math.max(0,f)}},[r,t,n]),{data:l}=EU({enabled:!0,snapshot:t,layers:(r==null?void 0:r.layers)??[]});return k.jsxs("div",{style:{borderLeft:"1px solid #3c3c3c",background:"#252526",padding:0,minHeight:0,display:"flex",flexDirection:"column"},children:[k.jsx("div",{style:{padding:"8px 12px",borderBottom:"1px solid #3c3c3c"},children:k.jsx("div",{style:{fontSize:11,color:"#bbbbbb",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Network"})}),k.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:10},children:[k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Total assets"}),k.jsx("div",{style:{fontSize:12,color:"#cccccc"},children:Kr(s)})]}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Total (non-assets)"}),k.jsx("div",{style:{fontSize:12,color:"#cccccc"},children:Kr(o)})]}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Total"}),k.jsx("div",{style:{fontSize:12,color:"#cccccc"},children:Kr(i)})]}),k.jsx("div",{style:{height:1,background:"#3c3c3c",opacity:.5}}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Per second"}),k.jsxs("div",{style:{fontSize:12,color:"#cccccc"},children:[Kr(a),"/s"]})]}),k.jsxs("div",{style:{width:"100%",height:160,border:"1px solid #3c3c3c",background:"#111",padding:"8px 10px 10px",boxSizing:"border-box"},children:[k.jsx("div",{style:{marginBottom:6,color:"#aaa",fontSize:12},children:"Bandwidth (total)"}),k.jsx(BC,{data:l,seriesKeys:["total"],seriesLabels:{total:"Total"},colors:["#4fc1ff"],height:120,tickRate:e,windowSeconds:10})]})]})]})}function ay({enabled:r,initialRect:e,minSize:t}){const[n,i]=N.useState(e),[s,o]=N.useState(!1),a=N.useRef({x:0,y:0}),l=N.useRef({resizing:!1,startX:0,startY:0,startW:0,startH:0});return N.useEffect(()=>{if(!r)return;const d=()=>{i(h=>{const p=Math.max(t.width,window.innerWidth-16),m=Math.max(t.height,window.innerHeight-8*2),S=Math.min(Math.max(t.width,h.width),p),w=Math.min(Math.max(t.height,h.height),m),g=Math.min(Math.max(8,h.x),Math.max(8,window.innerWidth-8-S)),y=Math.min(Math.max(8,h.y),Math.max(8,window.innerHeight-8-w));return{x:g,y,width:S,height:w}})};return d(),window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)},[r,t.height,t.width]),N.useEffect(()=>{if(!r)return;const d=f=>{if(s){i(p=>({...p,x:Math.max(0,f.clientX-a.current.x),y:Math.max(0,f.clientY-a.current.y)}));return}if(l.current.resizing){const p=f.clientX-l.current.startX,m=f.clientY-l.current.startY;i(S=>({...S,width:Math.max(t.width,l.current.startW+p),height:Math.max(t.height,l.current.startH+m)}))}},h=()=>{o(!1),l.current.resizing=!1};return window.addEventListener("mousemove",d),window.addEventListener("mouseup",h),()=>{window.removeEventListener("mousemove",d),window.removeEventListener("mouseup",h)}},[r,s,t.height,t.width]),{rect:n,setRect:i,isDragging:s,startDrag:(d,h)=>{r&&(o(!0),i(f=>(a.current={x:d-f.x,y:h-f.y},f)))},startResize:(d,h)=>{r&&i(f=>(l.current={resizing:!0,startX:d,startY:h,startW:f.width,startH:f.height},f))}}}function ly(r){const[e,t]=N.useState({width:600,height:400}),[n,i]=N.useState({left:0,top:0}),[s,o]=N.useState(null);return N.useLayoutEffect(()=>{const a=r.current??null;o(l=>l===a?l:a)},[r]),N.useEffect(()=>{const a=s;if(!a)return;const l=()=>{const c=a.getBoundingClientRect();i({left:c.left,top:c.top})},u=new ResizeObserver(c=>{const d=c[0];d&&(t({width:d.contentRect.width,height:d.contentRect.height}),l())});return u.observe(a),l(),window.addEventListener("resize",l),()=>{window.removeEventListener("resize",l),u.disconnect()}},[s]),{size:e,rect:n}}function UU(r,e){const[t,n]=N.useState(null),[i,s]=N.useState([]),[o,a]=N.useState(null),[l,u]=N.useState(0),c=N.useMemo(()=>r?r.layers.map(y=>({id:y.id,x:y.origin.x,y:y.origin.y,width:y.width,height:y.height,color:i.includes(y.id)?"rgba(43, 140, 255, 0.7)":void 0})):[],[r,i]),d=N.useMemo(()=>r?r.displays.map(y=>({id:y.id,x:y.origin.x,y:y.origin.y,width:y.size.x,height:y.size.y})):[],[r]),h=N.useMemo(()=>o!=null?c.find(y=>y.id===o)??null:t!=null?d.find(y=>y.id===t)??null:null,[o,t,d,c]),f=N.useMemo(()=>`${t??"none"}-${i.join(",")}-${l}`,[t,i,l]),p=y=>{r!=null&&r.displays.some(C=>C.id===y)&&(u(C=>C+1),n(y),s([]),a(null),e.setVisibleLayers(null))},m=y=>{const C=r==null?void 0:r.layers.find(x=>x.id===y);return C?{x:C.origin.x,y:C.origin.y,width:C.width,height:C.height}:null},S=(y,C)=>{if(e.setVisibleLayersDisplay255(y.length>0?y:null),C!=null){const x=m(C);x&&e.sendDisplayTransform(x)}},w=(y,C)=>{if(!(r!=null&&r.layers.some(I=>I.id===y)))return;const x=!!(C&&(C.metaKey||C.ctrlKey));u(I=>I+1),n(null),s(I=>{if(!x)return I.includes(y)?(a(null),S([],null),[]):(a(y),S([y],y),[y]);const E=I.includes(y)?I.filter(R=>R!==y):[...I,y],A=E.length>0?E[E.length-1]:null;return a(A),S(E,A),E})},g=(y,C)=>{if(!(r!=null&&r.layers.some(I=>I.id===y)))return;const x=!!(C&&(C.metaKey||C.ctrlKey));u(I=>I+1),n(null),s(I=>{if(!x)return I.includes(y)?(a(null),S([],null),[]):(a(y),S([y],y),[y]);const E=I.includes(y)?I.filter(R=>R!==y):[...I,y],A=E.length>0?E[E.length-1]:null;return a(A),S(E,A),E})};return N.useEffect(()=>{if(!r){n(null),s([]),a(null),e.setVisibleLayers(null),e.setVisibleLayersDisplay255(null);return}const y=new Set(r.layers.map(x=>x.id)),C=new Set(r.displays.map(x=>x.id));s(x=>{const I=x.filter(A=>y.has(A)),E=I.length>0?I[I.length-1]:null;return a(E),S(I,E),I}),n(x=>x!=null&&C.has(x)?x:null)},[r,e]),{selectedDisplayId:t,selectedLayerIds:i,lastSelectedLayerId:o,focusKey:f,focusRect:h,handleSelectDisplay:p,handleSelectLayer:w,handleSelectLayerDisplay255Only:g,setFocusNonce:u}}function AU(r){const{enabled:e,snapshot:t,topKeys:n,topTraffic:i}=r,[s,o]=N.useState([]),a=N.useRef(null),l=N.useRef(0),u=N.useRef(i);u.current=i;const c=N.useMemo(()=>n.join(","),[n]);N.useEffect(()=>{e&&o(f=>{if(f.length>0)return f;const p={time:"—"};for(let m=0;m<n.length;m++)p[n[m]]=0;return[p]})},[e,c]),N.useEffect(()=>{var C,x;if(!e||!t)return;const f=((C=t==null?void 0:t.tick)==null?void 0:C.tickRate)??((x=t==null?void 0:t.tick)==null?void 0:x.tps)??60,p=Math.max(1,Math.round(f*60)),m=performance.now?performance.now():Date.now(),S=Math.max(1,Math.round(1e3/f));if(m-l.current<S)return;l.current=m;const g={time:new Date().toLocaleTimeString("en-US",{hour12:!1,minute:"2-digit",second:"2-digit"})},y=u.current;for(let I=0;I<y.length;I++){const E=y[I];g[E.key]=E.bps??0}o(I=>{if(a.current!==f)return a.current=f,[g];const E=I.length===0?[g]:[...I,g];return E.length>p?E.slice(E.length-p):E})},[e,t,c]);const d=a.current??60,h=N.useMemo(()=>{if(!e)return[];const f=new Array(s.length);for(let p=0;p<s.length;p++){const m=s[p],S={time:m.time};for(let w=0;w<n.length;w++){const g=n[w];S[g]=Number(m[g]??0)}f[p]=S}return f},[e,s,n]);return{trafficHistory:s,tickRate:d,chartData:h}}const TU=r=>typeof r!="string"?"8-bit":r.includes("16")?"16-bit":"8-bit";function RU(r){var w;const{primaryUser:e,selection:t,selectedDisplayId:n,lastSelectedLayerId:i,selectedLayerIds:s}=r,o=N.useMemo(()=>((e==null?void 0:e.displays)??[]).map(y=>({id:y.id,x:y.origin.x,y:y.origin.y,width:y.size.x,height:y.size.y})),[e]),a=((w=e==null?void 0:e.layers)==null?void 0:w.length)??0,l=N.useMemo(()=>e?!t.selectedLayerIds.length&&!e?[]:e.layers.map(g=>({id:g.id,x:g.origin.x,y:g.origin.y,width:g.width,height:g.height,zIndex:g.z??0,name:g.name})):[],[e,t.selectedLayerIds.length]),u=N.useMemo(()=>{if(!e)return null;if(s.length){const g=e.layers.find(y=>y.id===i);return g?{type:"layer",item:g}:null}if(n!=null){const g=e.displays.find(y=>y.id===n);return g?{type:"display",item:g}:null}return null},[i,e,n,s.length]),c=N.useMemo(()=>{const y=((e==null?void 0:e.layers)??[]).filter(F=>typeof F.bytesPerSec1s=="number").map(F=>({key:`layer-${F.id}`,id:F.id,name:F.name,encoding:TU(F.charCodeMode),total:F.bytesTotal??0,bps:F.bytesPerSec1s??0,size:{x:F.width,y:F.height},position:{x:F.origin.x,y:F.origin.y},zIndex:F.z??0})),C=(e==null?void 0:e.miscTraffic)??{},x=F=>{switch(F){case"update.audioOrders":return"Audio";case"update.vibrationOrders":return"Vibration";case"update.macroOrders":return"Macro";case"update.postProcessOrders":return"PostProcess";default:return F}},I=Object.entries(C).map(([F,z],P)=>({key:`misc-${F}`,id:1e5+P,name:x(F),total:z.total??0,bps:z.bytesPerSec1s??0,size:{x:0,y:0},position:{x:0,y:0},zIndex:0})),E=((e==null?void 0:e.displays)??[]).filter(F=>F.id!==255),A=(e==null?void 0:e.displayTraffic)??{},R=E.map(F=>{const z=A[F.id];return{key:`display-${F.id}`,id:F.id,name:`Display ${F.id}`,total:(z==null?void 0:z.total)??0,bps:(z==null?void 0:z.bytesPerSec1s)??0,size:{x:F.size.x,y:F.size.y},position:{x:F.origin.x,y:F.origin.y},zIndex:0}}).filter(F=>typeof F.bps=="number");return[...y,...R,...I]},[e]),d=N.useMemo(()=>[...c].sort((g,y)=>y.total-g.total),[c]),h=N.useMemo(()=>d.slice(0,6),[d]),f=N.useMemo(()=>h.map(g=>g.key),[h]),p=N.useMemo(()=>Object.fromEntries(d.map(g=>[g.key,g.name??String(g.id)])),[d]),m=["#4fc1ff","#9cdcfe","#7bd389","#f9d85c","#f38ba8","#c586c0"],S=N.useMemo(()=>{const g={},y=new Set(d.map(x=>x.key)),C=x=>{let I=2166136261;for(let E=0;E<x.length;E++)I^=x.charCodeAt(E),I=Math.imul(I,16777619);return I>>>0};return y.forEach(x=>{const I=/^layer-(\d+)$/.exec(x),E=I?Number(I[1]):NaN,A=Number.isFinite(E)?E:C(x);g[x]=m[A%m.length]??"#4fc1ff"}),g},[d]);return{worldDisplays:o,worldLayers:l,layerCount:a,detailTarget:u,trafficItems:c,sortedTraffic:d,topTraffic:h,topKeys:f,keyToLabel:p,keyToColor:S}}function PU(r){const{runtimeClient:e,serverUrl:t,renderer:n,muted:i,snapshot:s}=r,o=N.useRef(null),a=N.useRef(null),l=N.useRef(null),[u,c]=N.useState({audio:[],atlases:[],palettes:[]}),d=N.useCallback(async()=>{const h=o.current,f=a.current;h&&(l.current=t,e.start({serverUrl:t,container:h,displayContainers:f?[{id:255,container:f}]:void 0,renderer:n,inputEnabled:!0,captureInput:!0}).catch(()=>{}))},[n,e,t]);return N.useEffect(()=>{const h=o.current,f=a.current;h&&l.current!==t&&(l.current=t,e.start({serverUrl:t,container:h,displayContainers:f?[{id:255,container:f}]:void 0,renderer:n,inputEnabled:!0,captureInput:!0}).catch(()=>{}))},[n,e,t]),N.useEffect(()=>{e.setMuted(i)},[i,e]),N.useEffect(()=>{c(e.getAssetsSnapshot())},[e,s]),{rendererContainerRef:o,debugDisplay255ContainerRef:a,connect:d,assetsSnapshot:u,setAssetsSnapshot:c}}function BU({connected:r,placement:e,headerHeight:t,frameRect:n,containerRef:i,onTogglePlacement:s,onStartDrag:o,onStartResize:a}){const l=e==="float";return k.jsxs("div",{style:{position:"fixed",left:n.x,top:n.y,width:n.width,height:n.height,zIndex:l?950:1,background:"#1a1a1a",border:"1px solid #3c3c3c",boxShadow:l?"0 8px 24px rgba(0,0,0,0.35)":"none",display:"flex",flexDirection:"column",userSelect:"none"},children:[k.jsxs("div",{style:{height:t,background:"#2d2d2d",borderBottom:"1px solid #3c3c3c",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px",fontSize:12,color:"#cccccc",cursor:l?"move":"default"},onMouseDown:u=>{l&&o(u.clientX,u.clientY)},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[k.jsx("div",{style:{width:8,height:8,borderRadius:4,background:r?"#4fc1ff":"#a0a0a0"}}),k.jsx("div",{children:"Debug View"})]}),k.jsx("button",{onClick:u=>{u.stopPropagation(),s()},style:{height:22,padding:"0 8px",border:"1px solid #3c3c3c",background:"#3c3c3c",color:"#ffffff",cursor:"pointer",fontSize:12},title:l?"Embed into layout":"Float window",children:l?"Embed":"Float"})]}),k.jsx("div",{ref:i,style:{flex:1,backgroundColor:"#0f0f0f",backgroundImage:"linear-gradient(45deg, rgba(255,255,255,0.05) 25%, transparent 25%),linear-gradient(-45deg, rgba(255,255,255,0.05) 25%, transparent 25%),linear-gradient(45deg, transparent 75%, rgba(255,255,255,0.05) 75%),linear-gradient(-45deg, transparent 75%, rgba(255,255,255,0.05) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0",overflow:"hidden",outline:"1px solid rgba(255,255,255,0.06)"}}),l&&k.jsx("div",{onMouseDown:u=>{u.stopPropagation(),a(u.clientX,u.clientY)},style:{position:"absolute",width:14,height:14,right:2,bottom:2,cursor:"nwse-resize",background:"#2d2d2d",border:"1px solid #3c3c3c",borderRadius:2}})]})}const vl=new aM;function zU(){var Cr;const[r,e]=N.useState(()=>{if(typeof window>"u")return"http://localhost:3200";const{protocol:Se,hostname:Re,port:pe}=window.location;return pe==="4173"||pe==="5173"?`${Se}//${Re}:3200`:`${Se}//${Re}${pe?`:${pe}`:""}`}),t=Ys(Se=>Se.lastSnapshot),n=Ys(Se=>Se.connected),[i,s]=N.useState(!1),[o,a]=N.useState("grid"),[l,u]=N.useState(null),[c,d]=N.useState("float"),[h,f]=N.useState({width:0,height:0}),[p,m]=N.useState("embedded"),[S,w]=N.useState("network"),g=28,y={width:220,height:160},C=c==="float",x=24,I={width:220,height:160},E=ay({enabled:C,initialRect:{x:12,y:80,width:360,height:220},minSize:y}),A=ay({enabled:p==="float",initialRect:{x:12,y:360,width:360,height:260},minSize:I}),R=((Cr=t==null?void 0:t.users)==null?void 0:Cr[0])??null,F=p==="float",z=UU(R,vl),P=z.selectedDisplayId,D=z.selectedLayerIds,L=z.lastSelectedLayerId,V=z.focusRect,X=z.focusKey,T=N.useRef(null),{rect:_,size:j}=ly(T),{worldDisplays:G,worldLayers:ee,detailTarget:q,sortedTraffic:K,topTraffic:oe,topKeys:ve,keyToLabel:ge,keyToColor:Ce}=RU({primaryUser:R,selection:z,selectedDisplayId:P,lastSelectedLayerId:L,selectedLayerIds:D}),{tickRate:dt,chartData:ht}=AU({enabled:!0,snapshot:t,topKeys:ve,topTraffic:oe}),{rendererContainerRef:xe,debugDisplay255ContainerRef:et,connect:Ke,assetsSnapshot:qe}=PU({runtimeClient:vl,serverUrl:r,renderer:Of.TerminalGL,muted:i,snapshot:t});N.useEffect(()=>{const Se="/logo_debugger.ico",Re=document.querySelector("link[rel='icon']");if(Re)Re.href=Se;else{const pe=document.createElement("link");pe.rel="icon",pe.href=Se,document.head.appendChild(pe)}},[]),N.useEffect(()=>{const Se=Re=>{const pe=Re.detail;pe&&vl.sendDisplayTransform(pe)};return window.addEventListener("__utsp_debug_display255_rect",Se),()=>window.removeEventListener("__utsp_debug_display255_rect",Se)},[]),N.useEffect(()=>{const Se=document.documentElement.style.overflow,Re=document.body.style.overflow,pe=document.documentElement.style.margin,ne=document.body.style.margin,$e=document.documentElement.style.padding,ft=document.body.style.padding;return document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.documentElement.style.margin="0",document.body.style.margin="0",document.documentElement.style.padding="0",document.body.style.padding="0",()=>{document.documentElement.style.overflow=Se,document.body.style.overflow=Re,document.documentElement.style.margin=pe,document.body.style.margin=ne,document.documentElement.style.padding=$e,document.body.style.padding=ft}},[]);const At=N.useRef(null),{size:wt,rect:Ft}=ly(At);N.useEffect(()=>{const Se=xe.current;if(!Se)return;const Re=new ResizeObserver(pe=>{const ne=pe[0];ne&&f({width:Math.round(ne.contentRect.width),height:Math.round(ne.contentRect.height)})});return Re.observe(Se),()=>Re.disconnect()},[]);const cr=wt.width,tt=wt.height,kt={left:C?E.rect.x:Ft.left,top:C?E.rect.y:Ft.top,width:C?E.rect.width:cr,height:C?E.rect.height:tt},nt=F?A.rect:{x:_.left??0,y:_.top??0,width:j.width||280,height:j.height||260};return k.jsxs("div",{style:{fontFamily:"'Segoe UI', 'Helvetica Neue', sans-serif",background:"#1e1e1e",color:"#cccccc",minHeight:"100vh",margin:0,display:"flex",flexDirection:"column"},children:[k.jsx(gM,{connected:n,serverUrl:r,onServerUrlChange:e,onReconnect:()=>{Ke()}}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"240px 1fr 280px",gap:0,padding:0,boxSizing:"border-box",flex:1,minHeight:0,overflow:"hidden"},children:[k.jsx("div",{style:{borderRight:"1px solid #3c3c3c",background:"#252526",display:"flex",flexDirection:"column",minHeight:0},children:k.jsx(pM,{primaryUser:R??null,selectedDisplayId:P,selectedLayerIds:D,onSelectDisplay:z.handleSelectDisplay,onSelectLayer:z.handleSelectLayerDisplay255Only})}),k.jsx(kU,{centerTab:o,setCenterTab:a,centerPanelRef:At,centerSize:wt,worldLayers:ee,worldDisplays:G,selectedLayerIds:D,setVisibleLayers:Se=>vl.setVisibleLayers(Se),selectedDisplayId:P,focusRect:V,focusKey:X,onSelectLayer:z.handleSelectLayer,onSelectDisplay:z.handleSelectDisplay,assetsSnapshot:qe,primaryUser:R,isFloating:C,sortedTraffic:K,topTraffic:oe,chartData:ht,topKeys:ve,keyToLabel:ge,keyToColor:Ce,tickRate:dt,hoveredTrafficKey:l,setHoveredTrafficKey:u}),k.jsxs("div",{style:{borderLeft:"1px solid #3c3c3c",background:"#252526",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto",overflowX:"hidden"},children:[k.jsx("div",{ref:T,style:{padding:0,borderBottom:"1px solid #3c3c3c",height:260,minHeight:260,width:"100%",boxSizing:"border-box"}}),k.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid #3c3c3c"},children:[{id:"network",label:"Network"},{id:"layer",label:"Selected Layer"}].map(Se=>{const Re=S===Se.id;return k.jsx("button",{onClick:()=>w(Se.id),style:{border:"1px solid #3c3c3c",background:Re?"#1e1e1e":"#2d2d2d",color:"#cccccc",padding:"4px 10px",cursor:"pointer",fontSize:12,borderRadius:6},children:Se.label},Se.id)})}),k.jsx("div",{style:{flex:1,minHeight:0},children:S==="network"?k.jsx(MU,{primaryUser:R,tickRate:dt,snapshot:t,assetsSnapshot:qe}):k.jsx("div",{style:{height:"100%",minHeight:0},children:k.jsx(dM,{detailTarget:q})})})]})]}),k.jsx(lM,{connected:n,muted:i,rendererPlacement:c,centerTab:o,frameRect:kt,rendererHeaderHeight:g,rendererContentSize:h,rendererContainerRef:xe,onTogglePlacement:()=>{d(Se=>{const Re=Se==="float"?"embedded":"float";return Re==="embedded"&&a("renderer"),Re})},onToggleMuted:()=>{s(Se=>!Se)},onStartDrag:(Se,Re)=>{E.startDrag(Se,Re)},onStartResize:(Se,Re)=>{E.startResize(Se,Re)}}),k.jsx(BU,{connected:n,placement:p,headerHeight:x,frameRect:nt,containerRef:et,onTogglePlacement:()=>m(Se=>Se==="float"?"embedded":"float"),onStartDrag:A.startDrag,onStartResize:A.startResize})]})}const DC=document.getElementById("root");if(!DC)throw new Error("Root container not found");td.createRoot(DC).render(k.jsx(Cy.StrictMode,{children:k.jsx(zU,{})}));
|