@utsp/runtime-server 0.16.0-nightly.20251231153713.b870da1 → 0.16.0-nightly.20260101200530.42ed56f
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.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var ix=Object.defineProperty;var sx=(r,e,t)=>e in r?ix(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Xi=(r,e,t)=>sx(r,typeof e!="symbol"?e+"":e,t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function t(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(i){if(i.ep)return;i.ep=!0;const s=t(i);fetch(i.href,s)}})();var Nr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Cy(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var xy={exports:{}},mu={},Iy={exports:{}},Ae={};/**
|
|
2
2
|
* @license React
|
|
3
3
|
* react.production.min.js
|
|
4
4
|
*
|
|
@@ -6,7 +6,7 @@ var qC=Object.defineProperty;var QC=(r,e,t)=>e in r?qC(r,e,{enumerable:!0,config
|
|
|
6
6
|
*
|
|
7
7
|
* This source code is licensed under the MIT license found in the
|
|
8
8
|
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var Pa=Symbol.for("react.element"),
|
|
9
|
+
*/var Pa=Symbol.for("react.element"),ox=Symbol.for("react.portal"),ax=Symbol.for("react.fragment"),lx=Symbol.for("react.strict_mode"),ux=Symbol.for("react.profiler"),cx=Symbol.for("react.provider"),dx=Symbol.for("react.context"),hx=Symbol.for("react.forward_ref"),fx=Symbol.for("react.suspense"),px=Symbol.for("react.memo"),gx=Symbol.for("react.lazy"),jp=Symbol.iterator;function mx(r){return r===null||typeof r!="object"?null:(r=jp&&r[jp]||r["@@iterator"],typeof r=="function"?r:null)}var Sy={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ky=Object.assign,Ey={};function go(r,e,t){this.props=r,this.context=e,this.refs=Ey,this.updater=t||Sy}go.prototype.isReactComponent={};go.prototype.setState=function(r,e){if(typeof r!="object"&&typeof r!="function"&&r!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,r,e,"setState")};go.prototype.forceUpdate=function(r){this.updater.enqueueForceUpdate(this,r,"forceUpdate")};function My(){}My.prototype=go.prototype;function Hh(r,e,t){this.props=r,this.context=e,this.refs=Ey,this.updater=t||Sy}var Vh=Hh.prototype=new My;Vh.constructor=Hh;ky(Vh,go.prototype);Vh.isPureReactComponent=!0;var Yp=Array.isArray,Ty=Object.prototype.hasOwnProperty,jh={current:null},Uy={key:!0,ref:!0,__self:!0,__source:!0};function Ay(r,e,t){var n,i={},s=null,o=null;if(e!=null)for(n in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(s=""+e.key),e)Ty.call(e,n)&&!Uy.hasOwnProperty(n)&&(i[n]=e[n]);var a=arguments.length-2;if(a===1)i.children=t;else if(1<a){for(var l=Array(a),u=0;u<a;u++)l[u]=arguments[u+2];i.children=l}if(r&&r.defaultProps)for(n in a=r.defaultProps,a)i[n]===void 0&&(i[n]=a[n]);return{$$typeof:Pa,type:r,key:s,ref:o,props:i,_owner:jh.current}}function yx(r,e){return{$$typeof:Pa,type:r.type,key:e,ref:r.ref,props:r.props,_owner:r._owner}}function Yh(r){return typeof r=="object"&&r!==null&&r.$$typeof===Pa}function vx(r){var e={"=":"=0",":":"=2"};return"$"+r.replace(/[=:]/g,function(t){return e[t]})}var Gp=/\/+/g;function dc(r,e){return typeof r=="object"&&r!==null&&r.key!=null?vx(""+r.key):e.toString(36)}function Cl(r,e,t,n,i){var s=typeof r;(s==="undefined"||s==="boolean")&&(r=null);var o=!1;if(r===null)o=!0;else switch(s){case"string":case"number":o=!0;break;case"object":switch(r.$$typeof){case Pa:case ox:o=!0}}if(o)return o=r,i=i(o),r=n===""?"."+dc(o,0):n,Yp(i)?(t="",r!=null&&(t=r.replace(Gp,"$&/")+"/"),Cl(i,e,t,"",function(u){return u})):i!=null&&(Yh(i)&&(i=yx(i,t+(!i.key||o&&o.key===i.key?"":(""+i.key).replace(Gp,"$&/")+"/")+r)),e.push(i)),1;if(o=0,n=n===""?".":n+":",Yp(r))for(var a=0;a<r.length;a++){s=r[a];var l=n+dc(s,a);o+=Cl(s,e,t,l,i)}else if(l=mx(r),typeof l=="function")for(r=l.call(r),a=0;!(s=r.next()).done;)s=s.value,l=n+dc(s,a++),o+=Cl(s,e,t,l,i);else if(s==="object")throw e=String(r),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(r).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.");return o}function Xa(r,e,t){if(r==null)return r;var n=[],i=0;return Cl(r,n,"","",function(s){return e.call(t,s,i++)}),n}function wx(r){if(r._status===-1){var e=r._result;e=e(),e.then(function(t){(r._status===0||r._status===-1)&&(r._status=1,r._result=t)},function(t){(r._status===0||r._status===-1)&&(r._status=2,r._result=t)}),r._status===-1&&(r._status=0,r._result=e)}if(r._status===1)return r._result.default;throw r._result}var Ar={current:null},xl={transition:null},bx={ReactCurrentDispatcher:Ar,ReactCurrentBatchConfig:xl,ReactCurrentOwner:jh};function Ry(){throw Error("act(...) is not supported in production builds of React.")}Ae.Children={map:Xa,forEach:function(r,e,t){Xa(r,function(){e.apply(this,arguments)},t)},count:function(r){var e=0;return Xa(r,function(){e++}),e},toArray:function(r){return Xa(r,function(e){return e})||[]},only:function(r){if(!Yh(r))throw Error("React.Children.only expected to receive a single React element child.");return r}};Ae.Component=go;Ae.Fragment=ax;Ae.Profiler=ux;Ae.PureComponent=Hh;Ae.StrictMode=lx;Ae.Suspense=fx;Ae.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=bx;Ae.act=Ry;Ae.cloneElement=function(r,e,t){if(r==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+r+".");var n=ky({},r.props),i=r.key,s=r.ref,o=r._owner;if(e!=null){if(e.ref!==void 0&&(s=e.ref,o=jh.current),e.key!==void 0&&(i=""+e.key),r.type&&r.type.defaultProps)var a=r.type.defaultProps;for(l in e)Ty.call(e,l)&&!Uy.hasOwnProperty(l)&&(n[l]=e[l]===void 0&&a!==void 0?a[l]:e[l])}var l=arguments.length-2;if(l===1)n.children=t;else if(1<l){a=Array(l);for(var u=0;u<l;u++)a[u]=arguments[u+2];n.children=a}return{$$typeof:Pa,type:r.type,key:i,ref:s,props:n,_owner:o}};Ae.createContext=function(r){return r={$$typeof:dx,_currentValue:r,_currentValue2:r,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},r.Provider={$$typeof:cx,_context:r},r.Consumer=r};Ae.createElement=Ay;Ae.createFactory=function(r){var e=Ay.bind(null,r);return e.type=r,e};Ae.createRef=function(){return{current:null}};Ae.forwardRef=function(r){return{$$typeof:hx,render:r}};Ae.isValidElement=Yh;Ae.lazy=function(r){return{$$typeof:gx,_payload:{_status:-1,_result:r},_init:wx}};Ae.memo=function(r,e){return{$$typeof:px,type:r,compare:e===void 0?null:e}};Ae.startTransition=function(r){var e=xl.transition;xl.transition={};try{r()}finally{xl.transition=e}};Ae.unstable_act=Ry;Ae.useCallback=function(r,e){return Ar.current.useCallback(r,e)};Ae.useContext=function(r){return Ar.current.useContext(r)};Ae.useDebugValue=function(){};Ae.useDeferredValue=function(r){return Ar.current.useDeferredValue(r)};Ae.useEffect=function(r,e){return Ar.current.useEffect(r,e)};Ae.useId=function(){return Ar.current.useId()};Ae.useImperativeHandle=function(r,e,t){return Ar.current.useImperativeHandle(r,e,t)};Ae.useInsertionEffect=function(r,e){return Ar.current.useInsertionEffect(r,e)};Ae.useLayoutEffect=function(r,e){return Ar.current.useLayoutEffect(r,e)};Ae.useMemo=function(r,e){return Ar.current.useMemo(r,e)};Ae.useReducer=function(r,e,t){return Ar.current.useReducer(r,e,t)};Ae.useRef=function(r){return Ar.current.useRef(r)};Ae.useState=function(r){return Ar.current.useState(r)};Ae.useSyncExternalStore=function(r,e,t){return Ar.current.useSyncExternalStore(r,e,t)};Ae.useTransition=function(){return Ar.current.useTransition()};Ae.version="18.3.1";Iy.exports=Ae;var $=Iy.exports;const Py=Cy($);/**
|
|
10
10
|
* @license React
|
|
11
11
|
* react-jsx-runtime.production.min.js
|
|
12
12
|
*
|
|
@@ -14,7 +14,7 @@ var qC=Object.defineProperty;var QC=(r,e,t)=>e in r?qC(r,e,{enumerable:!0,config
|
|
|
14
14
|
*
|
|
15
15
|
* This source code is licensed under the MIT license found in the
|
|
16
16
|
* LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/var
|
|
17
|
+
*/var Cx=$,xx=Symbol.for("react.element"),Ix=Symbol.for("react.fragment"),Sx=Object.prototype.hasOwnProperty,kx=Cx.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Ex={key:!0,ref:!0,__self:!0,__source:!0};function zy(r,e,t){var n,i={},s=null,o=null;t!==void 0&&(s=""+t),e.key!==void 0&&(s=""+e.key),e.ref!==void 0&&(o=e.ref);for(n in e)Sx.call(e,n)&&!Ex.hasOwnProperty(n)&&(i[n]=e[n]);if(r&&r.defaultProps)for(n in e=r.defaultProps,e)i[n]===void 0&&(i[n]=e[n]);return{$$typeof:xx,type:r,key:s,ref:o,props:i,_owner:kx.current}}mu.Fragment=Ix;mu.jsx=zy;mu.jsxs=zy;xy.exports=mu;var k=xy.exports,hd={},Dy={exports:{}},en={},Oy={exports:{}},By={};/**
|
|
18
18
|
* @license React
|
|
19
19
|
* scheduler.production.min.js
|
|
20
20
|
*
|
|
@@ -22,7 +22,7 @@ var qC=Object.defineProperty;var QC=(r,e,t)=>e in r?qC(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(W,j){var X=W.length;W.push(j);e:for(;0<X;){var te=X-1>>>1,Q=W[te];if(0<i(Q,j))W[te]=j,W[X]=Q,X=te;else break e}}function t(W){return W.length===0?null:W[0]}function n(W){if(W.length===0)return null;var j=W[0],X=W.pop();if(X!==j){W[0]=X;e:for(var te=0,Q=W.length,Z=Q>>>1;te<Z;){var se=2*(te+1)-1,ve=W[se],ge=se+1,be=W[ge];if(0>i(ve,X))ge<Q&&0>i(be,ve)?(W[te]=be,W[ge]=X,te=ge):(W[te]=ve,W[se]=X,te=se);else if(ge<Q&&0>i(be,X))W[te]=be,W[ge]=X,te=ge;else break e}}return j}function i(W,j){var X=W.sortIndex-j.sortIndex;return X!==0?X:W.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,g=!1,
|
|
25
|
+
*/(function(r){function e(W,j){var X=W.length;W.push(j);e:for(;0<X;){var te=X-1>>>1,Q=W[te];if(0<i(Q,j))W[te]=j,W[X]=Q,X=te;else break e}}function t(W){return W.length===0?null:W[0]}function n(W){if(W.length===0)return null;var j=W[0],X=W.pop();if(X!==j){W[0]=X;e:for(var te=0,Q=W.length,Z=Q>>>1;te<Z;){var se=2*(te+1)-1,ve=W[se],ge=se+1,be=W[ge];if(0>i(ve,X))ge<Q&&0>i(be,ve)?(W[te]=be,W[ge]=X,te=ge):(W[te]=ve,W[se]=X,te=se);else if(ge<Q&&0>i(be,X))W[te]=be,W[ge]=X,te=ge;else break e}}return j}function i(W,j){var X=W.sortIndex-j.sortIndex;return X!==0?X:W.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,g=!1,C=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,m=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function v(W){for(var j=t(u);j!==null;){if(j.callback===null)n(u);else if(j.startTime<=W)n(u),j.sortIndex=j.expirationTime,e(l,j);else break;j=t(u)}}function b(W){if(g=!1,v(W),!p)if(t(l)!==null)p=!0,H(S);else{var j=t(u);j!==null&&P(b,j.startTime-W)}}function S(W,j){p=!1,g&&(g=!1,y(U),U=-1),f=!0;var X=h;try{for(v(j),d=t(l);d!==null&&(!(d.expirationTime>j)||W&&!R());){var te=d.callback;if(typeof te=="function"){d.callback=null,h=d.priorityLevel;var Q=te(d.expirationTime<=j);j=r.unstable_now(),typeof Q=="function"?d.callback=Q:d===t(l)&&n(l),v(j)}else n(l);d=t(l)}if(d!==null)var Z=!0;else{var se=t(u);se!==null&&P(b,se.startTime-j),Z=!1}return Z}finally{d=null,h=X,f=!1}}var I=!1,E=null,U=-1,z=5,B=-1;function R(){return!(r.unstable_now()-B<z)}function O(){if(E!==null){var W=r.unstable_now();B=W;var j=!0;try{j=E(!0,W)}finally{j?A():(I=!1,E=null)}}else I=!1}var A;if(typeof m=="function")A=function(){m(O)};else if(typeof MessageChannel<"u"){var V=new MessageChannel,N=V.port2;V.port1.onmessage=O,A=function(){N.postMessage(null)}}else A=function(){C(O,0)};function H(W){E=W,I||(I=!0,A())}function P(W,j){U=C(function(){W(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(W){W.callback=null},r.unstable_continueExecution=function(){p||f||(p=!0,H(S))},r.unstable_forceFrameRate=function(W){0>W||125<W?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):z=0<W?Math.floor(1e3/W):5},r.unstable_getCurrentPriorityLevel=function(){return h},r.unstable_getFirstCallbackNode=function(){return t(l)},r.unstable_next=function(W){switch(h){case 1:case 2:case 3:var j=3;break;default:j=h}var X=h;h=j;try{return W()}finally{h=X}},r.unstable_pauseExecution=function(){},r.unstable_requestPaint=function(){},r.unstable_runWithPriority=function(W,j){switch(W){case 1:case 2:case 3:case 4:case 5:break;default:W=3}var X=h;h=W;try{return j()}finally{h=X}},r.unstable_scheduleCallback=function(W,j,X){var te=r.unstable_now();switch(typeof X=="object"&&X!==null?(X=X.delay,X=typeof X=="number"&&0<X?te+X:te):X=te,W){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=X+Q,W={id:c++,callback:j,priorityLevel:W,startTime:X,expirationTime:Q,sortIndex:-1},X>te?(W.sortIndex=X,e(u,W),t(l)===null&&W===t(u)&&(g?(y(U),U=-1):g=!0,P(b,X-te))):(W.sortIndex=Q,e(l,W),p||f||(p=!0,H(S))),W},r.unstable_shouldYield=R,r.unstable_wrapCallback=function(W){var j=h;return function(){var X=h;h=j;try{return W.apply(this,arguments)}finally{h=X}}}})(By);Oy.exports=By;var Mx=Oy.exports;/**
|
|
26
26
|
* @license React
|
|
27
27
|
* react-dom.production.min.js
|
|
28
28
|
*
|
|
@@ -30,35 +30,35 @@ var qC=Object.defineProperty;var QC=(r,e,t)=>e in r?qC(r,e,{enumerable:!0,config
|
|
|
30
30
|
*
|
|
31
31
|
* This source code is licensed under the MIT license found in the
|
|
32
32
|
* LICENSE file in the root directory of this source tree.
|
|
33
|
-
*/var
|
|
33
|
+
*/var Tx=$,Jr=Mx;function ee(r){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+r,t=1;t<arguments.length;t++)e+="&args[]="+encodeURIComponent(arguments[t]);return"Minified React error #"+r+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var Fy=new Set,pa={};function ps(r,e){ro(r,e),ro(r+"Capture",e)}function ro(r,e){for(pa[r]=e,r=0;r<e.length;r++)Fy.add(e[r])}var ni=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),fd=Object.prototype.hasOwnProperty,Ux=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Xp={},Zp={};function Ax(r){return fd.call(Zp,r)?!0:fd.call(Xp,r)?!1:Ux.test(r)?Zp[r]=!0:(Xp[r]=!0,!1)}function Rx(r,e,t,n){if(t!==null&&t.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return n?!1:t!==null?!t.acceptsBooleans:(r=r.toLowerCase().slice(0,5),r!=="data-"&&r!=="aria-");default:return!1}}function Px(r,e,t,n){if(e===null||typeof e>"u"||Rx(r,e,t,n))return!0;if(n)return!1;if(t!==null)switch(t.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function Rr(r,e,t,n,i,s,o){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=t,this.propertyName=r,this.type=e,this.sanitizeURL=s,this.removeEmptyString=o}var ur={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(r){ur[r]=new Rr(r,0,!1,r,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(r){var e=r[0];ur[e]=new Rr(e,1,!1,r[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(r){ur[r]=new Rr(r,2,!1,r.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(r){ur[r]=new Rr(r,2,!1,r,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(r){ur[r]=new Rr(r,3,!1,r.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(r){ur[r]=new Rr(r,3,!0,r,null,!1,!1)});["capture","download"].forEach(function(r){ur[r]=new Rr(r,4,!1,r,null,!1,!1)});["cols","rows","size","span"].forEach(function(r){ur[r]=new Rr(r,6,!1,r,null,!1,!1)});["rowSpan","start"].forEach(function(r){ur[r]=new Rr(r,5,!1,r.toLowerCase(),null,!1,!1)});var Gh=/[\-:]([a-z])/g;function Xh(r){return r[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(r){var e=r.replace(Gh,Xh);ur[e]=new Rr(e,1,!1,r,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(r){var e=r.replace(Gh,Xh);ur[e]=new Rr(e,1,!1,r,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(r){var e=r.replace(Gh,Xh);ur[e]=new Rr(e,1,!1,r,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(r){ur[r]=new Rr(r,1,!1,r.toLowerCase(),null,!1,!1)});ur.xlinkHref=new Rr("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(r){ur[r]=new Rr(r,1,!1,r.toLowerCase(),null,!0,!0)});function Zh(r,e,t,n){var i=ur.hasOwnProperty(e)?ur[e]:null;(i!==null?i.type!==0:n||!(2<e.length)||e[0]!=="o"&&e[0]!=="O"||e[1]!=="n"&&e[1]!=="N")&&(Px(e,t,i,n)&&(t=null),n||i===null?Ax(e)&&(t===null?r.removeAttribute(e):r.setAttribute(e,""+t)):i.mustUseProperty?r[i.propertyName]=t===null?i.type===3?!1:"":t:(e=i.attributeName,n=i.attributeNamespace,t===null?r.removeAttribute(e):(i=i.type,t=i===3||i===4&&t===!0?"":""+t,n?r.setAttributeNS(n,e,t):r.setAttribute(e,t))))}var ai=Tx.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,Za=Symbol.for("react.element"),Os=Symbol.for("react.portal"),Bs=Symbol.for("react.fragment"),Kh=Symbol.for("react.strict_mode"),pd=Symbol.for("react.profiler"),Ly=Symbol.for("react.provider"),_y=Symbol.for("react.context"),qh=Symbol.for("react.forward_ref"),gd=Symbol.for("react.suspense"),md=Symbol.for("react.suspense_list"),Qh=Symbol.for("react.memo"),mi=Symbol.for("react.lazy"),$y=Symbol.for("react.offscreen"),Kp=Symbol.iterator;function Ro(r){return r===null||typeof r!="object"?null:(r=Kp&&r[Kp]||r["@@iterator"],typeof r=="function"?r:null)}var Ct=Object.assign,hc;function Vo(r){if(hc===void 0)try{throw Error()}catch(t){var e=t.stack.trim().match(/\n( *(at )?)/);hc=e&&e[1]||""}return`
|
|
34
34
|
`+hc+r}var fc=!1;function pc(r,e){if(!r||fc)return"";fc=!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{fc=!1,Error.prepareStackTrace=t}return(r=r?r.displayName||r.name:"")?Ho(r):""}function Ex(r){switch(r.tag){case 5:return Ho(r.type);case 16:return Ho("Lazy");case 13:return Ho("Suspense");case 19:return Ho("SuspenseList");case 0:case 2:case 15:return r=pc(r.type,!1),r;case 11:return r=pc(r.type.render,!1),r;case 1:return r=pc(r.type,!0),r;default:return""}}function pd(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 Os:return"Fragment";case Ds:return"Portal";case dd:return"Profiler";case Gh:return"StrictMode";case hd:return"Suspense";case fd:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case zy:return(r.displayName||"Context")+".Consumer";case Py:return(r._context.displayName||"Context")+".Provider";case Xh: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:pd(r.type)||"Memo";case mi:e=r._payload,r=r._init;try{return pd(r(e))}catch{}}return null}function Mx(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 pd(e);case 8:return e===Gh?"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 Di(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function Oy(r){var e=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function Tx(r){var e=Oy(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 Ka(r){r._valueTracker||(r._valueTracker=Tx(r))}function By(r){if(!r)return!1;var e=r._valueTracker;if(!e)return!0;var t=e.getValue(),n="";return r&&(n=Oy(r)?r.checked?"true":"false":r.value),r=n,r!==t?(e.setValue(r),!0):!1}function _l(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 gd(r,e){var t=e.checked;return Ct({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??r._wrapperState.initialChecked})}function Xp(r,e){var t=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;t=Di(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 Fy(r,e){e=e.checked,e!=null&&Yh(r,"checked",e,!1)}function md(r,e){Fy(r,e);var t=Di(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")?yd(r,e.type,t):e.hasOwnProperty("defaultValue")&&yd(r,e.type,Di(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(r.defaultChecked=!!e.defaultChecked)}function Zp(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 yd(r,e,t){(e!=="number"||_l(r.ownerDocument)!==r)&&(t==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+t&&(r.defaultValue=""+t))}var Vo=Array.isArray;function Xs(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=""+Di(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 vd(r,e){if(e.dangerouslySetInnerHTML!=null)throw Error(ee(91));return Ct({},e,{value:void 0,defaultValue:void 0,children:""+r._wrapperState.initialValue})}function Kp(r,e){var t=e.value;if(t==null){if(t=e.children,e=e.defaultValue,t!=null){if(e!=null)throw Error(ee(92));if(Vo(t)){if(1<t.length)throw Error(ee(93));t=t[0]}e=t}e==null&&(e=""),t=e}r._wrapperState={initialValue:Di(t)}}function Ly(r,e){var t=Di(e.value),n=Di(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 qp(r){var e=r.textContent;e===r._wrapperState.initialValue&&e!==""&&e!==null&&(r.value=e)}function _y(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 wd(r,e){return r==null||r==="http://www.w3.org/1999/xhtml"?_y(e):r==="http://www.w3.org/2000/svg"&&e==="foreignObject"?"http://www.w3.org/1999/xhtml":r}var qa,$y=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(qa=qa||document.createElement("div"),qa.innerHTML="<svg>"+e.valueOf().toString()+"</svg>",e=qa.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;e.firstChild;)r.appendChild(e.firstChild)}});function ga(r,e){if(e){var t=r.firstChild;if(t&&t===r.lastChild&&t.nodeType===3){t.nodeValue=e;return}}r.textContent=e}var ta={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},Ux=["Webkit","ms","Moz","O"];Object.keys(ta).forEach(function(r){Ux.forEach(function(e){e=e+r.charAt(0).toUpperCase()+r.substring(1),ta[e]=ta[r]})});function Ny(r,e,t){return e==null||typeof e=="boolean"||e===""?"":t||typeof e!="number"||e===0||ta.hasOwnProperty(r)&&ta[r]?(""+e).trim():e+"px"}function Wy(r,e){r=r.style;for(var t in e)if(e.hasOwnProperty(t)){var n=t.indexOf("--")===0,i=Ny(t,e[t],n);t==="float"&&(t="cssFloat"),n?r.setProperty(t,i):r[t]=i}}var Ax=Ct({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 bd(r,e){if(e){if(Ax[r]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(ee(137,r));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(ee(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(ee(61))}if(e.style!=null&&typeof e.style!="object")throw Error(ee(62))}}function Cd(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 xd=null;function Kh(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var Sd=null,Zs=null,Ks=null;function Qp(r){if(r=Oa(r)){if(typeof Sd!="function")throw Error(ee(280));var e=r.stateNode;e&&(e=Cu(e),Sd(r.stateNode,r.type,e))}}function Hy(r){Zs?Ks?Ks.push(r):Ks=[r]:Zs=r}function Vy(){if(Zs){var r=Zs,e=Ks;if(Ks=Zs=null,Qp(r),e)for(r=0;r<e.length;r++)Qp(e[r])}}function jy(r,e){return r(e)}function Yy(){}var gc=!1;function Gy(r,e,t){if(gc)return r(e,t);gc=!0;try{return jy(r,e,t)}finally{gc=!1,(Zs!==null||Ks!==null)&&(Yy(),Vy())}}function ma(r,e){var t=r.stateNode;if(t===null)return null;var n=Cu(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(ee(231,e,typeof t));return t}var Id=!1;if(ni)try{var Ro={};Object.defineProperty(Ro,"passive",{get:function(){Id=!0}}),window.addEventListener("test",Ro,Ro),window.removeEventListener("test",Ro,Ro)}catch{Id=!1}function Rx(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 ra=!1,$l=null,Nl=!1,kd=null,Px={onError:function(r){ra=!0,$l=r}};function zx(r,e,t,n,i,s,o,a,l){ra=!1,$l=null,Rx.apply(Px,arguments)}function Dx(r,e,t,n,i,s,o,a,l){if(zx.apply(this,arguments),ra){if(ra){var u=$l;ra=!1,$l=null}else throw Error(ee(198));Nl||(Nl=!0,kd=u)}}function gs(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 Xy(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 Jp(r){if(gs(r)!==r)throw Error(ee(188))}function Ox(r){var e=r.alternate;if(!e){if(e=gs(r),e===null)throw Error(ee(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 Jp(i),r;if(s===n)return Jp(i),e;s=s.sibling}throw Error(ee(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(ee(189))}}if(t.alternate!==n)throw Error(ee(190))}if(t.tag!==3)throw Error(ee(188));return t.stateNode.current===t?r:e}function Zy(r){return r=Ox(r),r!==null?Ky(r):null}function Ky(r){if(r.tag===5||r.tag===6)return r;for(r=r.child;r!==null;){var e=Ky(r);if(e!==null)return e;r=r.sibling}return null}var qy=Qr.unstable_scheduleCallback,eg=Qr.unstable_cancelCallback,Bx=Qr.unstable_shouldYield,Fx=Qr.unstable_requestPaint,Ut=Qr.unstable_now,Lx=Qr.unstable_getCurrentPriorityLevel,qh=Qr.unstable_ImmediatePriority,Qy=Qr.unstable_UserBlockingPriority,Wl=Qr.unstable_NormalPriority,_x=Qr.unstable_LowPriority,Jy=Qr.unstable_IdlePriority,yu=null,Hn=null;function $x(r){if(Hn&&typeof Hn.onCommitFiberRoot=="function")try{Hn.onCommitFiberRoot(yu,r,void 0,(r.current.flags&128)===128)}catch{}}var Tn=Math.clz32?Math.clz32:Hx,Nx=Math.log,Wx=Math.LN2;function Hx(r){return r>>>=0,r===0?32:31-(Nx(r)/Wx|0)|0}var Qa=64,Ja=4194304;function jo(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 Hl(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=jo(a):(s&=o,s!==0&&(n=jo(s)))}else o=t&~i,o!==0?n=jo(o):s!==0&&(n=jo(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-Tn(e),i=1<<t,n|=r[t],e&=~i;return n}function Vx(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 jx(r,e){for(var t=r.suspendedLanes,n=r.pingedLanes,i=r.expirationTimes,s=r.pendingLanes;0<s;){var o=31-Tn(s),a=1<<o,l=i[o];l===-1?(!(a&t)||a&n)&&(i[o]=Vx(a,e)):l<=e&&(r.expiredLanes|=a),s&=~a}}function Ed(r){return r=r.pendingLanes&-1073741825,r!==0?r:r&1073741824?1073741824:0}function e0(){var r=Qa;return Qa<<=1,!(Qa&4194240)&&(Qa=64),r}function mc(r){for(var e=[],t=0;31>t;t++)e.push(r);return e}function za(r,e,t){r.pendingLanes|=e,e!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,e=31-Tn(e),r[e]=t}function Yx(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-Tn(t),s=1<<i;e[i]=0,n[i]=-1,r[i]=-1,t&=~s}}function Qh(r,e){var t=r.entangledLanes|=e;for(r=r.entanglements;t;){var n=31-Tn(t),i=1<<n;i&e|r[n]&e&&(r[n]|=e),t&=~i}}var Xe=0;function t0(r){return r&=-r,1<r?4<r?r&268435455?16:536870912:4:1}var r0,Jh,n0,i0,s0,Md=!1,el=[],Si=null,Ii=null,ki=null,ya=new Map,va=new Map,wi=[],Gx="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 tg(r,e){switch(r){case"focusin":case"focusout":Si=null;break;case"dragenter":case"dragleave":Ii=null;break;case"mouseover":case"mouseout":ki=null;break;case"pointerover":case"pointerout":ya.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":va.delete(e.pointerId)}}function Po(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=Oa(e),e!==null&&Jh(e)),r):(r.eventSystemFlags|=n,e=r.targetContainers,i!==null&&e.indexOf(i)===-1&&e.push(i),r)}function Xx(r,e,t,n,i){switch(e){case"focusin":return Si=Po(Si,r,e,t,n,i),!0;case"dragenter":return Ii=Po(Ii,r,e,t,n,i),!0;case"mouseover":return ki=Po(ki,r,e,t,n,i),!0;case"pointerover":var s=i.pointerId;return ya.set(s,Po(ya.get(s)||null,r,e,t,n,i)),!0;case"gotpointercapture":return s=i.pointerId,va.set(s,Po(va.get(s)||null,r,e,t,n,i)),!0}return!1}function o0(r){var e=rs(r.target);if(e!==null){var t=gs(e);if(t!==null){if(e=t.tag,e===13){if(e=Xy(t),e!==null){r.blockedOn=e,s0(r.priority,function(){n0(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 Sl(r){if(r.blockedOn!==null)return!1;for(var e=r.targetContainers;0<e.length;){var t=Td(r.domEventName,r.eventSystemFlags,e[0],r.nativeEvent);if(t===null){t=r.nativeEvent;var n=new t.constructor(t.type,t);xd=n,t.target.dispatchEvent(n),xd=null}else return e=Oa(t),e!==null&&Jh(e),r.blockedOn=t,!1;e.shift()}return!0}function rg(r,e,t){Sl(r)&&t.delete(e)}function Zx(){Md=!1,Si!==null&&Sl(Si)&&(Si=null),Ii!==null&&Sl(Ii)&&(Ii=null),ki!==null&&Sl(ki)&&(ki=null),ya.forEach(rg),va.forEach(rg)}function zo(r,e){r.blockedOn===e&&(r.blockedOn=null,Md||(Md=!0,Qr.unstable_scheduleCallback(Qr.unstable_NormalPriority,Zx)))}function wa(r){function e(i){return zo(i,r)}if(0<el.length){zo(el[0],r);for(var t=1;t<el.length;t++){var n=el[t];n.blockedOn===r&&(n.blockedOn=null)}}for(Si!==null&&zo(Si,r),Ii!==null&&zo(Ii,r),ki!==null&&zo(ki,r),ya.forEach(e),va.forEach(e),t=0;t<wi.length;t++)n=wi[t],n.blockedOn===r&&(n.blockedOn=null);for(;0<wi.length&&(t=wi[0],t.blockedOn===null);)o0(t),t.blockedOn===null&&wi.shift()}var qs=ai.ReactCurrentBatchConfig,Vl=!0;function Kx(r,e,t,n){var i=Xe,s=qs.transition;qs.transition=null;try{Xe=1,ef(r,e,t,n)}finally{Xe=i,qs.transition=s}}function qx(r,e,t,n){var i=Xe,s=qs.transition;qs.transition=null;try{Xe=4,ef(r,e,t,n)}finally{Xe=i,qs.transition=s}}function ef(r,e,t,n){if(Vl){var i=Td(r,e,t,n);if(i===null)Ec(r,e,n,jl,t),tg(r,n);else if(Xx(i,r,e,t,n))n.stopPropagation();else if(tg(r,n),e&4&&-1<Gx.indexOf(r)){for(;i!==null;){var s=Oa(i);if(s!==null&&r0(s),s=Td(r,e,t,n),s===null&&Ec(r,e,n,jl,t),s===i)break;i=s}i!==null&&n.stopPropagation()}else Ec(r,e,n,null,t)}}var jl=null;function Td(r,e,t,n){if(jl=null,r=Kh(n),r=rs(r),r!==null)if(e=gs(r),e===null)r=null;else if(t=e.tag,t===13){if(r=Xy(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 jl=r,null}function a0(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(Lx()){case qh:return 1;case Qy:return 4;case Wl:case _x:return 16;case Jy:return 536870912;default:return 16}default:return 16}}var Ci=null,tf=null,Il=null;function l0(){if(Il)return Il;var r,e=tf,t=e.length,n,i="value"in Ci?Ci.value:Ci.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 Il=i.slice(r,1<n?1-n:void 0)}function kl(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 tl(){return!0}function ng(){return!1}function en(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)?tl:ng,this.isPropagationStopped=ng,this}return Ct(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=tl)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=tl)},persist:function(){},isPersistent:tl}),e}var go={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},rf=en(go),Da=Ct({},go,{view:0,detail:0}),Qx=en(Da),yc,vc,Do,vu=Ct({},Da,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:nf,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!==Do&&(Do&&r.type==="mousemove"?(yc=r.screenX-Do.screenX,vc=r.screenY-Do.screenY):vc=yc=0,Do=r),yc)},movementY:function(r){return"movementY"in r?r.movementY:vc}}),ig=en(vu),Jx=Ct({},vu,{dataTransfer:0}),e2=en(Jx),t2=Ct({},Da,{relatedTarget:0}),wc=en(t2),r2=Ct({},go,{animationName:0,elapsedTime:0,pseudoElement:0}),n2=en(r2),i2=Ct({},go,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),s2=en(i2),o2=Ct({},go,{data:0}),sg=en(o2),a2={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},l2={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"},u2={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function c2(r){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(r):(r=u2[r])?!!e[r]:!1}function nf(){return c2}var d2=Ct({},Da,{key:function(r){if(r.key){var e=a2[r.key]||r.key;if(e!=="Unidentified")return e}return r.type==="keypress"?(r=kl(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?l2[r.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:nf,charCode:function(r){return r.type==="keypress"?kl(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?kl(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),h2=en(d2),f2=Ct({},vu,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),og=en(f2),p2=Ct({},Da,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:nf}),g2=en(p2),m2=Ct({},go,{propertyName:0,elapsedTime:0,pseudoElement:0}),y2=en(m2),v2=Ct({},vu,{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}),w2=en(v2),b2=[9,13,27,32],sf=ni&&"CompositionEvent"in window,na=null;ni&&"documentMode"in document&&(na=document.documentMode);var C2=ni&&"TextEvent"in window&&!na,u0=ni&&(!sf||na&&8<na&&11>=na),ag=" ",lg=!1;function c0(r,e){switch(r){case"keyup":return b2.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function d0(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var Bs=!1;function x2(r,e){switch(r){case"compositionend":return d0(e);case"keypress":return e.which!==32?null:(lg=!0,ag);case"textInput":return r=e.data,r===ag&&lg?null:r;default:return null}}function S2(r,e){if(Bs)return r==="compositionend"||!sf&&c0(r,e)?(r=l0(),Il=tf=Ci=null,Bs=!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 u0&&e.locale!=="ko"?null:e.data;default:return null}}var I2={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 ug(r){var e=r&&r.nodeName&&r.nodeName.toLowerCase();return e==="input"?!!I2[r.type]:e==="textarea"}function h0(r,e,t,n){Hy(n),e=Yl(e,"onChange"),0<e.length&&(t=new rf("onChange","change",null,t,n),r.push({event:t,listeners:e}))}var ia=null,ba=null;function k2(r){S0(r,0)}function wu(r){var e=_s(r);if(By(e))return r}function E2(r,e){if(r==="change")return e}var f0=!1;if(ni){var bc;if(ni){var Cc="oninput"in document;if(!Cc){var cg=document.createElement("div");cg.setAttribute("oninput","return;"),Cc=typeof cg.oninput=="function"}bc=Cc}else bc=!1;f0=bc&&(!document.documentMode||9<document.documentMode)}function dg(){ia&&(ia.detachEvent("onpropertychange",p0),ba=ia=null)}function p0(r){if(r.propertyName==="value"&&wu(ba)){var e=[];h0(e,ba,r,Kh(r)),Gy(k2,e)}}function M2(r,e,t){r==="focusin"?(dg(),ia=e,ba=t,ia.attachEvent("onpropertychange",p0)):r==="focusout"&&dg()}function T2(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return wu(ba)}function U2(r,e){if(r==="click")return wu(e)}function A2(r,e){if(r==="input"||r==="change")return wu(e)}function R2(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var An=typeof Object.is=="function"?Object.is:R2;function Ca(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(!cd.call(e,i)||!An(r[i],e[i]))return!1}return!0}function hg(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function fg(r,e){var t=hg(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=hg(t)}}function g0(r,e){return r&&e?r===e?!0:r&&r.nodeType===3?!1:e&&e.nodeType===3?g0(r,e.parentNode):"contains"in r?r.contains(e):r.compareDocumentPosition?!!(r.compareDocumentPosition(e)&16):!1:!1}function m0(){for(var r=window,e=_l();e instanceof r.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)r=e.contentWindow;else break;e=_l(r.document)}return e}function of(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 P2(r){var e=m0(),t=r.focusedElem,n=r.selectionRange;if(e!==t&&t&&t.ownerDocument&&g0(t.ownerDocument.documentElement,t)){if(n!==null&&of(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=fg(t,s);var o=fg(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 z2=ni&&"documentMode"in document&&11>=document.documentMode,Fs=null,Ud=null,sa=null,Ad=!1;function pg(r,e,t){var n=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;Ad||Fs==null||Fs!==_l(n)||(n=Fs,"selectionStart"in n&&of(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}),sa&&Ca(sa,n)||(sa=n,n=Yl(Ud,"onSelect"),0<n.length&&(e=new rf("onSelect","select",null,e,t),r.push({event:e,listeners:n}),e.target=Fs)))}function rl(r,e){var t={};return t[r.toLowerCase()]=e.toLowerCase(),t["Webkit"+r]="webkit"+e,t["Moz"+r]="moz"+e,t}var Ls={animationend:rl("Animation","AnimationEnd"),animationiteration:rl("Animation","AnimationIteration"),animationstart:rl("Animation","AnimationStart"),transitionend:rl("Transition","TransitionEnd")},xc={},y0={};ni&&(y0=document.createElement("div").style,"AnimationEvent"in window||(delete Ls.animationend.animation,delete Ls.animationiteration.animation,delete Ls.animationstart.animation),"TransitionEvent"in window||delete Ls.transitionend.transition);function bu(r){if(xc[r])return xc[r];if(!Ls[r])return r;var e=Ls[r],t;for(t in e)if(e.hasOwnProperty(t)&&t in y0)return xc[r]=e[t];return r}var v0=bu("animationend"),w0=bu("animationiteration"),b0=bu("animationstart"),C0=bu("transitionend"),x0=new Map,gg="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 Fi(r,e){x0.set(r,e),ps(e,[r])}for(var Sc=0;Sc<gg.length;Sc++){var Ic=gg[Sc],D2=Ic.toLowerCase(),O2=Ic[0].toUpperCase()+Ic.slice(1);Fi(D2,"on"+O2)}Fi(v0,"onAnimationEnd");Fi(w0,"onAnimationIteration");Fi(b0,"onAnimationStart");Fi("dblclick","onDoubleClick");Fi("focusin","onFocus");Fi("focusout","onBlur");Fi(C0,"onTransitionEnd");to("onMouseEnter",["mouseout","mouseover"]);to("onMouseLeave",["mouseout","mouseover"]);to("onPointerEnter",["pointerout","pointerover"]);to("onPointerLeave",["pointerout","pointerover"]);ps("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));ps("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));ps("onBeforeInput",["compositionend","keypress","textInput","paste"]);ps("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));ps("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));ps("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Yo="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(" "),B2=new Set("cancel close invalid load scroll toggle".split(" ").concat(Yo));function mg(r,e,t){var n=r.type||"unknown-event";r.currentTarget=t,Dx(n,e,void 0,r),r.currentTarget=null}function S0(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;mg(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;mg(i,a,u),s=l}}}if(Nl)throw r=kd,Nl=!1,kd=null,r}function at(r,e){var t=e[Od];t===void 0&&(t=e[Od]=new Set);var n=r+"__bubble";t.has(n)||(I0(e,r,2,!1),t.add(n))}function kc(r,e,t){var n=0;e&&(n|=4),I0(t,r,n,e)}var nl="_reactListening"+Math.random().toString(36).slice(2);function xa(r){if(!r[nl]){r[nl]=!0,Ry.forEach(function(t){t!=="selectionchange"&&(B2.has(t)||kc(t,!1,r),kc(t,!0,r))});var e=r.nodeType===9?r:r.ownerDocument;e===null||e[nl]||(e[nl]=!0,kc("selectionchange",!1,e))}}function I0(r,e,t,n){switch(a0(e)){case 1:var i=Kx;break;case 4:i=qx;break;default:i=ef}t=i.bind(null,e,t,r),i=void 0,!Id||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 Ec(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=rs(a),o===null)return;if(l=o.tag,l===5||l===6){n=s=o;continue e}a=a.parentNode}}n=n.return}Gy(function(){var u=s,c=Kh(t),d=[];e:{var h=x0.get(r);if(h!==void 0){var f=rf,p=r;switch(r){case"keypress":if(kl(t)===0)break e;case"keydown":case"keyup":f=h2;break;case"focusin":p="focus",f=wc;break;case"focusout":p="blur",f=wc;break;case"beforeblur":case"afterblur":f=wc;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=ig;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":f=e2;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":f=g2;break;case v0:case w0:case b0:f=n2;break;case C0:f=y2;break;case"scroll":f=Qx;break;case"wheel":f=w2;break;case"copy":case"cut":case"paste":f=s2;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":f=og}var g=(e&4)!==0,x=!g&&r==="scroll",y=g?h!==null?h+"Capture":null:h;g=[];for(var m=u,v;m!==null;){v=m;var b=v.stateNode;if(v.tag===5&&b!==null&&(v=b,y!==null&&(b=ma(m,y),b!=null&&g.push(Sa(m,b,v)))),x)break;m=m.return}0<g.length&&(h=new f(h,p,null,t,c),d.push({event:h,listeners:g}))}}if(!(e&7)){e:{if(h=r==="mouseover"||r==="pointerover",f=r==="mouseout"||r==="pointerout",h&&t!==xd&&(p=t.relatedTarget||t.fromElement)&&(rs(p)||p[ii]))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?rs(p):null,p!==null&&(x=gs(p),p!==x||p.tag!==5&&p.tag!==6)&&(p=null)):(f=null,p=u),f!==p)){if(g=ig,b="onMouseLeave",y="onMouseEnter",m="mouse",(r==="pointerout"||r==="pointerover")&&(g=og,b="onPointerLeave",y="onPointerEnter",m="pointer"),x=f==null?h:_s(f),v=p==null?h:_s(p),h=new g(b,m+"leave",f,t,c),h.target=x,h.relatedTarget=v,b=null,rs(c)===u&&(g=new g(y,m+"enter",p,t,c),g.target=v,g.relatedTarget=x,b=g),x=b,f&&p)t:{for(g=f,y=p,m=0,v=g;v;v=Ts(v))m++;for(v=0,b=y;b;b=Ts(b))v++;for(;0<m-v;)g=Ts(g),m--;for(;0<v-m;)y=Ts(y),v--;for(;m--;){if(g===y||y!==null&&g===y.alternate)break t;g=Ts(g),y=Ts(y)}g=null}else g=null;f!==null&&yg(d,h,f,g,!1),p!==null&&x!==null&&yg(d,x,p,g,!0)}}e:{if(h=u?_s(u):window,f=h.nodeName&&h.nodeName.toLowerCase(),f==="select"||f==="input"&&h.type==="file")var I=E2;else if(ug(h))if(f0)I=A2;else{I=T2;var S=M2}else(f=h.nodeName)&&f.toLowerCase()==="input"&&(h.type==="checkbox"||h.type==="radio")&&(I=U2);if(I&&(I=I(r,u))){h0(d,I,t,c);break e}S&&S(r,h,u),r==="focusout"&&(S=h._wrapperState)&&S.controlled&&h.type==="number"&&yd(h,"number",h.value)}switch(S=u?_s(u):window,r){case"focusin":(ug(S)||S.contentEditable==="true")&&(Fs=S,Ud=u,sa=null);break;case"focusout":sa=Ud=Fs=null;break;case"mousedown":Ad=!0;break;case"contextmenu":case"mouseup":case"dragend":Ad=!1,pg(d,t,c);break;case"selectionchange":if(z2)break;case"keydown":case"keyup":pg(d,t,c)}var M;if(sf)e:{switch(r){case"compositionstart":var U="onCompositionStart";break e;case"compositionend":U="onCompositionEnd";break e;case"compositionupdate":U="onCompositionUpdate";break e}U=void 0}else Bs?c0(r,t)&&(U="onCompositionEnd"):r==="keydown"&&t.keyCode===229&&(U="onCompositionStart");U&&(u0&&t.locale!=="ko"&&(Bs||U!=="onCompositionStart"?U==="onCompositionEnd"&&Bs&&(M=l0()):(Ci=c,tf="value"in Ci?Ci.value:Ci.textContent,Bs=!0)),S=Yl(u,U),0<S.length&&(U=new sg(U,r,null,t,c),d.push({event:U,listeners:S}),M?U.data=M:(M=d0(t),M!==null&&(U.data=M)))),(M=C2?x2(r,t):S2(r,t))&&(u=Yl(u,"onBeforeInput"),0<u.length&&(c=new sg("onBeforeInput","beforeinput",null,t,c),d.push({event:c,listeners:u}),c.data=M))}S0(d,e)})}function Sa(r,e,t){return{instance:r,listener:e,currentTarget:t}}function Yl(r,e){for(var t=e+"Capture",n=[];r!==null;){var i=r,s=i.stateNode;i.tag===5&&s!==null&&(i=s,s=ma(r,t),s!=null&&n.unshift(Sa(r,s,i)),s=ma(r,e),s!=null&&n.push(Sa(r,s,i))),r=r.return}return n}function Ts(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5);return r||null}function yg(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=ma(t,s),l!=null&&o.unshift(Sa(t,l,a))):i||(l=ma(t,s),l!=null&&o.push(Sa(t,l,a)))),t=t.return}o.length!==0&&r.push({event:e,listeners:o})}var F2=/\r\n?/g,L2=/\u0000|\uFFFD/g;function vg(r){return(typeof r=="string"?r:""+r).replace(F2,`
|
|
38
|
-
`).replace(L2,"")}function il(r,e,t){if(e=vg(e),vg(r)!==e&&t)throw Error(ee(425))}function Gl(){}var Rd=null,Pd=null;function zd(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 Dd=typeof setTimeout=="function"?setTimeout:void 0,_2=typeof clearTimeout=="function"?clearTimeout:void 0,wg=typeof Promise=="function"?Promise:void 0,$2=typeof queueMicrotask=="function"?queueMicrotask:typeof wg<"u"?function(r){return wg.resolve(null).then(r).catch(N2)}:Dd;function N2(r){setTimeout(function(){throw r})}function Mc(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),wa(e);return}n--}else t!=="$"&&t!=="$?"&&t!=="$!"||n++;t=i}while(t);wa(e)}function Ei(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 bg(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 mo=Math.random().toString(36).slice(2),Wn="__reactFiber$"+mo,Ia="__reactProps$"+mo,ii="__reactContainer$"+mo,Od="__reactEvents$"+mo,W2="__reactListeners$"+mo,H2="__reactHandles$"+mo;function rs(r){var e=r[Wn];if(e)return e;for(var t=r.parentNode;t;){if(e=t[ii]||t[Wn]){if(t=e.alternate,e.child!==null||t!==null&&t.child!==null)for(r=bg(r);r!==null;){if(t=r[Wn])return t;r=bg(r)}return e}r=t,t=r.parentNode}return null}function Oa(r){return r=r[Wn]||r[ii],!r||r.tag!==5&&r.tag!==6&&r.tag!==13&&r.tag!==3?null:r}function _s(r){if(r.tag===5||r.tag===6)return r.stateNode;throw Error(ee(33))}function Cu(r){return r[Ia]||null}var Bd=[],$s=-1;function Li(r){return{current:r}}function ut(r){0>$s||(r.current=Bd[$s],Bd[$s]=null,$s--)}function rt(r,e){$s++,Bd[$s]=r.current,r.current=e}var Oi={},vr=Li(Oi),Lr=Li(!1),ls=Oi;function ro(r,e){var t=r.type.contextTypes;if(!t)return Oi;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 Xl(){ut(Lr),ut(vr)}function Cg(r,e,t){if(vr.current!==Oi)throw Error(ee(168));rt(vr,e),rt(Lr,t)}function k0(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(ee(108,Mx(r)||"Unknown",i));return Ct({},t,n)}function Zl(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||Oi,ls=vr.current,rt(vr,r),rt(Lr,Lr.current),!0}function xg(r,e,t){var n=r.stateNode;if(!n)throw Error(ee(169));t?(r=k0(r,e,ls),n.__reactInternalMemoizedMergedChildContext=r,ut(Lr),ut(vr),rt(vr,r)):ut(Lr),rt(Lr,t)}var qn=null,xu=!1,Tc=!1;function E0(r){qn===null?qn=[r]:qn.push(r)}function V2(r){xu=!0,E0(r)}function _i(){if(!Tc&&qn!==null){Tc=!0;var r=0,e=Xe;try{var t=qn;for(Xe=1;r<t.length;r++){var n=t[r];do n=n(!0);while(n!==null)}qn=null,xu=!1}catch(i){throw qn!==null&&(qn=qn.slice(r+1)),qy(qh,_i),i}finally{Xe=e,Tc=!1}}return null}var Ns=[],Ws=0,Kl=null,ql=0,un=[],cn=0,us=null,Qn=1,Jn="";function Zi(r,e){Ns[Ws++]=ql,Ns[Ws++]=Kl,Kl=r,ql=e}function M0(r,e,t){un[cn++]=Qn,un[cn++]=Jn,un[cn++]=us,us=r;var n=Qn;r=Jn;var i=32-Tn(n)-1;n&=~(1<<i),t+=1;var s=32-Tn(e)+i;if(30<s){var o=i-i%5;s=(n&(1<<o)-1).toString(32),n>>=o,i-=o,Qn=1<<32-Tn(e)+i|t<<i|n,Jn=s+r}else Qn=1<<s|t<<i|n,Jn=r}function af(r){r.return!==null&&(Zi(r,1),M0(r,1,0))}function lf(r){for(;r===Kl;)Kl=Ns[--Ws],Ns[Ws]=null,ql=Ns[--Ws],Ns[Ws]=null;for(;r===us;)us=un[--cn],un[cn]=null,Jn=un[--cn],un[cn]=null,Qn=un[--cn],un[cn]=null}var Kr=null,Zr=null,gt=!1,En=null;function T0(r,e){var t=hn(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 Sg(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,Kr=r,Zr=Ei(e.firstChild),!0):!1;case 6:return e=r.pendingProps===""||e.nodeType!==3?null:e,e!==null?(r.stateNode=e,Kr=r,Zr=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(t=us!==null?{id:Qn,overflow:Jn}:null,r.memoizedState={dehydrated:e,treeContext:t,retryLane:1073741824},t=hn(18,null,null,0),t.stateNode=e,t.return=r,r.child=t,Kr=r,Zr=null,!0):!1;default:return!1}}function Fd(r){return(r.mode&1)!==0&&(r.flags&128)===0}function Ld(r){if(gt){var e=Zr;if(e){var t=e;if(!Sg(r,e)){if(Fd(r))throw Error(ee(418));e=Ei(t.nextSibling);var n=Kr;e&&Sg(r,e)?T0(n,t):(r.flags=r.flags&-4097|2,gt=!1,Kr=r)}}else{if(Fd(r))throw Error(ee(418));r.flags=r.flags&-4097|2,gt=!1,Kr=r}}}function Ig(r){for(r=r.return;r!==null&&r.tag!==5&&r.tag!==3&&r.tag!==13;)r=r.return;Kr=r}function sl(r){if(r!==Kr)return!1;if(!gt)return Ig(r),gt=!0,!1;var e;if((e=r.tag!==3)&&!(e=r.tag!==5)&&(e=r.type,e=e!=="head"&&e!=="body"&&!zd(r.type,r.memoizedProps)),e&&(e=Zr)){if(Fd(r))throw U0(),Error(ee(418));for(;e;)T0(r,e),e=Ei(e.nextSibling)}if(Ig(r),r.tag===13){if(r=r.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(ee(317));e:{for(r=r.nextSibling,e=0;r;){if(r.nodeType===8){var t=r.data;if(t==="/$"){if(e===0){Zr=Ei(r.nextSibling);break e}e--}else t!=="$"&&t!=="$!"&&t!=="$?"||e++}r=r.nextSibling}Zr=null}}else Zr=Kr?Ei(r.stateNode.nextSibling):null;return!0}function U0(){for(var r=Zr;r;)r=Ei(r.nextSibling)}function no(){Zr=Kr=null,gt=!1}function uf(r){En===null?En=[r]:En.push(r)}var j2=ai.ReactCurrentBatchConfig;function Oo(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(ee(309));var n=t.stateNode}if(!n)throw Error(ee(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(ee(284));if(!t._owner)throw Error(ee(290,r))}return r}function ol(r,e){throw r=Object.prototype.toString.call(e),Error(ee(31,r==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":r))}function kg(r){var e=r._init;return e(r._payload)}function A0(r){function e(y,m){if(r){var v=y.deletions;v===null?(y.deletions=[m],y.flags|=16):v.push(m)}}function t(y,m){if(!r)return null;for(;m!==null;)e(y,m),m=m.sibling;return null}function n(y,m){for(y=new Map;m!==null;)m.key!==null?y.set(m.key,m):y.set(m.index,m),m=m.sibling;return y}function i(y,m){return y=Ai(y,m),y.index=0,y.sibling=null,y}function s(y,m,v){return y.index=v,r?(v=y.alternate,v!==null?(v=v.index,v<m?(y.flags|=2,m):v):(y.flags|=2,m)):(y.flags|=1048576,m)}function o(y){return r&&y.alternate===null&&(y.flags|=2),y}function a(y,m,v,b){return m===null||m.tag!==6?(m=Oc(v,y.mode,b),m.return=y,m):(m=i(m,v),m.return=y,m)}function l(y,m,v,b){var I=v.type;return I===Os?c(y,m,v.props.children,b,v.key):m!==null&&(m.elementType===I||typeof I=="object"&&I!==null&&I.$$typeof===mi&&kg(I)===m.type)?(b=i(m,v.props),b.ref=Oo(y,m,v),b.return=y,b):(b=Pl(v.type,v.key,v.props,null,y.mode,b),b.ref=Oo(y,m,v),b.return=y,b)}function u(y,m,v,b){return m===null||m.tag!==4||m.stateNode.containerInfo!==v.containerInfo||m.stateNode.implementation!==v.implementation?(m=Bc(v,y.mode,b),m.return=y,m):(m=i(m,v.children||[]),m.return=y,m)}function c(y,m,v,b,I){return m===null||m.tag!==7?(m=os(v,y.mode,b,I),m.return=y,m):(m=i(m,v),m.return=y,m)}function d(y,m,v){if(typeof m=="string"&&m!==""||typeof m=="number")return m=Oc(""+m,y.mode,v),m.return=y,m;if(typeof m=="object"&&m!==null){switch(m.$$typeof){case Za:return v=Pl(m.type,m.key,m.props,null,y.mode,v),v.ref=Oo(y,null,m),v.return=y,v;case Ds:return m=Bc(m,y.mode,v),m.return=y,m;case mi:var b=m._init;return d(y,b(m._payload),v)}if(Vo(m)||Ao(m))return m=os(m,y.mode,v,null),m.return=y,m;ol(y,m)}return null}function h(y,m,v,b){var I=m!==null?m.key:null;if(typeof v=="string"&&v!==""||typeof v=="number")return I!==null?null:a(y,m,""+v,b);if(typeof v=="object"&&v!==null){switch(v.$$typeof){case Za:return v.key===I?l(y,m,v,b):null;case Ds:return v.key===I?u(y,m,v,b):null;case mi:return I=v._init,h(y,m,I(v._payload),b)}if(Vo(v)||Ao(v))return I!==null?null:c(y,m,v,b,null);ol(y,v)}return null}function f(y,m,v,b,I){if(typeof b=="string"&&b!==""||typeof b=="number")return y=y.get(v)||null,a(m,y,""+b,I);if(typeof b=="object"&&b!==null){switch(b.$$typeof){case Za:return y=y.get(b.key===null?v:b.key)||null,l(m,y,b,I);case Ds:return y=y.get(b.key===null?v:b.key)||null,u(m,y,b,I);case mi:var S=b._init;return f(y,m,v,S(b._payload),I)}if(Vo(b)||Ao(b))return y=y.get(v)||null,c(m,y,b,I,null);ol(m,b)}return null}function p(y,m,v,b){for(var I=null,S=null,M=m,U=m=0,z=null;M!==null&&U<v.length;U++){M.index>U?(z=M,M=null):z=M.sibling;var O=h(y,M,v[U],b);if(O===null){M===null&&(M=z);break}r&&M&&O.alternate===null&&e(y,M),m=s(O,m,U),S===null?I=O:S.sibling=O,S=O,M=z}if(U===v.length)return t(y,M),gt&&Zi(y,U),I;if(M===null){for(;U<v.length;U++)M=d(y,v[U],b),M!==null&&(m=s(M,m,U),S===null?I=M:S.sibling=M,S=M);return gt&&Zi(y,U),I}for(M=n(y,M);U<v.length;U++)z=f(M,y,U,v[U],b),z!==null&&(r&&z.alternate!==null&&M.delete(z.key===null?U:z.key),m=s(z,m,U),S===null?I=z:S.sibling=z,S=z);return r&&M.forEach(function(R){return e(y,R)}),gt&&Zi(y,U),I}function g(y,m,v,b){var I=Ao(v);if(typeof I!="function")throw Error(ee(150));if(v=I.call(v),v==null)throw Error(ee(151));for(var S=I=null,M=m,U=m=0,z=null,O=v.next();M!==null&&!O.done;U++,O=v.next()){M.index>U?(z=M,M=null):z=M.sibling;var R=h(y,M,O.value,b);if(R===null){M===null&&(M=z);break}r&&M&&R.alternate===null&&e(y,M),m=s(R,m,U),S===null?I=R:S.sibling=R,S=R,M=z}if(O.done)return t(y,M),gt&&Zi(y,U),I;if(M===null){for(;!O.done;U++,O=v.next())O=d(y,O.value,b),O!==null&&(m=s(O,m,U),S===null?I=O:S.sibling=O,S=O);return gt&&Zi(y,U),I}for(M=n(y,M);!O.done;U++,O=v.next())O=f(M,y,U,O.value,b),O!==null&&(r&&O.alternate!==null&&M.delete(O.key===null?U:O.key),m=s(O,m,U),S===null?I=O:S.sibling=O,S=O);return r&&M.forEach(function(B){return e(y,B)}),gt&&Zi(y,U),I}function x(y,m,v,b){if(typeof v=="object"&&v!==null&&v.type===Os&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case Za:e:{for(var I=v.key,S=m;S!==null;){if(S.key===I){if(I=v.type,I===Os){if(S.tag===7){t(y,S.sibling),m=i(S,v.props.children),m.return=y,y=m;break e}}else if(S.elementType===I||typeof I=="object"&&I!==null&&I.$$typeof===mi&&kg(I)===S.type){t(y,S.sibling),m=i(S,v.props),m.ref=Oo(y,S,v),m.return=y,y=m;break e}t(y,S);break}else e(y,S);S=S.sibling}v.type===Os?(m=os(v.props.children,y.mode,b,v.key),m.return=y,y=m):(b=Pl(v.type,v.key,v.props,null,y.mode,b),b.ref=Oo(y,m,v),b.return=y,y=b)}return o(y);case Ds:e:{for(S=v.key;m!==null;){if(m.key===S)if(m.tag===4&&m.stateNode.containerInfo===v.containerInfo&&m.stateNode.implementation===v.implementation){t(y,m.sibling),m=i(m,v.children||[]),m.return=y,y=m;break e}else{t(y,m);break}else e(y,m);m=m.sibling}m=Bc(v,y.mode,b),m.return=y,y=m}return o(y);case mi:return S=v._init,x(y,m,S(v._payload),b)}if(Vo(v))return p(y,m,v,b);if(Ao(v))return g(y,m,v,b);ol(y,v)}return typeof v=="string"&&v!==""||typeof v=="number"?(v=""+v,m!==null&&m.tag===6?(t(y,m.sibling),m=i(m,v),m.return=y,y=m):(t(y,m),m=Oc(v,y.mode,b),m.return=y,y=m),o(y)):t(y,m)}return x}var io=A0(!0),R0=A0(!1),Ql=Li(null),Jl=null,Hs=null,cf=null;function df(){cf=Hs=Jl=null}function hf(r){var e=Ql.current;ut(Ql),r._currentValue=e}function _d(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 Qs(r,e){Jl=r,cf=Hs=null,r=r.dependencies,r!==null&&r.firstContext!==null&&(r.lanes&e&&(Fr=!0),r.firstContext=null)}function pn(r){var e=r._currentValue;if(cf!==r)if(r={context:r,memoizedValue:e,next:null},Hs===null){if(Jl===null)throw Error(ee(308));Hs=r,Jl.dependencies={lanes:0,firstContext:r}}else Hs=Hs.next=r;return e}var ns=null;function ff(r){ns===null?ns=[r]:ns.push(r)}function P0(r,e,t,n){var i=e.interleaved;return i===null?(t.next=t,ff(e)):(t.next=i.next,i.next=t),e.interleaved=t,si(r,n)}function si(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 yi=!1;function pf(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function z0(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 ei(r,e){return{eventTime:r,lane:e,tag:0,payload:null,callback:null,next:null}}function Mi(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,si(r,t)}return i=n.interleaved,i===null?(e.next=e,ff(n)):(e.next=i.next,i.next=e),n.interleaved=e,si(r,t)}function El(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,Qh(r,t)}}function Eg(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 eu(r,e,t,n){var i=r.updateQueue;yi=!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,g=a;switch(h=e,f=t,g.tag){case 1:if(p=g.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=g.payload,h=typeof p=="function"?p.call(f,d,h):p,h==null)break e;d=Ct({},d,h);break e;case 2:yi=!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);ds|=o,r.lanes=o,r.memoizedState=d}}function Mg(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(ee(191,i));i.call(n)}}}var Ba={},Vn=Li(Ba),ka=Li(Ba),Ea=Li(Ba);function is(r){if(r===Ba)throw Error(ee(174));return r}function gf(r,e){switch(rt(Ea,e),rt(ka,r),rt(Vn,Ba),r=e.nodeType,r){case 9:case 11:e=(e=e.documentElement)?e.namespaceURI:wd(null,"");break;default:r=r===8?e.parentNode:e,e=r.namespaceURI||null,r=r.tagName,e=wd(e,r)}ut(Vn),rt(Vn,e)}function so(){ut(Vn),ut(ka),ut(Ea)}function D0(r){is(Ea.current);var e=is(Vn.current),t=wd(e,r.type);e!==t&&(rt(ka,r),rt(Vn,t))}function mf(r){ka.current===r&&(ut(Vn),ut(ka))}var wt=Li(0);function tu(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 yf(){for(var r=0;r<Uc.length;r++)Uc[r]._workInProgressVersionPrimary=null;Uc.length=0}var Ml=ai.ReactCurrentDispatcher,Ac=ai.ReactCurrentBatchConfig,cs=0,bt=null,Nt=null,er=null,ru=!1,oa=!1,Ma=0,Y2=0;function pr(){throw Error(ee(321))}function vf(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 wf(r,e,t,n,i,s){if(cs=s,bt=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,Ml.current=r===null||r.memoizedState===null?K2:q2,r=t(n,i),oa){s=0;do{if(oa=!1,Ma=0,25<=s)throw Error(ee(301));s+=1,er=Nt=null,e.updateQueue=null,Ml.current=Q2,r=t(n,i)}while(oa)}if(Ml.current=nu,e=Nt!==null&&Nt.next!==null,cs=0,er=Nt=bt=null,ru=!1,e)throw Error(ee(300));return r}function bf(){var r=Ma!==0;return Ma=0,r}function Nn(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return er===null?bt.memoizedState=er=r:er=er.next=r,er}function gn(){if(Nt===null){var r=bt.alternate;r=r!==null?r.memoizedState:null}else r=Nt.next;var e=er===null?bt.memoizedState:er.next;if(e!==null)er=e,Nt=r;else{if(r===null)throw Error(ee(310));Nt=r,r={memoizedState:Nt.memoizedState,baseState:Nt.baseState,baseQueue:Nt.baseQueue,queue:Nt.queue,next:null},er===null?bt.memoizedState=er=r:er=er.next=r}return er}function Ta(r,e){return typeof e=="function"?e(r):e}function Rc(r){var e=gn(),t=e.queue;if(t===null)throw Error(ee(311));t.lastRenderedReducer=r;var n=Nt,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((cs&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,bt.lanes|=c,ds|=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,bt.lanes|=s,ds|=s,i=i.next;while(i!==r)}else i===null&&(t.lanes=0);return[e.memoizedState,t.dispatch]}function Pc(r){var e=gn(),t=e.queue;if(t===null)throw Error(ee(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 O0(){}function B0(r,e){var t=bt,n=gn(),i=e(),s=!An(n.memoizedState,i);if(s&&(n.memoizedState=i,Fr=!0),n=n.queue,Cf(_0.bind(null,t,n,r),[r]),n.getSnapshot!==e||s||er!==null&&er.memoizedState.tag&1){if(t.flags|=2048,Ua(9,L0.bind(null,t,n,i,e),void 0,null),tr===null)throw Error(ee(349));cs&30||F0(t,e,i)}return i}function F0(r,e,t){r.flags|=16384,r={getSnapshot:e,value:t},e=bt.updateQueue,e===null?(e={lastEffect:null,stores:null},bt.updateQueue=e,e.stores=[r]):(t=e.stores,t===null?e.stores=[r]:t.push(r))}function L0(r,e,t,n){e.value=t,e.getSnapshot=n,$0(e)&&N0(r)}function _0(r,e,t){return t(function(){$0(e)&&N0(r)})}function $0(r){var e=r.getSnapshot;r=r.value;try{var t=e();return!An(r,t)}catch{return!0}}function N0(r){var e=si(r,1);e!==null&&Un(e,r,1,-1)}function Tg(r){var e=Nn();return typeof r=="function"&&(r=r()),e.memoizedState=e.baseState=r,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ta,lastRenderedState:r},e.queue=r,r=r.dispatch=Z2.bind(null,bt,r),[e.memoizedState,r]}function Ua(r,e,t,n){return r={tag:r,create:e,destroy:t,deps:n,next:null},e=bt.updateQueue,e===null?(e={lastEffect:null,stores:null},bt.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 W0(){return gn().memoizedState}function Tl(r,e,t,n){var i=Nn();bt.flags|=r,i.memoizedState=Ua(1|e,t,void 0,n===void 0?null:n)}function Su(r,e,t,n){var i=gn();n=n===void 0?null:n;var s=void 0;if(Nt!==null){var o=Nt.memoizedState;if(s=o.destroy,n!==null&&vf(n,o.deps)){i.memoizedState=Ua(e,t,s,n);return}}bt.flags|=r,i.memoizedState=Ua(1|e,t,s,n)}function Ug(r,e){return Tl(8390656,8,r,e)}function Cf(r,e){return Su(2048,8,r,e)}function H0(r,e){return Su(4,2,r,e)}function V0(r,e){return Su(4,4,r,e)}function j0(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 Y0(r,e,t){return t=t!=null?t.concat([r]):null,Su(4,4,j0.bind(null,e,r),t)}function xf(){}function G0(r,e){var t=gn();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&vf(e,n[1])?n[0]:(t.memoizedState=[r,e],r)}function X0(r,e){var t=gn();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&vf(e,n[1])?n[0]:(r=r(),t.memoizedState=[r,e],r)}function Z0(r,e,t){return cs&21?(An(t,e)||(t=e0(),bt.lanes|=t,ds|=t,r.baseState=!0),e):(r.baseState&&(r.baseState=!1,Fr=!0),r.memoizedState=t)}function G2(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 K0(){return gn().memoizedState}function X2(r,e,t){var n=Ui(r);if(t={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null},q0(r))Q0(e,t);else if(t=P0(r,e,t,n),t!==null){var i=Tr();Un(t,r,n,i),J0(t,e,n)}}function Z2(r,e,t){var n=Ui(r),i={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null};if(q0(r))Q0(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,ff(e)):(i.next=l.next,l.next=i),e.interleaved=i;return}}catch{}finally{}t=P0(r,e,i,n),t!==null&&(i=Tr(),Un(t,r,n,i),J0(t,e,n))}}function q0(r){var e=r.alternate;return r===bt||e!==null&&e===bt}function Q0(r,e){oa=ru=!0;var t=r.pending;t===null?e.next=e:(e.next=t.next,t.next=e),r.pending=e}function J0(r,e,t){if(t&4194240){var n=e.lanes;n&=r.pendingLanes,t|=n,e.lanes=t,Qh(r,t)}}var nu={readContext:pn,useCallback:pr,useContext:pr,useEffect:pr,useImperativeHandle:pr,useInsertionEffect:pr,useLayoutEffect:pr,useMemo:pr,useReducer:pr,useRef:pr,useState:pr,useDebugValue:pr,useDeferredValue:pr,useTransition:pr,useMutableSource:pr,useSyncExternalStore:pr,useId:pr,unstable_isNewReconciler:!1},K2={readContext:pn,useCallback:function(r,e){return Nn().memoizedState=[r,e===void 0?null:e],r},useContext:pn,useEffect:Ug,useImperativeHandle:function(r,e,t){return t=t!=null?t.concat([r]):null,Tl(4194308,4,j0.bind(null,e,r),t)},useLayoutEffect:function(r,e){return Tl(4194308,4,r,e)},useInsertionEffect:function(r,e){return Tl(4,2,r,e)},useMemo:function(r,e){var t=Nn();return e=e===void 0?null:e,r=r(),t.memoizedState=[r,e],r},useReducer:function(r,e,t){var n=Nn();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=X2.bind(null,bt,r),[n.memoizedState,r]},useRef:function(r){var e=Nn();return r={current:r},e.memoizedState=r},useState:Tg,useDebugValue:xf,useDeferredValue:function(r){return Nn().memoizedState=r},useTransition:function(){var r=Tg(!1),e=r[0];return r=G2.bind(null,r[1]),Nn().memoizedState=r,[e,r]},useMutableSource:function(){},useSyncExternalStore:function(r,e,t){var n=bt,i=Nn();if(gt){if(t===void 0)throw Error(ee(407));t=t()}else{if(t=e(),tr===null)throw Error(ee(349));cs&30||F0(n,e,t)}i.memoizedState=t;var s={value:t,getSnapshot:e};return i.queue=s,Ug(_0.bind(null,n,s,r),[r]),n.flags|=2048,Ua(9,L0.bind(null,n,s,t,e),void 0,null),t},useId:function(){var r=Nn(),e=tr.identifierPrefix;if(gt){var t=Jn,n=Qn;t=(n&~(1<<32-Tn(n)-1)).toString(32)+t,e=":"+e+"R"+t,t=Ma++,0<t&&(e+="H"+t.toString(32)),e+=":"}else t=Y2++,e=":"+e+"r"+t.toString(32)+":";return r.memoizedState=e},unstable_isNewReconciler:!1},q2={readContext:pn,useCallback:G0,useContext:pn,useEffect:Cf,useImperativeHandle:Y0,useInsertionEffect:H0,useLayoutEffect:V0,useMemo:X0,useReducer:Rc,useRef:W0,useState:function(){return Rc(Ta)},useDebugValue:xf,useDeferredValue:function(r){var e=gn();return Z0(e,Nt.memoizedState,r)},useTransition:function(){var r=Rc(Ta)[0],e=gn().memoizedState;return[r,e]},useMutableSource:O0,useSyncExternalStore:B0,useId:K0,unstable_isNewReconciler:!1},Q2={readContext:pn,useCallback:G0,useContext:pn,useEffect:Cf,useImperativeHandle:Y0,useInsertionEffect:H0,useLayoutEffect:V0,useMemo:X0,useReducer:Pc,useRef:W0,useState:function(){return Pc(Ta)},useDebugValue:xf,useDeferredValue:function(r){var e=gn();return Nt===null?e.memoizedState=r:Z0(e,Nt.memoizedState,r)},useTransition:function(){var r=Pc(Ta)[0],e=gn().memoizedState;return[r,e]},useMutableSource:O0,useSyncExternalStore:B0,useId:K0,unstable_isNewReconciler:!1};function xn(r,e){if(r&&r.defaultProps){e=Ct({},e),r=r.defaultProps;for(var t in r)e[t]===void 0&&(e[t]=r[t]);return e}return e}function $d(r,e,t,n){e=r.memoizedState,t=t(n,e),t=t==null?e:Ct({},e,t),r.memoizedState=t,r.lanes===0&&(r.updateQueue.baseState=t)}var Iu={isMounted:function(r){return(r=r._reactInternals)?gs(r)===r:!1},enqueueSetState:function(r,e,t){r=r._reactInternals;var n=Tr(),i=Ui(r),s=ei(n,i);s.payload=e,t!=null&&(s.callback=t),e=Mi(r,s,i),e!==null&&(Un(e,r,i,n),El(e,r,i))},enqueueReplaceState:function(r,e,t){r=r._reactInternals;var n=Tr(),i=Ui(r),s=ei(n,i);s.tag=1,s.payload=e,t!=null&&(s.callback=t),e=Mi(r,s,i),e!==null&&(Un(e,r,i,n),El(e,r,i))},enqueueForceUpdate:function(r,e){r=r._reactInternals;var t=Tr(),n=Ui(r),i=ei(t,n);i.tag=2,e!=null&&(i.callback=e),e=Mi(r,i,n),e!==null&&(Un(e,r,n,t),El(e,r,n))}};function Ag(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?!Ca(t,n)||!Ca(i,s):!0}function ev(r,e,t){var n=!1,i=Oi,s=e.contextType;return typeof s=="object"&&s!==null?s=pn(s):(i=_r(e)?ls:vr.current,n=e.contextTypes,s=(n=n!=null)?ro(r,i):Oi),e=new e(t,s),r.memoizedState=e.state!==null&&e.state!==void 0?e.state:null,e.updater=Iu,r.stateNode=e,e._reactInternals=r,n&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=i,r.__reactInternalMemoizedMaskedChildContext=s),e}function Rg(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&&Iu.enqueueReplaceState(e,e.state,null)}function Nd(r,e,t,n){var i=r.stateNode;i.props=t,i.state=r.memoizedState,i.refs={},pf(r);var s=e.contextType;typeof s=="object"&&s!==null?i.context=pn(s):(s=_r(e)?ls:vr.current,i.context=ro(r,s)),i.state=r.memoizedState,s=e.getDerivedStateFromProps,typeof s=="function"&&($d(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&&Iu.enqueueReplaceState(i,i.state,null),eu(r,t,i,n),i.state=r.memoizedState),typeof i.componentDidMount=="function"&&(r.flags|=4194308)}function oo(r,e){try{var t="",n=e;do t+=Ex(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{fc=!1,Error.prepareStackTrace=t}return(r=r?r.displayName||r.name:"")?Vo(r):""}function zx(r){switch(r.tag){case 5:return Vo(r.type);case 16:return Vo("Lazy");case 13:return Vo("Suspense");case 19:return Vo("SuspenseList");case 0:case 2:case 15:return r=pc(r.type,!1),r;case 11:return r=pc(r.type.render,!1),r;case 1:return r=pc(r.type,!0),r;default:return""}}function yd(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 Os:return"Portal";case pd:return"Profiler";case Kh:return"StrictMode";case gd:return"Suspense";case md:return"SuspenseList"}if(typeof r=="object")switch(r.$$typeof){case _y:return(r.displayName||"Context")+".Consumer";case Ly:return(r._context.displayName||"Context")+".Provider";case qh:var e=r.render;return r=r.displayName,r||(r=e.displayName||e.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case Qh:return e=r.displayName||null,e!==null?e:yd(r.type)||"Memo";case mi:e=r._payload,r=r._init;try{return yd(r(e))}catch{}}return null}function Dx(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 yd(e);case 8:return e===Kh?"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 Di(r){switch(typeof r){case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function Ny(r){var e=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function Ox(r){var e=Ny(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 Ka(r){r._valueTracker||(r._valueTracker=Ox(r))}function Wy(r){if(!r)return!1;var e=r._valueTracker;if(!e)return!0;var t=e.getValue(),n="";return r&&(n=Ny(r)?r.checked?"true":"false":r.value),r=n,r!==t?(e.setValue(r),!0):!1}function _l(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 vd(r,e){var t=e.checked;return Ct({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??r._wrapperState.initialChecked})}function qp(r,e){var t=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;t=Di(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 Hy(r,e){e=e.checked,e!=null&&Zh(r,"checked",e,!1)}function wd(r,e){Hy(r,e);var t=Di(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")?bd(r,e.type,t):e.hasOwnProperty("defaultValue")&&bd(r,e.type,Di(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(r.defaultChecked=!!e.defaultChecked)}function Qp(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 bd(r,e,t){(e!=="number"||_l(r.ownerDocument)!==r)&&(t==null?r.defaultValue=""+r._wrapperState.initialValue:r.defaultValue!==""+t&&(r.defaultValue=""+t))}var jo=Array.isArray;function Zs(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=""+Di(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(ee(91));return Ct({},e,{value:void 0,defaultValue:void 0,children:""+r._wrapperState.initialValue})}function Jp(r,e){var t=e.value;if(t==null){if(t=e.children,e=e.defaultValue,t!=null){if(e!=null)throw Error(ee(92));if(jo(t)){if(1<t.length)throw Error(ee(93));t=t[0]}e=t}e==null&&(e=""),t=e}r._wrapperState={initialValue:Di(t)}}function Vy(r,e){var t=Di(e.value),n=Di(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 eg(r){var e=r.textContent;e===r._wrapperState.initialValue&&e!==""&&e!==null&&(r.value=e)}function jy(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 xd(r,e){return r==null||r==="http://www.w3.org/1999/xhtml"?jy(e):r==="http://www.w3.org/2000/svg"&&e==="foreignObject"?"http://www.w3.org/1999/xhtml":r}var qa,Yy=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(qa=qa||document.createElement("div"),qa.innerHTML="<svg>"+e.valueOf().toString()+"</svg>",e=qa.firstChild;r.firstChild;)r.removeChild(r.firstChild);for(;e.firstChild;)r.appendChild(e.firstChild)}});function ga(r,e){if(e){var t=r.firstChild;if(t&&t===r.lastChild&&t.nodeType===3){t.nodeValue=e;return}}r.textContent=e}var ta={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},Bx=["Webkit","ms","Moz","O"];Object.keys(ta).forEach(function(r){Bx.forEach(function(e){e=e+r.charAt(0).toUpperCase()+r.substring(1),ta[e]=ta[r]})});function Gy(r,e,t){return e==null||typeof e=="boolean"||e===""?"":t||typeof e!="number"||e===0||ta.hasOwnProperty(r)&&ta[r]?(""+e).trim():e+"px"}function Xy(r,e){r=r.style;for(var t in e)if(e.hasOwnProperty(t)){var n=t.indexOf("--")===0,i=Gy(t,e[t],n);t==="float"&&(t="cssFloat"),n?r.setProperty(t,i):r[t]=i}}var Fx=Ct({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 Id(r,e){if(e){if(Fx[r]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(ee(137,r));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(ee(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(ee(61))}if(e.style!=null&&typeof e.style!="object")throw Error(ee(62))}}function Sd(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 kd=null;function Jh(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var Ed=null,Ks=null,qs=null;function tg(r){if(r=Oa(r)){if(typeof Ed!="function")throw Error(ee(280));var e=r.stateNode;e&&(e=Cu(e),Ed(r.stateNode,r.type,e))}}function Zy(r){Ks?qs?qs.push(r):qs=[r]:Ks=r}function Ky(){if(Ks){var r=Ks,e=qs;if(qs=Ks=null,tg(r),e)for(r=0;r<e.length;r++)tg(e[r])}}function qy(r,e){return r(e)}function Qy(){}var gc=!1;function Jy(r,e,t){if(gc)return r(e,t);gc=!0;try{return qy(r,e,t)}finally{gc=!1,(Ks!==null||qs!==null)&&(Qy(),Ky())}}function ma(r,e){var t=r.stateNode;if(t===null)return null;var n=Cu(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(ee(231,e,typeof t));return t}var Md=!1;if(ni)try{var Po={};Object.defineProperty(Po,"passive",{get:function(){Md=!0}}),window.addEventListener("test",Po,Po),window.removeEventListener("test",Po,Po)}catch{Md=!1}function Lx(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 ra=!1,$l=null,Nl=!1,Td=null,_x={onError:function(r){ra=!0,$l=r}};function $x(r,e,t,n,i,s,o,a,l){ra=!1,$l=null,Lx.apply(_x,arguments)}function Nx(r,e,t,n,i,s,o,a,l){if($x.apply(this,arguments),ra){if(ra){var u=$l;ra=!1,$l=null}else throw Error(ee(198));Nl||(Nl=!0,Td=u)}}function gs(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 e0(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 rg(r){if(gs(r)!==r)throw Error(ee(188))}function Wx(r){var e=r.alternate;if(!e){if(e=gs(r),e===null)throw Error(ee(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 rg(i),r;if(s===n)return rg(i),e;s=s.sibling}throw Error(ee(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(ee(189))}}if(t.alternate!==n)throw Error(ee(190))}if(t.tag!==3)throw Error(ee(188));return t.stateNode.current===t?r:e}function t0(r){return r=Wx(r),r!==null?r0(r):null}function r0(r){if(r.tag===5||r.tag===6)return r;for(r=r.child;r!==null;){var e=r0(r);if(e!==null)return e;r=r.sibling}return null}var n0=Jr.unstable_scheduleCallback,ng=Jr.unstable_cancelCallback,Hx=Jr.unstable_shouldYield,Vx=Jr.unstable_requestPaint,Ut=Jr.unstable_now,jx=Jr.unstable_getCurrentPriorityLevel,ef=Jr.unstable_ImmediatePriority,i0=Jr.unstable_UserBlockingPriority,Wl=Jr.unstable_NormalPriority,Yx=Jr.unstable_LowPriority,s0=Jr.unstable_IdlePriority,yu=null,Hn=null;function Gx(r){if(Hn&&typeof Hn.onCommitFiberRoot=="function")try{Hn.onCommitFiberRoot(yu,r,void 0,(r.current.flags&128)===128)}catch{}}var Tn=Math.clz32?Math.clz32:Kx,Xx=Math.log,Zx=Math.LN2;function Kx(r){return r>>>=0,r===0?32:31-(Xx(r)/Zx|0)|0}var Qa=64,Ja=4194304;function Yo(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 Hl(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=Yo(a):(s&=o,s!==0&&(n=Yo(s)))}else o=t&~i,o!==0?n=Yo(o):s!==0&&(n=Yo(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-Tn(e),i=1<<t,n|=r[t],e&=~i;return n}function qx(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 Qx(r,e){for(var t=r.suspendedLanes,n=r.pingedLanes,i=r.expirationTimes,s=r.pendingLanes;0<s;){var o=31-Tn(s),a=1<<o,l=i[o];l===-1?(!(a&t)||a&n)&&(i[o]=qx(a,e)):l<=e&&(r.expiredLanes|=a),s&=~a}}function Ud(r){return r=r.pendingLanes&-1073741825,r!==0?r:r&1073741824?1073741824:0}function o0(){var r=Qa;return Qa<<=1,!(Qa&4194240)&&(Qa=64),r}function mc(r){for(var e=[],t=0;31>t;t++)e.push(r);return e}function za(r,e,t){r.pendingLanes|=e,e!==536870912&&(r.suspendedLanes=0,r.pingedLanes=0),r=r.eventTimes,e=31-Tn(e),r[e]=t}function Jx(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-Tn(t),s=1<<i;e[i]=0,n[i]=-1,r[i]=-1,t&=~s}}function tf(r,e){var t=r.entangledLanes|=e;for(r=r.entanglements;t;){var n=31-Tn(t),i=1<<n;i&e|r[n]&e&&(r[n]|=e),t&=~i}}var Xe=0;function a0(r){return r&=-r,1<r?4<r?r&268435455?16:536870912:4:1}var l0,rf,u0,c0,d0,Ad=!1,el=[],Ii=null,Si=null,ki=null,ya=new Map,va=new Map,wi=[],e2="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 ig(r,e){switch(r){case"focusin":case"focusout":Ii=null;break;case"dragenter":case"dragleave":Si=null;break;case"mouseover":case"mouseout":ki=null;break;case"pointerover":case"pointerout":ya.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":va.delete(e.pointerId)}}function zo(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=Oa(e),e!==null&&rf(e)),r):(r.eventSystemFlags|=n,e=r.targetContainers,i!==null&&e.indexOf(i)===-1&&e.push(i),r)}function t2(r,e,t,n,i){switch(e){case"focusin":return Ii=zo(Ii,r,e,t,n,i),!0;case"dragenter":return Si=zo(Si,r,e,t,n,i),!0;case"mouseover":return ki=zo(ki,r,e,t,n,i),!0;case"pointerover":var s=i.pointerId;return ya.set(s,zo(ya.get(s)||null,r,e,t,n,i)),!0;case"gotpointercapture":return s=i.pointerId,va.set(s,zo(va.get(s)||null,r,e,t,n,i)),!0}return!1}function h0(r){var e=rs(r.target);if(e!==null){var t=gs(e);if(t!==null){if(e=t.tag,e===13){if(e=e0(t),e!==null){r.blockedOn=e,d0(r.priority,function(){u0(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 Il(r){if(r.blockedOn!==null)return!1;for(var e=r.targetContainers;0<e.length;){var t=Rd(r.domEventName,r.eventSystemFlags,e[0],r.nativeEvent);if(t===null){t=r.nativeEvent;var n=new t.constructor(t.type,t);kd=n,t.target.dispatchEvent(n),kd=null}else return e=Oa(t),e!==null&&rf(e),r.blockedOn=t,!1;e.shift()}return!0}function sg(r,e,t){Il(r)&&t.delete(e)}function r2(){Ad=!1,Ii!==null&&Il(Ii)&&(Ii=null),Si!==null&&Il(Si)&&(Si=null),ki!==null&&Il(ki)&&(ki=null),ya.forEach(sg),va.forEach(sg)}function Do(r,e){r.blockedOn===e&&(r.blockedOn=null,Ad||(Ad=!0,Jr.unstable_scheduleCallback(Jr.unstable_NormalPriority,r2)))}function wa(r){function e(i){return Do(i,r)}if(0<el.length){Do(el[0],r);for(var t=1;t<el.length;t++){var n=el[t];n.blockedOn===r&&(n.blockedOn=null)}}for(Ii!==null&&Do(Ii,r),Si!==null&&Do(Si,r),ki!==null&&Do(ki,r),ya.forEach(e),va.forEach(e),t=0;t<wi.length;t++)n=wi[t],n.blockedOn===r&&(n.blockedOn=null);for(;0<wi.length&&(t=wi[0],t.blockedOn===null);)h0(t),t.blockedOn===null&&wi.shift()}var Qs=ai.ReactCurrentBatchConfig,Vl=!0;function n2(r,e,t,n){var i=Xe,s=Qs.transition;Qs.transition=null;try{Xe=1,nf(r,e,t,n)}finally{Xe=i,Qs.transition=s}}function i2(r,e,t,n){var i=Xe,s=Qs.transition;Qs.transition=null;try{Xe=4,nf(r,e,t,n)}finally{Xe=i,Qs.transition=s}}function nf(r,e,t,n){if(Vl){var i=Rd(r,e,t,n);if(i===null)Ec(r,e,n,jl,t),ig(r,n);else if(t2(i,r,e,t,n))n.stopPropagation();else if(ig(r,n),e&4&&-1<e2.indexOf(r)){for(;i!==null;){var s=Oa(i);if(s!==null&&l0(s),s=Rd(r,e,t,n),s===null&&Ec(r,e,n,jl,t),s===i)break;i=s}i!==null&&n.stopPropagation()}else Ec(r,e,n,null,t)}}var jl=null;function Rd(r,e,t,n){if(jl=null,r=Jh(n),r=rs(r),r!==null)if(e=gs(r),e===null)r=null;else if(t=e.tag,t===13){if(r=e0(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 jl=r,null}function f0(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(jx()){case ef:return 1;case i0:return 4;case Wl:case Yx:return 16;case s0:return 536870912;default:return 16}default:return 16}}var Ci=null,sf=null,Sl=null;function p0(){if(Sl)return Sl;var r,e=sf,t=e.length,n,i="value"in Ci?Ci.value:Ci.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 kl(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 tl(){return!0}function og(){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)?tl:og,this.isPropagationStopped=og,this}return Ct(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=tl)},stopPropagation:function(){var t=this.nativeEvent;t&&(t.stopPropagation?t.stopPropagation():typeof t.cancelBubble!="unknown"&&(t.cancelBubble=!0),this.isPropagationStopped=tl)},persist:function(){},isPersistent:tl}),e}var mo={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},of=tn(mo),Da=Ct({},mo,{view:0,detail:0}),s2=tn(Da),yc,vc,Oo,vu=Ct({},Da,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:af,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!==Oo&&(Oo&&r.type==="mousemove"?(yc=r.screenX-Oo.screenX,vc=r.screenY-Oo.screenY):vc=yc=0,Oo=r),yc)},movementY:function(r){return"movementY"in r?r.movementY:vc}}),ag=tn(vu),o2=Ct({},vu,{dataTransfer:0}),a2=tn(o2),l2=Ct({},Da,{relatedTarget:0}),wc=tn(l2),u2=Ct({},mo,{animationName:0,elapsedTime:0,pseudoElement:0}),c2=tn(u2),d2=Ct({},mo,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),h2=tn(d2),f2=Ct({},mo,{data:0}),lg=tn(f2),p2={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},g2={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"},m2={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function y2(r){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(r):(r=m2[r])?!!e[r]:!1}function af(){return y2}var v2=Ct({},Da,{key:function(r){if(r.key){var e=p2[r.key]||r.key;if(e!=="Unidentified")return e}return r.type==="keypress"?(r=kl(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?g2[r.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:af,charCode:function(r){return r.type==="keypress"?kl(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?kl(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),w2=tn(v2),b2=Ct({},vu,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),ug=tn(b2),C2=Ct({},Da,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:af}),x2=tn(C2),I2=Ct({},mo,{propertyName:0,elapsedTime:0,pseudoElement:0}),S2=tn(I2),k2=Ct({},vu,{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}),E2=tn(k2),M2=[9,13,27,32],lf=ni&&"CompositionEvent"in window,na=null;ni&&"documentMode"in document&&(na=document.documentMode);var T2=ni&&"TextEvent"in window&&!na,g0=ni&&(!lf||na&&8<na&&11>=na),cg=" ",dg=!1;function m0(r,e){switch(r){case"keyup":return M2.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function y0(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var Fs=!1;function U2(r,e){switch(r){case"compositionend":return y0(e);case"keypress":return e.which!==32?null:(dg=!0,cg);case"textInput":return r=e.data,r===cg&&dg?null:r;default:return null}}function A2(r,e){if(Fs)return r==="compositionend"||!lf&&m0(r,e)?(r=p0(),Sl=sf=Ci=null,Fs=!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 g0&&e.locale!=="ko"?null:e.data;default:return null}}var R2={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 hg(r){var e=r&&r.nodeName&&r.nodeName.toLowerCase();return e==="input"?!!R2[r.type]:e==="textarea"}function v0(r,e,t,n){Zy(n),e=Yl(e,"onChange"),0<e.length&&(t=new of("onChange","change",null,t,n),r.push({event:t,listeners:e}))}var ia=null,ba=null;function P2(r){U0(r,0)}function wu(r){var e=$s(r);if(Wy(e))return r}function z2(r,e){if(r==="change")return e}var w0=!1;if(ni){var bc;if(ni){var Cc="oninput"in document;if(!Cc){var fg=document.createElement("div");fg.setAttribute("oninput","return;"),Cc=typeof fg.oninput=="function"}bc=Cc}else bc=!1;w0=bc&&(!document.documentMode||9<document.documentMode)}function pg(){ia&&(ia.detachEvent("onpropertychange",b0),ba=ia=null)}function b0(r){if(r.propertyName==="value"&&wu(ba)){var e=[];v0(e,ba,r,Jh(r)),Jy(P2,e)}}function D2(r,e,t){r==="focusin"?(pg(),ia=e,ba=t,ia.attachEvent("onpropertychange",b0)):r==="focusout"&&pg()}function O2(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return wu(ba)}function B2(r,e){if(r==="click")return wu(e)}function F2(r,e){if(r==="input"||r==="change")return wu(e)}function L2(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var An=typeof Object.is=="function"?Object.is:L2;function Ca(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(!fd.call(e,i)||!An(r[i],e[i]))return!1}return!0}function gg(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function mg(r,e){var t=gg(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=gg(t)}}function C0(r,e){return r&&e?r===e?!0:r&&r.nodeType===3?!1:e&&e.nodeType===3?C0(r,e.parentNode):"contains"in r?r.contains(e):r.compareDocumentPosition?!!(r.compareDocumentPosition(e)&16):!1:!1}function x0(){for(var r=window,e=_l();e instanceof r.HTMLIFrameElement;){try{var t=typeof e.contentWindow.location.href=="string"}catch{t=!1}if(t)r=e.contentWindow;else break;e=_l(r.document)}return e}function uf(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 _2(r){var e=x0(),t=r.focusedElem,n=r.selectionRange;if(e!==t&&t&&t.ownerDocument&&C0(t.ownerDocument.documentElement,t)){if(n!==null&&uf(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=mg(t,s);var o=mg(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 $2=ni&&"documentMode"in document&&11>=document.documentMode,Ls=null,Pd=null,sa=null,zd=!1;function yg(r,e,t){var n=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;zd||Ls==null||Ls!==_l(n)||(n=Ls,"selectionStart"in n&&uf(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}),sa&&Ca(sa,n)||(sa=n,n=Yl(Pd,"onSelect"),0<n.length&&(e=new of("onSelect","select",null,e,t),r.push({event:e,listeners:n}),e.target=Ls)))}function rl(r,e){var t={};return t[r.toLowerCase()]=e.toLowerCase(),t["Webkit"+r]="webkit"+e,t["Moz"+r]="moz"+e,t}var _s={animationend:rl("Animation","AnimationEnd"),animationiteration:rl("Animation","AnimationIteration"),animationstart:rl("Animation","AnimationStart"),transitionend:rl("Transition","TransitionEnd")},xc={},I0={};ni&&(I0=document.createElement("div").style,"AnimationEvent"in window||(delete _s.animationend.animation,delete _s.animationiteration.animation,delete _s.animationstart.animation),"TransitionEvent"in window||delete _s.transitionend.transition);function bu(r){if(xc[r])return xc[r];if(!_s[r])return r;var e=_s[r],t;for(t in e)if(e.hasOwnProperty(t)&&t in I0)return xc[r]=e[t];return r}var S0=bu("animationend"),k0=bu("animationiteration"),E0=bu("animationstart"),M0=bu("transitionend"),T0=new Map,vg="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 Fi(r,e){T0.set(r,e),ps(e,[r])}for(var Ic=0;Ic<vg.length;Ic++){var Sc=vg[Ic],N2=Sc.toLowerCase(),W2=Sc[0].toUpperCase()+Sc.slice(1);Fi(N2,"on"+W2)}Fi(S0,"onAnimationEnd");Fi(k0,"onAnimationIteration");Fi(E0,"onAnimationStart");Fi("dblclick","onDoubleClick");Fi("focusin","onFocus");Fi("focusout","onBlur");Fi(M0,"onTransitionEnd");ro("onMouseEnter",["mouseout","mouseover"]);ro("onMouseLeave",["mouseout","mouseover"]);ro("onPointerEnter",["pointerout","pointerover"]);ro("onPointerLeave",["pointerout","pointerover"]);ps("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));ps("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));ps("onBeforeInput",["compositionend","keypress","textInput","paste"]);ps("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));ps("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));ps("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Go="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(" "),H2=new Set("cancel close invalid load scroll toggle".split(" ").concat(Go));function wg(r,e,t){var n=r.type||"unknown-event";r.currentTarget=t,Nx(n,e,void 0,r),r.currentTarget=null}function U0(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;wg(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;wg(i,a,u),s=l}}}if(Nl)throw r=Td,Nl=!1,Td=null,r}function at(r,e){var t=e[Ld];t===void 0&&(t=e[Ld]=new Set);var n=r+"__bubble";t.has(n)||(A0(e,r,2,!1),t.add(n))}function kc(r,e,t){var n=0;e&&(n|=4),A0(t,r,n,e)}var nl="_reactListening"+Math.random().toString(36).slice(2);function xa(r){if(!r[nl]){r[nl]=!0,Fy.forEach(function(t){t!=="selectionchange"&&(H2.has(t)||kc(t,!1,r),kc(t,!0,r))});var e=r.nodeType===9?r:r.ownerDocument;e===null||e[nl]||(e[nl]=!0,kc("selectionchange",!1,e))}}function A0(r,e,t,n){switch(f0(e)){case 1:var i=n2;break;case 4:i=i2;break;default:i=nf}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 Ec(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=rs(a),o===null)return;if(l=o.tag,l===5||l===6){n=s=o;continue e}a=a.parentNode}}n=n.return}Jy(function(){var u=s,c=Jh(t),d=[];e:{var h=T0.get(r);if(h!==void 0){var f=of,p=r;switch(r){case"keypress":if(kl(t)===0)break e;case"keydown":case"keyup":f=w2;break;case"focusin":p="focus",f=wc;break;case"focusout":p="blur",f=wc;break;case"beforeblur":case"afterblur":f=wc;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=ag;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":f=a2;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":f=x2;break;case S0:case k0:case E0:f=c2;break;case M0:f=S2;break;case"scroll":f=s2;break;case"wheel":f=E2;break;case"copy":case"cut":case"paste":f=h2;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":f=ug}var g=(e&4)!==0,C=!g&&r==="scroll",y=g?h!==null?h+"Capture":null:h;g=[];for(var m=u,v;m!==null;){v=m;var b=v.stateNode;if(v.tag===5&&b!==null&&(v=b,y!==null&&(b=ma(m,y),b!=null&&g.push(Ia(m,b,v)))),C)break;m=m.return}0<g.length&&(h=new f(h,p,null,t,c),d.push({event:h,listeners:g}))}}if(!(e&7)){e:{if(h=r==="mouseover"||r==="pointerover",f=r==="mouseout"||r==="pointerout",h&&t!==kd&&(p=t.relatedTarget||t.fromElement)&&(rs(p)||p[ii]))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?rs(p):null,p!==null&&(C=gs(p),p!==C||p.tag!==5&&p.tag!==6)&&(p=null)):(f=null,p=u),f!==p)){if(g=ag,b="onMouseLeave",y="onMouseEnter",m="mouse",(r==="pointerout"||r==="pointerover")&&(g=ug,b="onPointerLeave",y="onPointerEnter",m="pointer"),C=f==null?h:$s(f),v=p==null?h:$s(p),h=new g(b,m+"leave",f,t,c),h.target=C,h.relatedTarget=v,b=null,rs(c)===u&&(g=new g(y,m+"enter",p,t,c),g.target=v,g.relatedTarget=C,b=g),C=b,f&&p)t:{for(g=f,y=p,m=0,v=g;v;v=Ts(v))m++;for(v=0,b=y;b;b=Ts(b))v++;for(;0<m-v;)g=Ts(g),m--;for(;0<v-m;)y=Ts(y),v--;for(;m--;){if(g===y||y!==null&&g===y.alternate)break t;g=Ts(g),y=Ts(y)}g=null}else g=null;f!==null&&bg(d,h,f,g,!1),p!==null&&C!==null&&bg(d,C,p,g,!0)}}e:{if(h=u?$s(u):window,f=h.nodeName&&h.nodeName.toLowerCase(),f==="select"||f==="input"&&h.type==="file")var S=z2;else if(hg(h))if(w0)S=F2;else{S=O2;var I=D2}else(f=h.nodeName)&&f.toLowerCase()==="input"&&(h.type==="checkbox"||h.type==="radio")&&(S=B2);if(S&&(S=S(r,u))){v0(d,S,t,c);break e}I&&I(r,h,u),r==="focusout"&&(I=h._wrapperState)&&I.controlled&&h.type==="number"&&bd(h,"number",h.value)}switch(I=u?$s(u):window,r){case"focusin":(hg(I)||I.contentEditable==="true")&&(Ls=I,Pd=u,sa=null);break;case"focusout":sa=Pd=Ls=null;break;case"mousedown":zd=!0;break;case"contextmenu":case"mouseup":case"dragend":zd=!1,yg(d,t,c);break;case"selectionchange":if($2)break;case"keydown":case"keyup":yg(d,t,c)}var E;if(lf)e:{switch(r){case"compositionstart":var U="onCompositionStart";break e;case"compositionend":U="onCompositionEnd";break e;case"compositionupdate":U="onCompositionUpdate";break e}U=void 0}else Fs?m0(r,t)&&(U="onCompositionEnd"):r==="keydown"&&t.keyCode===229&&(U="onCompositionStart");U&&(g0&&t.locale!=="ko"&&(Fs||U!=="onCompositionStart"?U==="onCompositionEnd"&&Fs&&(E=p0()):(Ci=c,sf="value"in Ci?Ci.value:Ci.textContent,Fs=!0)),I=Yl(u,U),0<I.length&&(U=new lg(U,r,null,t,c),d.push({event:U,listeners:I}),E?U.data=E:(E=y0(t),E!==null&&(U.data=E)))),(E=T2?U2(r,t):A2(r,t))&&(u=Yl(u,"onBeforeInput"),0<u.length&&(c=new lg("onBeforeInput","beforeinput",null,t,c),d.push({event:c,listeners:u}),c.data=E))}U0(d,e)})}function Ia(r,e,t){return{instance:r,listener:e,currentTarget:t}}function Yl(r,e){for(var t=e+"Capture",n=[];r!==null;){var i=r,s=i.stateNode;i.tag===5&&s!==null&&(i=s,s=ma(r,t),s!=null&&n.unshift(Ia(r,s,i)),s=ma(r,e),s!=null&&n.push(Ia(r,s,i))),r=r.return}return n}function Ts(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5);return r||null}function bg(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=ma(t,s),l!=null&&o.unshift(Ia(t,l,a))):i||(l=ma(t,s),l!=null&&o.push(Ia(t,l,a)))),t=t.return}o.length!==0&&r.push({event:e,listeners:o})}var V2=/\r\n?/g,j2=/\u0000|\uFFFD/g;function Cg(r){return(typeof r=="string"?r:""+r).replace(V2,`
|
|
38
|
+
`).replace(j2,"")}function il(r,e,t){if(e=Cg(e),Cg(r)!==e&&t)throw Error(ee(425))}function Gl(){}var Dd=null,Od=null;function Bd(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 Fd=typeof setTimeout=="function"?setTimeout:void 0,Y2=typeof clearTimeout=="function"?clearTimeout:void 0,xg=typeof Promise=="function"?Promise:void 0,G2=typeof queueMicrotask=="function"?queueMicrotask:typeof xg<"u"?function(r){return xg.resolve(null).then(r).catch(X2)}:Fd;function X2(r){setTimeout(function(){throw r})}function Mc(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),wa(e);return}n--}else t!=="$"&&t!=="$?"&&t!=="$!"||n++;t=i}while(t);wa(e)}function Ei(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 Ig(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 yo=Math.random().toString(36).slice(2),Wn="__reactFiber$"+yo,Sa="__reactProps$"+yo,ii="__reactContainer$"+yo,Ld="__reactEvents$"+yo,Z2="__reactListeners$"+yo,K2="__reactHandles$"+yo;function rs(r){var e=r[Wn];if(e)return e;for(var t=r.parentNode;t;){if(e=t[ii]||t[Wn]){if(t=e.alternate,e.child!==null||t!==null&&t.child!==null)for(r=Ig(r);r!==null;){if(t=r[Wn])return t;r=Ig(r)}return e}r=t,t=r.parentNode}return null}function Oa(r){return r=r[Wn]||r[ii],!r||r.tag!==5&&r.tag!==6&&r.tag!==13&&r.tag!==3?null:r}function $s(r){if(r.tag===5||r.tag===6)return r.stateNode;throw Error(ee(33))}function Cu(r){return r[Sa]||null}var _d=[],Ns=-1;function Li(r){return{current:r}}function ut(r){0>Ns||(r.current=_d[Ns],_d[Ns]=null,Ns--)}function rt(r,e){Ns++,_d[Ns]=r.current,r.current=e}var Oi={},vr=Li(Oi),Lr=Li(!1),ls=Oi;function no(r,e){var t=r.type.contextTypes;if(!t)return Oi;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 Xl(){ut(Lr),ut(vr)}function Sg(r,e,t){if(vr.current!==Oi)throw Error(ee(168));rt(vr,e),rt(Lr,t)}function R0(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(ee(108,Dx(r)||"Unknown",i));return Ct({},t,n)}function Zl(r){return r=(r=r.stateNode)&&r.__reactInternalMemoizedMergedChildContext||Oi,ls=vr.current,rt(vr,r),rt(Lr,Lr.current),!0}function kg(r,e,t){var n=r.stateNode;if(!n)throw Error(ee(169));t?(r=R0(r,e,ls),n.__reactInternalMemoizedMergedChildContext=r,ut(Lr),ut(vr),rt(vr,r)):ut(Lr),rt(Lr,t)}var qn=null,xu=!1,Tc=!1;function P0(r){qn===null?qn=[r]:qn.push(r)}function q2(r){xu=!0,P0(r)}function _i(){if(!Tc&&qn!==null){Tc=!0;var r=0,e=Xe;try{var t=qn;for(Xe=1;r<t.length;r++){var n=t[r];do n=n(!0);while(n!==null)}qn=null,xu=!1}catch(i){throw qn!==null&&(qn=qn.slice(r+1)),n0(ef,_i),i}finally{Xe=e,Tc=!1}}return null}var Ws=[],Hs=0,Kl=null,ql=0,un=[],cn=0,us=null,Qn=1,Jn="";function Zi(r,e){Ws[Hs++]=ql,Ws[Hs++]=Kl,Kl=r,ql=e}function z0(r,e,t){un[cn++]=Qn,un[cn++]=Jn,un[cn++]=us,us=r;var n=Qn;r=Jn;var i=32-Tn(n)-1;n&=~(1<<i),t+=1;var s=32-Tn(e)+i;if(30<s){var o=i-i%5;s=(n&(1<<o)-1).toString(32),n>>=o,i-=o,Qn=1<<32-Tn(e)+i|t<<i|n,Jn=s+r}else Qn=1<<s|t<<i|n,Jn=r}function cf(r){r.return!==null&&(Zi(r,1),z0(r,1,0))}function df(r){for(;r===Kl;)Kl=Ws[--Hs],Ws[Hs]=null,ql=Ws[--Hs],Ws[Hs]=null;for(;r===us;)us=un[--cn],un[cn]=null,Jn=un[--cn],un[cn]=null,Qn=un[--cn],un[cn]=null}var qr=null,Kr=null,gt=!1,En=null;function D0(r,e){var t=hn(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 Eg(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,Kr=Ei(e.firstChild),!0):!1;case 6:return e=r.pendingProps===""||e.nodeType!==3?null:e,e!==null?(r.stateNode=e,qr=r,Kr=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(t=us!==null?{id:Qn,overflow:Jn}:null,r.memoizedState={dehydrated:e,treeContext:t,retryLane:1073741824},t=hn(18,null,null,0),t.stateNode=e,t.return=r,r.child=t,qr=r,Kr=null,!0):!1;default:return!1}}function $d(r){return(r.mode&1)!==0&&(r.flags&128)===0}function Nd(r){if(gt){var e=Kr;if(e){var t=e;if(!Eg(r,e)){if($d(r))throw Error(ee(418));e=Ei(t.nextSibling);var n=qr;e&&Eg(r,e)?D0(n,t):(r.flags=r.flags&-4097|2,gt=!1,qr=r)}}else{if($d(r))throw Error(ee(418));r.flags=r.flags&-4097|2,gt=!1,qr=r}}}function Mg(r){for(r=r.return;r!==null&&r.tag!==5&&r.tag!==3&&r.tag!==13;)r=r.return;qr=r}function sl(r){if(r!==qr)return!1;if(!gt)return Mg(r),gt=!0,!1;var e;if((e=r.tag!==3)&&!(e=r.tag!==5)&&(e=r.type,e=e!=="head"&&e!=="body"&&!Bd(r.type,r.memoizedProps)),e&&(e=Kr)){if($d(r))throw O0(),Error(ee(418));for(;e;)D0(r,e),e=Ei(e.nextSibling)}if(Mg(r),r.tag===13){if(r=r.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(ee(317));e:{for(r=r.nextSibling,e=0;r;){if(r.nodeType===8){var t=r.data;if(t==="/$"){if(e===0){Kr=Ei(r.nextSibling);break e}e--}else t!=="$"&&t!=="$!"&&t!=="$?"||e++}r=r.nextSibling}Kr=null}}else Kr=qr?Ei(r.stateNode.nextSibling):null;return!0}function O0(){for(var r=Kr;r;)r=Ei(r.nextSibling)}function io(){Kr=qr=null,gt=!1}function hf(r){En===null?En=[r]:En.push(r)}var Q2=ai.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(ee(309));var n=t.stateNode}if(!n)throw Error(ee(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(ee(284));if(!t._owner)throw Error(ee(290,r))}return r}function ol(r,e){throw r=Object.prototype.toString.call(e),Error(ee(31,r==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":r))}function Tg(r){var e=r._init;return e(r._payload)}function B0(r){function e(y,m){if(r){var v=y.deletions;v===null?(y.deletions=[m],y.flags|=16):v.push(m)}}function t(y,m){if(!r)return null;for(;m!==null;)e(y,m),m=m.sibling;return null}function n(y,m){for(y=new Map;m!==null;)m.key!==null?y.set(m.key,m):y.set(m.index,m),m=m.sibling;return y}function i(y,m){return y=Ai(y,m),y.index=0,y.sibling=null,y}function s(y,m,v){return y.index=v,r?(v=y.alternate,v!==null?(v=v.index,v<m?(y.flags|=2,m):v):(y.flags|=2,m)):(y.flags|=1048576,m)}function o(y){return r&&y.alternate===null&&(y.flags|=2),y}function a(y,m,v,b){return m===null||m.tag!==6?(m=Oc(v,y.mode,b),m.return=y,m):(m=i(m,v),m.return=y,m)}function l(y,m,v,b){var S=v.type;return S===Bs?c(y,m,v.props.children,b,v.key):m!==null&&(m.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===mi&&Tg(S)===m.type)?(b=i(m,v.props),b.ref=Bo(y,m,v),b.return=y,b):(b=Pl(v.type,v.key,v.props,null,y.mode,b),b.ref=Bo(y,m,v),b.return=y,b)}function u(y,m,v,b){return m===null||m.tag!==4||m.stateNode.containerInfo!==v.containerInfo||m.stateNode.implementation!==v.implementation?(m=Bc(v,y.mode,b),m.return=y,m):(m=i(m,v.children||[]),m.return=y,m)}function c(y,m,v,b,S){return m===null||m.tag!==7?(m=os(v,y.mode,b,S),m.return=y,m):(m=i(m,v),m.return=y,m)}function d(y,m,v){if(typeof m=="string"&&m!==""||typeof m=="number")return m=Oc(""+m,y.mode,v),m.return=y,m;if(typeof m=="object"&&m!==null){switch(m.$$typeof){case Za:return v=Pl(m.type,m.key,m.props,null,y.mode,v),v.ref=Bo(y,null,m),v.return=y,v;case Os:return m=Bc(m,y.mode,v),m.return=y,m;case mi:var b=m._init;return d(y,b(m._payload),v)}if(jo(m)||Ro(m))return m=os(m,y.mode,v,null),m.return=y,m;ol(y,m)}return null}function h(y,m,v,b){var S=m!==null?m.key:null;if(typeof v=="string"&&v!==""||typeof v=="number")return S!==null?null:a(y,m,""+v,b);if(typeof v=="object"&&v!==null){switch(v.$$typeof){case Za:return v.key===S?l(y,m,v,b):null;case Os:return v.key===S?u(y,m,v,b):null;case mi:return S=v._init,h(y,m,S(v._payload),b)}if(jo(v)||Ro(v))return S!==null?null:c(y,m,v,b,null);ol(y,v)}return null}function f(y,m,v,b,S){if(typeof b=="string"&&b!==""||typeof b=="number")return y=y.get(v)||null,a(m,y,""+b,S);if(typeof b=="object"&&b!==null){switch(b.$$typeof){case Za:return y=y.get(b.key===null?v:b.key)||null,l(m,y,b,S);case Os:return y=y.get(b.key===null?v:b.key)||null,u(m,y,b,S);case mi:var I=b._init;return f(y,m,v,I(b._payload),S)}if(jo(b)||Ro(b))return y=y.get(v)||null,c(m,y,b,S,null);ol(m,b)}return null}function p(y,m,v,b){for(var S=null,I=null,E=m,U=m=0,z=null;E!==null&&U<v.length;U++){E.index>U?(z=E,E=null):z=E.sibling;var B=h(y,E,v[U],b);if(B===null){E===null&&(E=z);break}r&&E&&B.alternate===null&&e(y,E),m=s(B,m,U),I===null?S=B:I.sibling=B,I=B,E=z}if(U===v.length)return t(y,E),gt&&Zi(y,U),S;if(E===null){for(;U<v.length;U++)E=d(y,v[U],b),E!==null&&(m=s(E,m,U),I===null?S=E:I.sibling=E,I=E);return gt&&Zi(y,U),S}for(E=n(y,E);U<v.length;U++)z=f(E,y,U,v[U],b),z!==null&&(r&&z.alternate!==null&&E.delete(z.key===null?U:z.key),m=s(z,m,U),I===null?S=z:I.sibling=z,I=z);return r&&E.forEach(function(R){return e(y,R)}),gt&&Zi(y,U),S}function g(y,m,v,b){var S=Ro(v);if(typeof S!="function")throw Error(ee(150));if(v=S.call(v),v==null)throw Error(ee(151));for(var I=S=null,E=m,U=m=0,z=null,B=v.next();E!==null&&!B.done;U++,B=v.next()){E.index>U?(z=E,E=null):z=E.sibling;var R=h(y,E,B.value,b);if(R===null){E===null&&(E=z);break}r&&E&&R.alternate===null&&e(y,E),m=s(R,m,U),I===null?S=R:I.sibling=R,I=R,E=z}if(B.done)return t(y,E),gt&&Zi(y,U),S;if(E===null){for(;!B.done;U++,B=v.next())B=d(y,B.value,b),B!==null&&(m=s(B,m,U),I===null?S=B:I.sibling=B,I=B);return gt&&Zi(y,U),S}for(E=n(y,E);!B.done;U++,B=v.next())B=f(E,y,U,B.value,b),B!==null&&(r&&B.alternate!==null&&E.delete(B.key===null?U:B.key),m=s(B,m,U),I===null?S=B:I.sibling=B,I=B);return r&&E.forEach(function(O){return e(y,O)}),gt&&Zi(y,U),S}function C(y,m,v,b){if(typeof v=="object"&&v!==null&&v.type===Bs&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case Za:e:{for(var S=v.key,I=m;I!==null;){if(I.key===S){if(S=v.type,S===Bs){if(I.tag===7){t(y,I.sibling),m=i(I,v.props.children),m.return=y,y=m;break e}}else if(I.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===mi&&Tg(S)===I.type){t(y,I.sibling),m=i(I,v.props),m.ref=Bo(y,I,v),m.return=y,y=m;break e}t(y,I);break}else e(y,I);I=I.sibling}v.type===Bs?(m=os(v.props.children,y.mode,b,v.key),m.return=y,y=m):(b=Pl(v.type,v.key,v.props,null,y.mode,b),b.ref=Bo(y,m,v),b.return=y,y=b)}return o(y);case Os:e:{for(I=v.key;m!==null;){if(m.key===I)if(m.tag===4&&m.stateNode.containerInfo===v.containerInfo&&m.stateNode.implementation===v.implementation){t(y,m.sibling),m=i(m,v.children||[]),m.return=y,y=m;break e}else{t(y,m);break}else e(y,m);m=m.sibling}m=Bc(v,y.mode,b),m.return=y,y=m}return o(y);case mi:return I=v._init,C(y,m,I(v._payload),b)}if(jo(v))return p(y,m,v,b);if(Ro(v))return g(y,m,v,b);ol(y,v)}return typeof v=="string"&&v!==""||typeof v=="number"?(v=""+v,m!==null&&m.tag===6?(t(y,m.sibling),m=i(m,v),m.return=y,y=m):(t(y,m),m=Oc(v,y.mode,b),m.return=y,y=m),o(y)):t(y,m)}return C}var so=B0(!0),F0=B0(!1),Ql=Li(null),Jl=null,Vs=null,ff=null;function pf(){ff=Vs=Jl=null}function gf(r){var e=Ql.current;ut(Ql),r._currentValue=e}function Wd(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 Js(r,e){Jl=r,ff=Vs=null,r=r.dependencies,r!==null&&r.firstContext!==null&&(r.lanes&e&&(Fr=!0),r.firstContext=null)}function pn(r){var e=r._currentValue;if(ff!==r)if(r={context:r,memoizedValue:e,next:null},Vs===null){if(Jl===null)throw Error(ee(308));Vs=r,Jl.dependencies={lanes:0,firstContext:r}}else Vs=Vs.next=r;return e}var ns=null;function mf(r){ns===null?ns=[r]:ns.push(r)}function L0(r,e,t,n){var i=e.interleaved;return i===null?(t.next=t,mf(e)):(t.next=i.next,i.next=t),e.interleaved=t,si(r,n)}function si(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 yi=!1;function yf(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function _0(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 ei(r,e){return{eventTime:r,lane:e,tag:0,payload:null,callback:null,next:null}}function Mi(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,si(r,t)}return i=n.interleaved,i===null?(e.next=e,mf(n)):(e.next=i.next,i.next=e),n.interleaved=e,si(r,t)}function El(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,tf(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 eu(r,e,t,n){var i=r.updateQueue;yi=!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,g=a;switch(h=e,f=t,g.tag){case 1:if(p=g.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=g.payload,h=typeof p=="function"?p.call(f,d,h):p,h==null)break e;d=Ct({},d,h);break e;case 2:yi=!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);ds|=o,r.lanes=o,r.memoizedState=d}}function Ag(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(ee(191,i));i.call(n)}}}var Ba={},Vn=Li(Ba),ka=Li(Ba),Ea=Li(Ba);function is(r){if(r===Ba)throw Error(ee(174));return r}function vf(r,e){switch(rt(Ea,e),rt(ka,r),rt(Vn,Ba),r=e.nodeType,r){case 9:case 11:e=(e=e.documentElement)?e.namespaceURI:xd(null,"");break;default:r=r===8?e.parentNode:e,e=r.namespaceURI||null,r=r.tagName,e=xd(e,r)}ut(Vn),rt(Vn,e)}function oo(){ut(Vn),ut(ka),ut(Ea)}function $0(r){is(Ea.current);var e=is(Vn.current),t=xd(e,r.type);e!==t&&(rt(ka,r),rt(Vn,t))}function wf(r){ka.current===r&&(ut(Vn),ut(ka))}var wt=Li(0);function tu(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 bf(){for(var r=0;r<Uc.length;r++)Uc[r]._workInProgressVersionPrimary=null;Uc.length=0}var Ml=ai.ReactCurrentDispatcher,Ac=ai.ReactCurrentBatchConfig,cs=0,bt=null,Nt=null,er=null,ru=!1,oa=!1,Ma=0,J2=0;function pr(){throw Error(ee(321))}function Cf(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 xf(r,e,t,n,i,s){if(cs=s,bt=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,Ml.current=r===null||r.memoizedState===null?nI:iI,r=t(n,i),oa){s=0;do{if(oa=!1,Ma=0,25<=s)throw Error(ee(301));s+=1,er=Nt=null,e.updateQueue=null,Ml.current=sI,r=t(n,i)}while(oa)}if(Ml.current=nu,e=Nt!==null&&Nt.next!==null,cs=0,er=Nt=bt=null,ru=!1,e)throw Error(ee(300));return r}function If(){var r=Ma!==0;return Ma=0,r}function Nn(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return er===null?bt.memoizedState=er=r:er=er.next=r,er}function gn(){if(Nt===null){var r=bt.alternate;r=r!==null?r.memoizedState:null}else r=Nt.next;var e=er===null?bt.memoizedState:er.next;if(e!==null)er=e,Nt=r;else{if(r===null)throw Error(ee(310));Nt=r,r={memoizedState:Nt.memoizedState,baseState:Nt.baseState,baseQueue:Nt.baseQueue,queue:Nt.queue,next:null},er===null?bt.memoizedState=er=r:er=er.next=r}return er}function Ta(r,e){return typeof e=="function"?e(r):e}function Rc(r){var e=gn(),t=e.queue;if(t===null)throw Error(ee(311));t.lastRenderedReducer=r;var n=Nt,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((cs&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,bt.lanes|=c,ds|=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,bt.lanes|=s,ds|=s,i=i.next;while(i!==r)}else i===null&&(t.lanes=0);return[e.memoizedState,t.dispatch]}function Pc(r){var e=gn(),t=e.queue;if(t===null)throw Error(ee(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 N0(){}function W0(r,e){var t=bt,n=gn(),i=e(),s=!An(n.memoizedState,i);if(s&&(n.memoizedState=i,Fr=!0),n=n.queue,Sf(j0.bind(null,t,n,r),[r]),n.getSnapshot!==e||s||er!==null&&er.memoizedState.tag&1){if(t.flags|=2048,Ua(9,V0.bind(null,t,n,i,e),void 0,null),tr===null)throw Error(ee(349));cs&30||H0(t,e,i)}return i}function H0(r,e,t){r.flags|=16384,r={getSnapshot:e,value:t},e=bt.updateQueue,e===null?(e={lastEffect:null,stores:null},bt.updateQueue=e,e.stores=[r]):(t=e.stores,t===null?e.stores=[r]:t.push(r))}function V0(r,e,t,n){e.value=t,e.getSnapshot=n,Y0(e)&&G0(r)}function j0(r,e,t){return t(function(){Y0(e)&&G0(r)})}function Y0(r){var e=r.getSnapshot;r=r.value;try{var t=e();return!An(r,t)}catch{return!0}}function G0(r){var e=si(r,1);e!==null&&Un(e,r,1,-1)}function Rg(r){var e=Nn();return typeof r=="function"&&(r=r()),e.memoizedState=e.baseState=r,r={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Ta,lastRenderedState:r},e.queue=r,r=r.dispatch=rI.bind(null,bt,r),[e.memoizedState,r]}function Ua(r,e,t,n){return r={tag:r,create:e,destroy:t,deps:n,next:null},e=bt.updateQueue,e===null?(e={lastEffect:null,stores:null},bt.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 X0(){return gn().memoizedState}function Tl(r,e,t,n){var i=Nn();bt.flags|=r,i.memoizedState=Ua(1|e,t,void 0,n===void 0?null:n)}function Iu(r,e,t,n){var i=gn();n=n===void 0?null:n;var s=void 0;if(Nt!==null){var o=Nt.memoizedState;if(s=o.destroy,n!==null&&Cf(n,o.deps)){i.memoizedState=Ua(e,t,s,n);return}}bt.flags|=r,i.memoizedState=Ua(1|e,t,s,n)}function Pg(r,e){return Tl(8390656,8,r,e)}function Sf(r,e){return Iu(2048,8,r,e)}function Z0(r,e){return Iu(4,2,r,e)}function K0(r,e){return Iu(4,4,r,e)}function q0(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 Q0(r,e,t){return t=t!=null?t.concat([r]):null,Iu(4,4,q0.bind(null,e,r),t)}function kf(){}function J0(r,e){var t=gn();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&Cf(e,n[1])?n[0]:(t.memoizedState=[r,e],r)}function ev(r,e){var t=gn();e=e===void 0?null:e;var n=t.memoizedState;return n!==null&&e!==null&&Cf(e,n[1])?n[0]:(r=r(),t.memoizedState=[r,e],r)}function tv(r,e,t){return cs&21?(An(t,e)||(t=o0(),bt.lanes|=t,ds|=t,r.baseState=!0),e):(r.baseState&&(r.baseState=!1,Fr=!0),r.memoizedState=t)}function eI(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 rv(){return gn().memoizedState}function tI(r,e,t){var n=Ui(r);if(t={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null},nv(r))iv(e,t);else if(t=L0(r,e,t,n),t!==null){var i=Tr();Un(t,r,n,i),sv(t,e,n)}}function rI(r,e,t){var n=Ui(r),i={lane:n,action:t,hasEagerState:!1,eagerState:null,next:null};if(nv(r))iv(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,mf(e)):(i.next=l.next,l.next=i),e.interleaved=i;return}}catch{}finally{}t=L0(r,e,i,n),t!==null&&(i=Tr(),Un(t,r,n,i),sv(t,e,n))}}function nv(r){var e=r.alternate;return r===bt||e!==null&&e===bt}function iv(r,e){oa=ru=!0;var t=r.pending;t===null?e.next=e:(e.next=t.next,t.next=e),r.pending=e}function sv(r,e,t){if(t&4194240){var n=e.lanes;n&=r.pendingLanes,t|=n,e.lanes=t,tf(r,t)}}var nu={readContext:pn,useCallback:pr,useContext:pr,useEffect:pr,useImperativeHandle:pr,useInsertionEffect:pr,useLayoutEffect:pr,useMemo:pr,useReducer:pr,useRef:pr,useState:pr,useDebugValue:pr,useDeferredValue:pr,useTransition:pr,useMutableSource:pr,useSyncExternalStore:pr,useId:pr,unstable_isNewReconciler:!1},nI={readContext:pn,useCallback:function(r,e){return Nn().memoizedState=[r,e===void 0?null:e],r},useContext:pn,useEffect:Pg,useImperativeHandle:function(r,e,t){return t=t!=null?t.concat([r]):null,Tl(4194308,4,q0.bind(null,e,r),t)},useLayoutEffect:function(r,e){return Tl(4194308,4,r,e)},useInsertionEffect:function(r,e){return Tl(4,2,r,e)},useMemo:function(r,e){var t=Nn();return e=e===void 0?null:e,r=r(),t.memoizedState=[r,e],r},useReducer:function(r,e,t){var n=Nn();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=tI.bind(null,bt,r),[n.memoizedState,r]},useRef:function(r){var e=Nn();return r={current:r},e.memoizedState=r},useState:Rg,useDebugValue:kf,useDeferredValue:function(r){return Nn().memoizedState=r},useTransition:function(){var r=Rg(!1),e=r[0];return r=eI.bind(null,r[1]),Nn().memoizedState=r,[e,r]},useMutableSource:function(){},useSyncExternalStore:function(r,e,t){var n=bt,i=Nn();if(gt){if(t===void 0)throw Error(ee(407));t=t()}else{if(t=e(),tr===null)throw Error(ee(349));cs&30||H0(n,e,t)}i.memoizedState=t;var s={value:t,getSnapshot:e};return i.queue=s,Pg(j0.bind(null,n,s,r),[r]),n.flags|=2048,Ua(9,V0.bind(null,n,s,t,e),void 0,null),t},useId:function(){var r=Nn(),e=tr.identifierPrefix;if(gt){var t=Jn,n=Qn;t=(n&~(1<<32-Tn(n)-1)).toString(32)+t,e=":"+e+"R"+t,t=Ma++,0<t&&(e+="H"+t.toString(32)),e+=":"}else t=J2++,e=":"+e+"r"+t.toString(32)+":";return r.memoizedState=e},unstable_isNewReconciler:!1},iI={readContext:pn,useCallback:J0,useContext:pn,useEffect:Sf,useImperativeHandle:Q0,useInsertionEffect:Z0,useLayoutEffect:K0,useMemo:ev,useReducer:Rc,useRef:X0,useState:function(){return Rc(Ta)},useDebugValue:kf,useDeferredValue:function(r){var e=gn();return tv(e,Nt.memoizedState,r)},useTransition:function(){var r=Rc(Ta)[0],e=gn().memoizedState;return[r,e]},useMutableSource:N0,useSyncExternalStore:W0,useId:rv,unstable_isNewReconciler:!1},sI={readContext:pn,useCallback:J0,useContext:pn,useEffect:Sf,useImperativeHandle:Q0,useInsertionEffect:Z0,useLayoutEffect:K0,useMemo:ev,useReducer:Pc,useRef:X0,useState:function(){return Pc(Ta)},useDebugValue:kf,useDeferredValue:function(r){var e=gn();return Nt===null?e.memoizedState=r:tv(e,Nt.memoizedState,r)},useTransition:function(){var r=Pc(Ta)[0],e=gn().memoizedState;return[r,e]},useMutableSource:N0,useSyncExternalStore:W0,useId:rv,unstable_isNewReconciler:!1};function xn(r,e){if(r&&r.defaultProps){e=Ct({},e),r=r.defaultProps;for(var t in r)e[t]===void 0&&(e[t]=r[t]);return e}return e}function Hd(r,e,t,n){e=r.memoizedState,t=t(n,e),t=t==null?e:Ct({},e,t),r.memoizedState=t,r.lanes===0&&(r.updateQueue.baseState=t)}var Su={isMounted:function(r){return(r=r._reactInternals)?gs(r)===r:!1},enqueueSetState:function(r,e,t){r=r._reactInternals;var n=Tr(),i=Ui(r),s=ei(n,i);s.payload=e,t!=null&&(s.callback=t),e=Mi(r,s,i),e!==null&&(Un(e,r,i,n),El(e,r,i))},enqueueReplaceState:function(r,e,t){r=r._reactInternals;var n=Tr(),i=Ui(r),s=ei(n,i);s.tag=1,s.payload=e,t!=null&&(s.callback=t),e=Mi(r,s,i),e!==null&&(Un(e,r,i,n),El(e,r,i))},enqueueForceUpdate:function(r,e){r=r._reactInternals;var t=Tr(),n=Ui(r),i=ei(t,n);i.tag=2,e!=null&&(i.callback=e),e=Mi(r,i,n),e!==null&&(Un(e,r,n,t),El(e,r,n))}};function zg(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?!Ca(t,n)||!Ca(i,s):!0}function ov(r,e,t){var n=!1,i=Oi,s=e.contextType;return typeof s=="object"&&s!==null?s=pn(s):(i=_r(e)?ls:vr.current,n=e.contextTypes,s=(n=n!=null)?no(r,i):Oi),e=new e(t,s),r.memoizedState=e.state!==null&&e.state!==void 0?e.state:null,e.updater=Su,r.stateNode=e,e._reactInternals=r,n&&(r=r.stateNode,r.__reactInternalMemoizedUnmaskedChildContext=i,r.__reactInternalMemoizedMaskedChildContext=s),e}function Dg(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&&Su.enqueueReplaceState(e,e.state,null)}function Vd(r,e,t,n){var i=r.stateNode;i.props=t,i.state=r.memoizedState,i.refs={},yf(r);var s=e.contextType;typeof s=="object"&&s!==null?i.context=pn(s):(s=_r(e)?ls:vr.current,i.context=no(r,s)),i.state=r.memoizedState,s=e.getDerivedStateFromProps,typeof s=="function"&&(Hd(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&&Su.enqueueReplaceState(i,i.state,null),eu(r,t,i,n),i.state=r.memoizedState),typeof i.componentDidMount=="function"&&(r.flags|=4194308)}function ao(r,e){try{var t="",n=e;do t+=zx(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 zc(r,e,t){return{value:r,source:null,stack:t??null,digest:e??null}}function Wd(r,e){try{console.error(e.value)}catch(t){setTimeout(function(){throw t})}}var J2=typeof WeakMap=="function"?WeakMap:Map;function tv(r,e,t){t=ei(-1,t),t.tag=3,t.payload={element:null};var n=e.value;return t.callback=function(){su||(su=!0,Qd=n),Wd(r,e)},t}function rv(r,e,t){t=ei(-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(){Wd(r,e)}}var s=r.stateNode;return s!==null&&typeof s.componentDidCatch=="function"&&(t.callback=function(){Wd(r,e),typeof n!="function"&&(Ti===null?Ti=new Set([this]):Ti.add(this));var o=e.stack;this.componentDidCatch(e.value,{componentStack:o!==null?o:""})}),t}function Pg(r,e,t){var n=r.pingCache;if(n===null){n=r.pingCache=new J2;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=fS.bind(null,r,e,t),e.then(r,r))}function zg(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 Dg(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=ei(-1,1),e.tag=2,Mi(t,e,1))),t.lanes|=1),r)}var eS=ai.ReactCurrentOwner,Fr=!1;function kr(r,e,t,n){e.child=r===null?R0(e,null,t,n):io(e,r.child,t,n)}function Og(r,e,t,n,i){t=t.render;var s=e.ref;return Qs(e,i),n=wf(r,e,t,n,s,i),t=bf(),r!==null&&!Fr?(e.updateQueue=r.updateQueue,e.flags&=-2053,r.lanes&=~i,oi(r,e,i)):(gt&&t&&af(e),e.flags|=1,kr(r,e,n,i),e.child)}function Bg(r,e,t,n,i){if(r===null){var s=t.type;return typeof s=="function"&&!Af(s)&&s.defaultProps===void 0&&t.compare===null&&t.defaultProps===void 0?(e.tag=15,e.type=s,nv(r,e,s,n,i)):(r=Pl(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:Ca,t(o,n)&&r.ref===e.ref)return oi(r,e,i)}return e.flags|=1,r=Ai(s,n),r.ref=e.ref,r.return=e,e.child=r}function nv(r,e,t,n,i){if(r!==null){var s=r.memoizedProps;if(Ca(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,oi(r,e,i)}return Hd(r,e,t,n,i)}function iv(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(js,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(js,Gr),Gr|=r,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=s!==null?s.baseLanes:t,rt(js,Gr),Gr|=n}else s!==null?(n=s.baseLanes|t,e.memoizedState=null):n=t,rt(js,Gr),Gr|=n;return kr(r,e,i,t),e.child}function sv(r,e){var t=e.ref;(r===null&&t!==null||r!==null&&r.ref!==t)&&(e.flags|=512,e.flags|=2097152)}function Hd(r,e,t,n,i){var s=_r(t)?ls:vr.current;return s=ro(e,s),Qs(e,i),t=wf(r,e,t,n,s,i),n=bf(),r!==null&&!Fr?(e.updateQueue=r.updateQueue,e.flags&=-2053,r.lanes&=~i,oi(r,e,i)):(gt&&n&&af(e),e.flags|=1,kr(r,e,t,i),e.child)}function Fg(r,e,t,n,i){if(_r(t)){var s=!0;Zl(e)}else s=!1;if(Qs(e,i),e.stateNode===null)Ul(r,e),ev(e,t,n),Nd(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=pn(u):(u=_r(t)?ls:vr.current,u=ro(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)&&Rg(e,o,n,u),yi=!1;var h=e.memoizedState;o.state=h,eu(e,n,o,i),l=e.memoizedState,a!==n||h!==l||Lr.current||yi?(typeof c=="function"&&($d(e,t,c,n),l=e.memoizedState),(a=yi||Ag(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,z0(r,e),a=e.memoizedProps,u=e.type===e.elementType?a:xn(e.type,a),o.props=u,d=e.pendingProps,h=o.context,l=t.contextType,typeof l=="object"&&l!==null?l=pn(l):(l=_r(t)?ls:vr.current,l=ro(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)&&Rg(e,o,n,l),yi=!1,h=e.memoizedState,o.state=h,eu(e,n,o,i);var p=e.memoizedState;a!==d||h!==p||Lr.current||yi?(typeof f=="function"&&($d(e,t,f,n),p=e.memoizedState),(u=yi||Ag(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 Vd(r,e,t,n,s,i)}function Vd(r,e,t,n,i,s){sv(r,e);var o=(e.flags&128)!==0;if(!n&&!o)return i&&xg(e,t,!1),oi(r,e,s);n=e.stateNode,eS.current=e;var a=o&&typeof t.getDerivedStateFromError!="function"?null:n.render();return e.flags|=1,r!==null&&o?(e.child=io(e,r.child,null,s),e.child=io(e,null,a,s)):kr(r,e,a,s),e.memoizedState=n.state,i&&xg(e,t,!0),e.child}function ov(r){var e=r.stateNode;e.pendingContext?Cg(r,e.pendingContext,e.pendingContext!==e.context):e.context&&Cg(r,e.context,!1),gf(r,e.containerInfo)}function Lg(r,e,t,n,i){return no(),uf(i),e.flags|=256,kr(r,e,t,n),e.child}var jd={dehydrated:null,treeContext:null,retryLane:0};function Yd(r){return{baseLanes:r,cachePool:null,transitions:null}}function av(r,e,t){var n=e.pendingProps,i=wt.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(wt,i&1),r===null)return Ld(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=Mu(o,n,0,null),r=os(r,n,t,null),s.return=e,r.return=e,s.sibling=r,e.child=s,e.child.memoizedState=Yd(t),e.memoizedState=jd,r):Sf(e,o));if(i=r.memoizedState,i!==null&&(a=i.dehydrated,a!==null))return tS(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=Ai(i,l),n.subtreeFlags=i.subtreeFlags&14680064),a!==null?s=Ai(a,s):(s=os(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?Yd(t):{baseLanes:o.baseLanes|t,cachePool:null,transitions:o.transitions},s.memoizedState=o,s.childLanes=r.childLanes&~t,e.memoizedState=jd,n}return s=r.child,r=s.sibling,n=Ai(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 Sf(r,e){return e=Mu({mode:"visible",children:e},r.mode,0,null),e.return=r,r.child=e}function al(r,e,t,n){return n!==null&&uf(n),io(e,r.child,null,t),r=Sf(e,e.pendingProps.children),r.flags|=2,e.memoizedState=null,r}function tS(r,e,t,n,i,s,o){if(t)return e.flags&256?(e.flags&=-257,n=zc(Error(ee(422))),al(r,e,o,n)):e.memoizedState!==null?(e.child=r.child,e.flags|=128,null):(s=n.fallback,i=e.mode,n=Mu({mode:"visible",children:n.children},i,0,null),s=os(s,i,o,null),s.flags|=2,n.return=e,s.return=e,n.sibling=s,e.child=n,e.mode&1&&io(e,r.child,null,o),e.child.memoizedState=Yd(o),e.memoizedState=jd,s);if(!(e.mode&1))return al(r,e,o,null);if(i.data==="$!"){if(n=i.nextSibling&&i.nextSibling.dataset,n)var a=n.dgst;return n=a,s=Error(ee(419)),n=zc(s,n,void 0),al(r,e,o,n)}if(a=(o&r.childLanes)!==0,Fr||a){if(n=tr,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,si(r,i),Un(n,r,i,-1))}return Uf(),n=zc(Error(ee(421))),al(r,e,o,n)}return i.data==="$?"?(e.flags|=128,e.child=r.child,e=pS.bind(null,r),i._reactRetry=e,null):(r=s.treeContext,Zr=Ei(i.nextSibling),Kr=e,gt=!0,En=null,r!==null&&(un[cn++]=Qn,un[cn++]=Jn,un[cn++]=us,Qn=r.id,Jn=r.overflow,us=e),e=Sf(e,n.children),e.flags|=4096,e)}function _g(r,e,t){r.lanes|=e;var n=r.alternate;n!==null&&(n.lanes|=e),_d(r.return,e,t)}function Dc(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 lv(r,e,t){var n=e.pendingProps,i=n.revealOrder,s=n.tail;if(kr(r,e,n.children,t),n=wt.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&&_g(r,t,e);else if(r.tag===19)_g(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(wt,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&&tu(r)===null&&(i=t),t=t.sibling;t=i,t===null?(i=e.child,e.child=null):(i=t.sibling,t.sibling=null),Dc(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&&tu(r)===null){e.child=i;break}r=i.sibling,i.sibling=t,t=i,i=r}Dc(e,!0,t,null,s);break;case"together":Dc(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function Ul(r,e){!(e.mode&1)&&r!==null&&(r.alternate=null,e.alternate=null,e.flags|=2)}function oi(r,e,t){if(r!==null&&(e.dependencies=r.dependencies),ds|=e.lanes,!(t&e.childLanes))return null;if(r!==null&&e.child!==r.child)throw Error(ee(153));if(e.child!==null){for(r=e.child,t=Ai(r,r.pendingProps),e.child=t,t.return=e;r.sibling!==null;)r=r.sibling,t=t.sibling=Ai(r,r.pendingProps),t.return=e;t.sibling=null}return e.child}function rS(r,e,t){switch(e.tag){case 3:ov(e),no();break;case 5:D0(e);break;case 1:_r(e.type)&&Zl(e);break;case 4:gf(e,e.stateNode.containerInfo);break;case 10:var n=e.type._context,i=e.memoizedProps.value;rt(Ql,n._currentValue),n._currentValue=i;break;case 13:if(n=e.memoizedState,n!==null)return n.dehydrated!==null?(rt(wt,wt.current&1),e.flags|=128,null):t&e.child.childLanes?av(r,e,t):(rt(wt,wt.current&1),r=oi(r,e,t),r!==null?r.sibling:null);rt(wt,wt.current&1);break;case 19:if(n=(t&e.childLanes)!==0,r.flags&128){if(n)return lv(r,e,t);e.flags|=128}if(i=e.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),rt(wt,wt.current),n)break;return null;case 22:case 23:return e.lanes=0,iv(r,e,t)}return oi(r,e,t)}var uv,Gd,cv,dv;uv=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}};Gd=function(){};cv=function(r,e,t,n){var i=r.memoizedProps;if(i!==n){r=e.stateNode,is(Vn.current);var s=null;switch(t){case"input":i=gd(r,i),n=gd(r,n),s=[];break;case"select":i=Ct({},i,{value:void 0}),n=Ct({},n,{value:void 0}),s=[];break;case"textarea":i=vd(r,i),n=vd(r,n),s=[];break;default:typeof i.onClick!="function"&&typeof n.onClick=="function"&&(r.onclick=Gl)}bd(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"&&(pa.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"&&(pa.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)}};dv=function(r,e,t,n){t!==n&&(e.flags|=4)};function Bo(r,e){if(!gt)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 gr(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 nS(r,e,t){var n=e.pendingProps;switch(lf(e),e.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return gr(e),null;case 1:return _r(e.type)&&Xl(),gr(e),null;case 3:return n=e.stateNode,so(),ut(Lr),ut(vr),yf(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(r===null||r.child===null)&&(sl(e)?e.flags|=4:r===null||r.memoizedState.isDehydrated&&!(e.flags&256)||(e.flags|=1024,En!==null&&(th(En),En=null))),Gd(r,e),gr(e),null;case 5:mf(e);var i=is(Ea.current);if(t=e.type,r!==null&&e.stateNode!=null)cv(r,e,t,n,i),r.ref!==e.ref&&(e.flags|=512,e.flags|=2097152);else{if(!n){if(e.stateNode===null)throw Error(ee(166));return gr(e),null}if(r=is(Vn.current),sl(e)){n=e.stateNode,t=e.type;var s=e.memoizedProps;switch(n[Wn]=e,n[Ia]=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<Yo.length;i++)at(Yo[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":Xp(n,s),at("invalid",n);break;case"select":n._wrapperState={wasMultiple:!!s.multiple},at("invalid",n);break;case"textarea":Kp(n,s),at("invalid",n)}bd(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&&il(n.textContent,a,r),i=["children",a]):typeof a=="number"&&n.textContent!==""+a&&(s.suppressHydrationWarning!==!0&&il(n.textContent,a,r),i=["children",""+a]):pa.hasOwnProperty(o)&&a!=null&&o==="onScroll"&&at("scroll",n)}switch(t){case"input":Ka(n),Zp(n,s,!0);break;case"textarea":Ka(n),qp(n);break;case"select":case"option":break;default:typeof s.onClick=="function"&&(n.onclick=Gl)}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=_y(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[Wn]=e,r[Ia]=n,uv(r,e,!1,!1),e.stateNode=r;e:{switch(o=Cd(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<Yo.length;i++)at(Yo[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":Xp(r,n),i=gd(r,n),at("invalid",r);break;case"option":i=n;break;case"select":r._wrapperState={wasMultiple:!!n.multiple},i=Ct({},n,{value:void 0}),at("invalid",r);break;case"textarea":Kp(r,n),i=vd(r,n),at("invalid",r);break;default:i=n}bd(t,i),a=i;for(s in a)if(a.hasOwnProperty(s)){var l=a[s];s==="style"?Wy(r,l):s==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,l!=null&&$y(r,l)):s==="children"?typeof l=="string"?(t!=="textarea"||l!=="")&&ga(r,l):typeof l=="number"&&ga(r,""+l):s!=="suppressContentEditableWarning"&&s!=="suppressHydrationWarning"&&s!=="autoFocus"&&(pa.hasOwnProperty(s)?l!=null&&s==="onScroll"&&at("scroll",r):l!=null&&Yh(r,s,l,o))}switch(t){case"input":Ka(r),Zp(r,n,!1);break;case"textarea":Ka(r),qp(r);break;case"option":n.value!=null&&r.setAttribute("value",""+Di(n.value));break;case"select":r.multiple=!!n.multiple,s=n.value,s!=null?Xs(r,!!n.multiple,s,!1):n.defaultValue!=null&&Xs(r,!!n.multiple,n.defaultValue,!0);break;default:typeof i.onClick=="function"&&(r.onclick=Gl)}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 gr(e),null;case 6:if(r&&e.stateNode!=null)dv(r,e,r.memoizedProps,n);else{if(typeof n!="string"&&e.stateNode===null)throw Error(ee(166));if(t=is(Ea.current),is(Vn.current),sl(e)){if(n=e.stateNode,t=e.memoizedProps,n[Wn]=e,(s=n.nodeValue!==t)&&(r=Kr,r!==null))switch(r.tag){case 3:il(n.nodeValue,t,(r.mode&1)!==0);break;case 5:r.memoizedProps.suppressHydrationWarning!==!0&&il(n.nodeValue,t,(r.mode&1)!==0)}s&&(e.flags|=4)}else n=(t.nodeType===9?t:t.ownerDocument).createTextNode(n),n[Wn]=e,e.stateNode=n}return gr(e),null;case 13:if(ut(wt),n=e.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(gt&&Zr!==null&&e.mode&1&&!(e.flags&128))U0(),no(),e.flags|=98560,s=!1;else if(s=sl(e),n!==null&&n.dehydrated!==null){if(r===null){if(!s)throw Error(ee(318));if(s=e.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(ee(317));s[Wn]=e}else no(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;gr(e),s=!1}else En!==null&&(th(En),En=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||wt.current&1?Vt===0&&(Vt=3):Uf())),e.updateQueue!==null&&(e.flags|=4),gr(e),null);case 4:return so(),Gd(r,e),r===null&&xa(e.stateNode.containerInfo),gr(e),null;case 10:return hf(e.type._context),gr(e),null;case 17:return _r(e.type)&&Xl(),gr(e),null;case 19:if(ut(wt),s=e.memoizedState,s===null)return gr(e),null;if(n=(e.flags&128)!==0,o=s.rendering,o===null)if(n)Bo(s,!1);else{if(Vt!==0||r!==null&&r.flags&128)for(r=e.child;r!==null;){if(o=tu(r),o!==null){for(e.flags|=128,Bo(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(wt,wt.current&1|2),e.child}r=r.sibling}s.tail!==null&&Ut()>ao&&(e.flags|=128,n=!0,Bo(s,!1),e.lanes=4194304)}else{if(!n)if(r=tu(o),r!==null){if(e.flags|=128,n=!0,t=r.updateQueue,t!==null&&(e.updateQueue=t,e.flags|=4),Bo(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!gt)return gr(e),null}else 2*Ut()-s.renderingStartTime>ao&&t!==1073741824&&(e.flags|=128,n=!0,Bo(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=Ut(),e.sibling=null,t=wt.current,rt(wt,n?t&1|2:t&1),e):(gr(e),null);case 22:case 23:return Tf(),n=e.memoizedState!==null,r!==null&&r.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?Gr&1073741824&&(gr(e),e.subtreeFlags&6&&(e.flags|=8192)):gr(e),null;case 24:return null;case 25:return null}throw Error(ee(156,e.tag))}function iS(r,e){switch(lf(e),e.tag){case 1:return _r(e.type)&&Xl(),r=e.flags,r&65536?(e.flags=r&-65537|128,e):null;case 3:return so(),ut(Lr),ut(vr),yf(),r=e.flags,r&65536&&!(r&128)?(e.flags=r&-65537|128,e):null;case 5:return mf(e),null;case 13:if(ut(wt),r=e.memoizedState,r!==null&&r.dehydrated!==null){if(e.alternate===null)throw Error(ee(340));no()}return r=e.flags,r&65536?(e.flags=r&-65537|128,e):null;case 19:return ut(wt),null;case 4:return so(),null;case 10:return hf(e.type._context),null;case 22:case 23:return Tf(),null;case 24:return null;default:return null}}var ll=!1,mr=!1,sS=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){Et(r,e,n)}else t.current=null}function Xd(r,e,t){try{t()}catch(n){Et(r,e,n)}}var $g=!1;function oS(r,e){if(Rd=Vl,r=m0(),of(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(Pd={focusedElem:r,selectionRange:t},Vl=!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 g=p.memoizedProps,x=p.memoizedState,y=e.stateNode,m=y.getSnapshotBeforeUpdate(e.elementType===e.type?g:xn(e.type,g),x);y.__reactInternalSnapshotBeforeUpdate=m}break;case 3:var v=e.stateNode.containerInfo;v.nodeType===1?v.textContent="":v.nodeType===9&&v.documentElement&&v.removeChild(v.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ee(163))}}catch(b){Et(e,e.return,b)}if(r=e.sibling,r!==null){r.return=e.return,fe=r;break}fe=e.return}return p=$g,$g=!1,p}function aa(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&&Xd(e,t,s)}i=i.next}while(i!==n)}}function ku(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 Zd(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 hv(r){var e=r.alternate;e!==null&&(r.alternate=null,hv(e)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(e=r.stateNode,e!==null&&(delete e[Wn],delete e[Ia],delete e[Od],delete e[W2],delete e[H2])),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 fv(r){return r.tag===5||r.tag===3||r.tag===4}function Ng(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||fv(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 Kd(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=Gl));else if(n!==4&&(r=r.child,r!==null))for(Kd(r,e,t),r=r.sibling;r!==null;)Kd(r,e,t),r=r.sibling}function qd(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(qd(r,e,t),r=r.sibling;r!==null;)qd(r,e,t),r=r.sibling}var ar=null,Sn=!1;function pi(r,e,t){for(t=t.child;t!==null;)pv(r,e,t),t=t.sibling}function pv(r,e,t){if(Hn&&typeof Hn.onCommitFiberUnmount=="function")try{Hn.onCommitFiberUnmount(yu,t)}catch{}switch(t.tag){case 5:mr||Vs(t,e);case 6:var n=ar,i=Sn;ar=null,pi(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?Mc(r.parentNode,t):r.nodeType===1&&Mc(r,t),wa(r)):Mc(ar,t.stateNode));break;case 4:n=ar,i=Sn,ar=t.stateNode.containerInfo,Sn=!0,pi(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)&&Xd(t,e,o),i=i.next}while(i!==n)}pi(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){Et(t,e,a)}pi(r,e,t);break;case 21:pi(r,e,t);break;case 22:t.mode&1?(mr=(n=mr)||t.memoizedState!==null,pi(r,e,t),mr=n):pi(r,e,t);break;default:pi(r,e,t)}}function Wg(r){var e=r.updateQueue;if(e!==null){r.updateQueue=null;var t=r.stateNode;t===null&&(t=r.stateNode=new sS),e.forEach(function(n){var i=gS.bind(null,r,n);t.has(n)||(t.add(n),n.then(i,i))})}}function wn(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(ee(160));pv(s,o,i),ar=null,Sn=!1;var l=i.alternate;l!==null&&(l.return=null),i.return=null}catch(u){Et(i,e,u)}}if(e.subtreeFlags&12854)for(e=e.child;e!==null;)gv(e,r),e=e.sibling}function gv(r,e){var t=r.alternate,n=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:if(wn(e,r),_n(r),n&4){try{aa(3,r,r.return),ku(3,r)}catch(g){Et(r,r.return,g)}try{aa(5,r,r.return)}catch(g){Et(r,r.return,g)}}break;case 1:wn(e,r),_n(r),n&512&&t!==null&&Vs(t,t.return);break;case 5:if(wn(e,r),_n(r),n&512&&t!==null&&Vs(t,t.return),r.flags&32){var i=r.stateNode;try{ga(i,"")}catch(g){Et(r,r.return,g)}}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&&Fy(i,s),Cd(a,o);var u=Cd(a,s);for(o=0;o<l.length;o+=2){var c=l[o],d=l[o+1];c==="style"?Wy(i,d):c==="dangerouslySetInnerHTML"?$y(i,d):c==="children"?ga(i,d):Yh(i,c,d,u)}switch(a){case"input":md(i,s);break;case"textarea":Ly(i,s);break;case"select":var h=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!s.multiple;var f=s.value;f!=null?Xs(i,!!s.multiple,f,!1):h!==!!s.multiple&&(s.defaultValue!=null?Xs(i,!!s.multiple,s.defaultValue,!0):Xs(i,!!s.multiple,s.multiple?[]:"",!1))}i[Ia]=s}catch(g){Et(r,r.return,g)}}break;case 6:if(wn(e,r),_n(r),n&4){if(r.stateNode===null)throw Error(ee(162));i=r.stateNode,s=r.memoizedProps;try{i.nodeValue=s}catch(g){Et(r,r.return,g)}}break;case 3:if(wn(e,r),_n(r),n&4&&t!==null&&t.memoizedState.isDehydrated)try{wa(e.containerInfo)}catch(g){Et(r,r.return,g)}break;case 4:wn(e,r),_n(r);break;case 13:wn(e,r),_n(r),i=r.child,i.flags&8192&&(s=i.memoizedState!==null,i.stateNode.isHidden=s,!s||i.alternate!==null&&i.alternate.memoizedState!==null||(Ef=Ut())),n&4&&Wg(r);break;case 22:if(c=t!==null&&t.memoizedState!==null,r.mode&1?(mr=(u=mr)||c,wn(e,r),mr=u):wn(e,r),_n(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:aa(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(g){Et(n,t,g)}}break;case 5:Vs(h,h.return);break;case 22:if(h.memoizedState!==null){Vg(d);continue}}f!==null?(f.return=h,fe=f):Vg(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=Ny("display",o))}catch(g){Et(r,r.return,g)}}}else if(d.tag===6){if(c===null)try{d.stateNode.nodeValue=u?"":d.memoizedProps}catch(g){Et(r,r.return,g)}}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:wn(e,r),_n(r),n&4&&Wg(r);break;case 21:break;default:wn(e,r),_n(r)}}function _n(r){var e=r.flags;if(e&2){try{e:{for(var t=r.return;t!==null;){if(fv(t)){var n=t;break e}t=t.return}throw Error(ee(160))}switch(n.tag){case 5:var i=n.stateNode;n.flags&32&&(ga(i,""),n.flags&=-33);var s=Ng(r);qd(r,s,i);break;case 3:case 4:var o=n.stateNode.containerInfo,a=Ng(r);Kd(r,a,o);break;default:throw Error(ee(161))}}catch(l){Et(r,r.return,l)}r.flags&=-3}e&4096&&(r.flags&=-4097)}function aS(r,e,t){fe=r,mv(r)}function mv(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||ll;if(!o){var a=i.alternate,l=a!==null&&a.memoizedState!==null||mr;a=ll;var u=mr;if(ll=o,(mr=l)&&!u)for(fe=i;fe!==null;)o=fe,l=o.child,o.tag===22&&o.memoizedState!==null?jg(i):l!==null?(l.return=o,fe=l):jg(i);for(;s!==null;)fe=s,mv(s),s=s.sibling;fe=i,ll=a,mr=u}Hg(r)}else i.subtreeFlags&8772&&s!==null?(s.return=i,fe=s):Hg(r)}}function Hg(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||ku(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:xn(e.type,t.memoizedProps);n.componentDidUpdate(i,t.memoizedState,n.__reactInternalSnapshotBeforeUpdate)}var s=e.updateQueue;s!==null&&Mg(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}Mg(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&&wa(d)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(ee(163))}mr||e.flags&512&&Zd(e)}catch(h){Et(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 Vg(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 jg(r){for(;fe!==null;){var e=fe;try{switch(e.tag){case 0:case 11:case 15:var t=e.return;try{ku(4,e)}catch(l){Et(e,t,l)}break;case 1:var n=e.stateNode;if(typeof n.componentDidMount=="function"){var i=e.return;try{n.componentDidMount()}catch(l){Et(e,i,l)}}var s=e.return;try{Zd(e)}catch(l){Et(e,s,l)}break;case 5:var o=e.return;try{Zd(e)}catch(l){Et(e,o,l)}}}catch(l){Et(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 lS=Math.ceil,iu=ai.ReactCurrentDispatcher,If=ai.ReactCurrentOwner,fn=ai.ReactCurrentBatchConfig,Oe=0,tr=null,zt=null,lr=0,Gr=0,js=Li(0),Vt=0,Aa=null,ds=0,Eu=0,kf=0,la=null,Br=null,Ef=0,ao=1/0,Kn=null,su=!1,Qd=null,Ti=null,ul=!1,xi=null,ou=0,ua=0,Jd=null,Al=-1,Rl=0;function Tr(){return Oe&6?Ut():Al!==-1?Al:Al=Ut()}function Ui(r){return r.mode&1?Oe&2&&lr!==0?lr&-lr:j2.transition!==null?(Rl===0&&(Rl=e0()),Rl):(r=Xe,r!==0||(r=window.event,r=r===void 0?16:a0(r.type)),r):1}function Un(r,e,t,n){if(50<ua)throw ua=0,Jd=null,Error(ee(185));za(r,t,n),(!(Oe&2)||r!==tr)&&(r===tr&&(!(Oe&2)&&(Eu|=t),Vt===4&&bi(r,lr)),$r(r,n),t===1&&Oe===0&&!(e.mode&1)&&(ao=Ut()+500,xu&&_i()))}function $r(r,e){var t=r.callbackNode;jx(r,e);var n=Hl(r,r===tr?lr:0);if(n===0)t!==null&&eg(t),r.callbackNode=null,r.callbackPriority=0;else if(e=n&-n,r.callbackPriority!==e){if(t!=null&&eg(t),e===1)r.tag===0?V2(Yg.bind(null,r)):E0(Yg.bind(null,r)),$2(function(){!(Oe&6)&&_i()}),t=null;else{switch(t0(n)){case 1:t=qh;break;case 4:t=Qy;break;case 16:t=Wl;break;case 536870912:t=Jy;break;default:t=Wl}t=Iv(t,yv.bind(null,r))}r.callbackPriority=e,r.callbackNode=t}}function yv(r,e){if(Al=-1,Rl=0,Oe&6)throw Error(ee(327));var t=r.callbackNode;if(Js()&&r.callbackNode!==t)return null;var n=Hl(r,r===tr?lr:0);if(n===0)return null;if(n&30||n&r.expiredLanes||e)e=au(r,n);else{e=n;var i=Oe;Oe|=2;var s=wv();(tr!==r||lr!==e)&&(Kn=null,ao=Ut()+500,ss(r,e));do try{dS();break}catch(a){vv(r,a)}while(!0);df(),iu.current=s,Oe=i,zt!==null?e=0:(tr=null,lr=0,e=Vt)}if(e!==0){if(e===2&&(i=Ed(r),i!==0&&(n=i,e=eh(r,i))),e===1)throw t=Aa,ss(r,0),bi(r,n),$r(r,Ut()),t;if(e===6)bi(r,n);else{if(i=r.current.alternate,!(n&30)&&!uS(i)&&(e=au(r,n),e===2&&(s=Ed(r),s!==0&&(n=s,e=eh(r,s))),e===1))throw t=Aa,ss(r,0),bi(r,n),$r(r,Ut()),t;switch(r.finishedWork=i,r.finishedLanes=n,e){case 0:case 1:throw Error(ee(345));case 2:Ki(r,Br,Kn);break;case 3:if(bi(r,n),(n&130023424)===n&&(e=Ef+500-Ut(),10<e)){if(Hl(r,0)!==0)break;if(i=r.suspendedLanes,(i&n)!==n){Tr(),r.pingedLanes|=r.suspendedLanes&i;break}r.timeoutHandle=Dd(Ki.bind(null,r,Br,Kn),e);break}Ki(r,Br,Kn);break;case 4:if(bi(r,n),(n&4194240)===n)break;for(e=r.eventTimes,i=-1;0<n;){var o=31-Tn(n);s=1<<o,o=e[o],o>i&&(i=o),n&=~s}if(n=i,n=Ut()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*lS(n/1960))-n,10<n){r.timeoutHandle=Dd(Ki.bind(null,r,Br,Kn),n);break}Ki(r,Br,Kn);break;case 5:Ki(r,Br,Kn);break;default:throw Error(ee(329))}}}return $r(r,Ut()),r.callbackNode===t?yv.bind(null,r):null}function eh(r,e){var t=la;return r.current.memoizedState.isDehydrated&&(ss(r,e).flags|=256),r=au(r,e),r!==2&&(e=Br,Br=t,e!==null&&th(e)),r}function th(r){Br===null?Br=r:Br.push.apply(Br,r)}function uS(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 bi(r,e){for(e&=~kf,e&=~Eu,r.suspendedLanes|=e,r.pingedLanes&=~e,r=r.expirationTimes;0<e;){var t=31-Tn(e),n=1<<t;r[t]=-1,e&=~n}}function Yg(r){if(Oe&6)throw Error(ee(327));Js();var e=Hl(r,0);if(!(e&1))return $r(r,Ut()),null;var t=au(r,e);if(r.tag!==0&&t===2){var n=Ed(r);n!==0&&(e=n,t=eh(r,n))}if(t===1)throw t=Aa,ss(r,0),bi(r,e),$r(r,Ut()),t;if(t===6)throw Error(ee(345));return r.finishedWork=r.current.alternate,r.finishedLanes=e,Ki(r,Br,Kn),$r(r,Ut()),null}function Mf(r,e){var t=Oe;Oe|=1;try{return r(e)}finally{Oe=t,Oe===0&&(ao=Ut()+500,xu&&_i())}}function hs(r){xi!==null&&xi.tag===0&&!(Oe&6)&&Js();var e=Oe;Oe|=1;var t=fn.transition,n=Xe;try{if(fn.transition=null,Xe=1,r)return r()}finally{Xe=n,fn.transition=t,Oe=e,!(Oe&6)&&_i()}}function Tf(){Gr=js.current,ut(js)}function ss(r,e){r.finishedWork=null,r.finishedLanes=0;var t=r.timeoutHandle;if(t!==-1&&(r.timeoutHandle=-1,_2(t)),zt!==null)for(t=zt.return;t!==null;){var n=t;switch(lf(n),n.tag){case 1:n=n.type.childContextTypes,n!=null&&Xl();break;case 3:so(),ut(Lr),ut(vr),yf();break;case 5:mf(n);break;case 4:so();break;case 13:ut(wt);break;case 19:ut(wt);break;case 10:hf(n.type._context);break;case 22:case 23:Tf()}t=t.return}if(tr=r,zt=r=Ai(r.current,null),lr=Gr=e,Vt=0,Aa=null,kf=Eu=ds=0,Br=la=null,ns!==null){for(e=0;e<ns.length;e++)if(t=ns[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}ns=null}return r}function vv(r,e){do{var t=zt;try{if(df(),Ml.current=nu,ru){for(var n=bt.memoizedState;n!==null;){var i=n.queue;i!==null&&(i.pending=null),n=n.next}ru=!1}if(cs=0,er=Nt=bt=null,oa=!1,Ma=0,If.current=null,t===null||t.return===null){Vt=1,Aa=e,zt=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=zg(o);if(f!==null){f.flags&=-257,Dg(f,o,a,s,e),f.mode&1&&Pg(s,u,e),e=f,l=u;var p=e.updateQueue;if(p===null){var g=new Set;g.add(l),e.updateQueue=g}else p.add(l);break e}else{if(!(e&1)){Pg(s,u,e),Uf();break e}l=Error(ee(426))}}else if(gt&&a.mode&1){var x=zg(o);if(x!==null){!(x.flags&65536)&&(x.flags|=256),Dg(x,o,a,s,e),uf(oo(l,a));break e}}s=l=oo(l,a),Vt!==4&&(Vt=2),la===null?la=[s]:la.push(s),s=o;do{switch(s.tag){case 3:s.flags|=65536,e&=-e,s.lanes|=e;var y=tv(s,l,e);Eg(s,y);break e;case 1:a=l;var m=s.type,v=s.stateNode;if(!(s.flags&128)&&(typeof m.getDerivedStateFromError=="function"||v!==null&&typeof v.componentDidCatch=="function"&&(Ti===null||!Ti.has(v)))){s.flags|=65536,e&=-e,s.lanes|=e;var b=rv(s,a,e);Eg(s,b);break e}}s=s.return}while(s!==null)}Cv(t)}catch(I){e=I,zt===t&&t!==null&&(zt=t=t.return);continue}break}while(!0)}function wv(){var r=iu.current;return iu.current=nu,r===null?nu:r}function Uf(){(Vt===0||Vt===3||Vt===2)&&(Vt=4),tr===null||!(ds&268435455)&&!(Eu&268435455)||bi(tr,lr)}function au(r,e){var t=Oe;Oe|=2;var n=wv();(tr!==r||lr!==e)&&(Kn=null,ss(r,e));do try{cS();break}catch(i){vv(r,i)}while(!0);if(df(),Oe=t,iu.current=n,zt!==null)throw Error(ee(261));return tr=null,lr=0,Vt}function cS(){for(;zt!==null;)bv(zt)}function dS(){for(;zt!==null&&!Bx();)bv(zt)}function bv(r){var e=Sv(r.alternate,r,Gr);r.memoizedProps=r.pendingProps,e===null?Cv(r):zt=e,If.current=null}function Cv(r){var e=r;do{var t=e.alternate;if(r=e.return,e.flags&32768){if(t=iS(t,e),t!==null){t.flags&=32767,zt=t;return}if(r!==null)r.flags|=32768,r.subtreeFlags=0,r.deletions=null;else{Vt=6,zt=null;return}}else if(t=nS(t,e,Gr),t!==null){zt=t;return}if(e=e.sibling,e!==null){zt=e;return}zt=e=r}while(e!==null);Vt===0&&(Vt=5)}function Ki(r,e,t){var n=Xe,i=fn.transition;try{fn.transition=null,Xe=1,hS(r,e,t,n)}finally{fn.transition=i,Xe=n}return null}function hS(r,e,t,n){do Js();while(xi!==null);if(Oe&6)throw Error(ee(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(ee(177));r.callbackNode=null,r.callbackPriority=0;var s=t.lanes|t.childLanes;if(Yx(r,s),r===tr&&(zt=tr=null,lr=0),!(t.subtreeFlags&2064)&&!(t.flags&2064)||ul||(ul=!0,Iv(Wl,function(){return Js(),null})),s=(t.flags&15990)!==0,t.subtreeFlags&15990||s){s=fn.transition,fn.transition=null;var o=Xe;Xe=1;var a=Oe;Oe|=4,If.current=null,oS(r,t),gv(t,r),P2(Pd),Vl=!!Rd,Pd=Rd=null,r.current=t,aS(t),Fx(),Oe=a,Xe=o,fn.transition=s}else r.current=t;if(ul&&(ul=!1,xi=r,ou=i),s=r.pendingLanes,s===0&&(Ti=null),$x(t.stateNode),$r(r,Ut()),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(su)throw su=!1,r=Qd,Qd=null,r;return ou&1&&r.tag!==0&&Js(),s=r.pendingLanes,s&1?r===Jd?ua++:(ua=0,Jd=r):ua=0,_i(),null}function Js(){if(xi!==null){var r=t0(ou),e=fn.transition,t=Xe;try{if(fn.transition=null,Xe=16>r?16:r,xi===null)var n=!1;else{if(r=xi,xi=null,ou=0,Oe&6)throw Error(ee(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:aa(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(hv(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 g=p.child;if(g!==null){p.child=null;do{var x=g.sibling;g.sibling=null,g=x}while(g!==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:aa(9,s,s.return)}var y=s.sibling;if(y!==null){y.return=s.return,fe=y;break e}fe=s.return}}var m=r.current;for(fe=m;fe!==null;){o=fe;var v=o.child;if(o.subtreeFlags&2064&&v!==null)v.return=o,fe=v;else e:for(o=m;fe!==null;){if(a=fe,a.flags&2048)try{switch(a.tag){case 0:case 11:case 15:ku(9,a)}}catch(I){Et(a,a.return,I)}if(a===o){fe=null;break e}var b=a.sibling;if(b!==null){b.return=a.return,fe=b;break e}fe=a.return}}if(Oe=i,_i(),Hn&&typeof Hn.onPostCommitFiberRoot=="function")try{Hn.onPostCommitFiberRoot(yu,r)}catch{}n=!0}return n}finally{Xe=t,fn.transition=e}}return!1}function Gg(r,e,t){e=oo(t,e),e=tv(r,e,1),r=Mi(r,e,1),e=Tr(),r!==null&&(za(r,1,e),$r(r,e))}function Et(r,e,t){if(r.tag===3)Gg(r,r,t);else for(;e!==null;){if(e.tag===3){Gg(e,r,t);break}else if(e.tag===1){var n=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(Ti===null||!Ti.has(n))){r=oo(t,r),r=rv(e,r,1),e=Mi(e,r,1),r=Tr(),e!==null&&(za(e,1,r),$r(e,r));break}}e=e.return}}function fS(r,e,t){var n=r.pingCache;n!==null&&n.delete(e),e=Tr(),r.pingedLanes|=r.suspendedLanes&t,tr===r&&(lr&t)===t&&(Vt===4||Vt===3&&(lr&130023424)===lr&&500>Ut()-Ef?ss(r,0):kf|=t),$r(r,e)}function xv(r,e){e===0&&(r.mode&1?(e=Ja,Ja<<=1,!(Ja&130023424)&&(Ja=4194304)):e=1);var t=Tr();r=si(r,e),r!==null&&(za(r,e,t),$r(r,t))}function pS(r){var e=r.memoizedState,t=0;e!==null&&(t=e.retryLane),xv(r,t)}function gS(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(ee(314))}n!==null&&n.delete(e),xv(r,t)}var Sv;Sv=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,rS(r,e,t);Fr=!!(r.flags&131072)}else Fr=!1,gt&&e.flags&1048576&&M0(e,ql,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;Ul(r,e),r=e.pendingProps;var i=ro(e,vr.current);Qs(e,t),i=wf(null,e,n,r,i,t);var s=bf();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,Zl(e)):s=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,pf(e),i.updater=Iu,e.stateNode=i,i._reactInternals=e,Nd(e,n,r,t),e=Vd(null,e,n,!0,s,t)):(e.tag=0,gt&&s&&af(e),kr(null,e,i,t),e=e.child),e;case 16:n=e.elementType;e:{switch(Ul(r,e),r=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=yS(n),r=xn(n,r),i){case 0:e=Hd(null,e,n,r,t);break e;case 1:e=Fg(null,e,n,r,t);break e;case 11:e=Og(null,e,n,r,t);break e;case 14:e=Bg(null,e,n,xn(n.type,r),t);break e}throw Error(ee(306,n,""))}return e;case 0:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:xn(n,i),Hd(r,e,n,i,t);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:xn(n,i),Fg(r,e,n,i,t);case 3:e:{if(ov(e),r===null)throw Error(ee(387));n=e.pendingProps,s=e.memoizedState,i=s.element,z0(r,e),eu(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=oo(Error(ee(423)),e),e=Lg(r,e,n,t,i);break e}else if(n!==i){i=oo(Error(ee(424)),e),e=Lg(r,e,n,t,i);break e}else for(Zr=Ei(e.stateNode.containerInfo.firstChild),Kr=e,gt=!0,En=null,t=R0(e,null,n,t),e.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(no(),n===i){e=oi(r,e,t);break e}kr(r,e,n,t)}e=e.child}return e;case 5:return D0(e),r===null&&Ld(e),n=e.type,i=e.pendingProps,s=r!==null?r.memoizedProps:null,o=i.children,zd(n,i)?o=null:s!==null&&zd(n,s)&&(e.flags|=32),sv(r,e),kr(r,e,o,t),e.child;case 6:return r===null&&Ld(e),null;case 13:return av(r,e,t);case 4:return gf(e,e.stateNode.containerInfo),n=e.pendingProps,r===null?e.child=io(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:xn(n,i),Og(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(Ql,n._currentValue),n._currentValue=o,s!==null)if(An(s.value,o)){if(s.children===i.children&&!Lr.current){e=oi(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=ei(-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),_d(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(ee(341));o.lanes|=t,a=o.alternate,a!==null&&(a.lanes|=t),_d(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,Qs(e,t),i=pn(i),n=n(i),e.flags|=1,kr(r,e,n,t),e.child;case 14:return n=e.type,i=xn(n,e.pendingProps),i=xn(n.type,i),Bg(r,e,n,i,t);case 15:return nv(r,e,e.type,e.pendingProps,t);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:xn(n,i),Ul(r,e),e.tag=1,_r(n)?(r=!0,Zl(e)):r=!1,Qs(e,t),ev(e,n,i),Nd(e,n,i,t),Vd(null,e,n,!0,r,t);case 19:return lv(r,e,t);case 22:return iv(r,e,t)}throw Error(ee(156,e.tag))};function Iv(r,e){return qy(r,e)}function mS(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 hn(r,e,t,n){return new mS(r,e,t,n)}function Af(r){return r=r.prototype,!(!r||!r.isReactComponent)}function yS(r){if(typeof r=="function")return Af(r)?1:0;if(r!=null){if(r=r.$$typeof,r===Xh)return 11;if(r===Zh)return 14}return 2}function Ai(r,e){var t=r.alternate;return t===null?(t=hn(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 Pl(r,e,t,n,i,s){var o=2;if(n=r,typeof r=="function")Af(r)&&(o=1);else if(typeof r=="string")o=5;else e:switch(r){case Os:return os(t.children,i,s,e);case Gh:o=8,i|=8;break;case dd:return r=hn(12,t,e,i|2),r.elementType=dd,r.lanes=s,r;case hd:return r=hn(13,t,e,i),r.elementType=hd,r.lanes=s,r;case fd:return r=hn(19,t,e,i),r.elementType=fd,r.lanes=s,r;case Dy:return Mu(t,i,s,e);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case Py:o=10;break e;case zy:o=9;break e;case Xh:o=11;break e;case Zh:o=14;break e;case mi:o=16,n=null;break e}throw Error(ee(130,r==null?r:typeof r,""))}return e=hn(o,t,e,i),e.elementType=r,e.type=n,e.lanes=s,e}function os(r,e,t,n){return r=hn(7,r,n,e),r.lanes=t,r}function Mu(r,e,t,n){return r=hn(22,r,n,e),r.elementType=Dy,r.lanes=t,r.stateNode={isHidden:!1},r}function Oc(r,e,t){return r=hn(6,r,null,e),r.lanes=t,r}function Bc(r,e,t){return e=hn(4,r.children!==null?r.children:[],r.key,e),e.lanes=t,e.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},e}function vS(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=mc(0),this.expirationTimes=mc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=mc(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Rf(r,e,t,n,i,s,o,a,l){return r=new vS(r,e,t,a,l),e===1?(e=1,s===!0&&(e|=8)):e=0,s=hn(3,null,null,e),r.current=s,s.stateNode=r,s.memoizedState={element:n,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},pf(s),r}function wS(r,e,t){var n=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Ds,key:n==null?null:""+n,children:r,containerInfo:e,implementation:t}}function kv(r){if(!r)return Oi;r=r._reactInternals;e:{if(gs(r)!==r||r.tag!==1)throw Error(ee(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(ee(171))}if(r.tag===1){var t=r.type;if(_r(t))return k0(r,t,e)}return e}function Ev(r,e,t,n,i,s,o,a,l){return r=Rf(t,n,!0,r,i,s,o,a,l),r.context=kv(null),t=r.current,n=Tr(),i=Ui(t),s=ei(n,i),s.callback=e??null,Mi(t,s,i),r.current.lanes=i,za(r,i,n),$r(r,n),r}function Tu(r,e,t,n){var i=e.current,s=Tr(),o=Ui(i);return t=kv(t),e.context===null?e.context=t:e.pendingContext=t,e=ei(s,o),e.payload={element:r},n=n===void 0?null:n,n!==null&&(e.callback=n),r=Mi(i,e,o),r!==null&&(Un(r,i,o,s),El(r,i,o)),o}function lu(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 Xg(r,e){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var t=r.retryLane;r.retryLane=t!==0&&t<e?t:e}}function Pf(r,e){Xg(r,e),(r=r.alternate)&&Xg(r,e)}function bS(){return null}var Mv=typeof reportError=="function"?reportError:function(r){console.error(r)};function zf(r){this._internalRoot=r}Uu.prototype.render=zf.prototype.render=function(r){var e=this._internalRoot;if(e===null)throw Error(ee(409));Tu(r,e,null,null)};Uu.prototype.unmount=zf.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var e=r.containerInfo;hs(function(){Tu(null,r,null,null)}),e[ii]=null}};function Uu(r){this._internalRoot=r}Uu.prototype.unstable_scheduleHydration=function(r){if(r){var e=i0();r={blockedOn:null,target:r,priority:e};for(var t=0;t<wi.length&&e!==0&&e<wi[t].priority;t++);wi.splice(t,0,r),t===0&&o0(r)}};function Df(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function Au(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11&&(r.nodeType!==8||r.nodeValue!==" react-mount-point-unstable "))}function Zg(){}function CS(r,e,t,n,i){if(i){if(typeof n=="function"){var s=n;n=function(){var u=lu(o);s.call(u)}}var o=Ev(e,n,r,0,null,!1,!1,"",Zg);return r._reactRootContainer=o,r[ii]=o.current,xa(r.nodeType===8?r.parentNode:r),hs(),o}for(;i=r.lastChild;)r.removeChild(i);if(typeof n=="function"){var a=n;n=function(){var u=lu(l);a.call(u)}}var l=Rf(r,0,!1,null,null,!1,!1,"",Zg);return r._reactRootContainer=l,r[ii]=l.current,xa(r.nodeType===8?r.parentNode:r),hs(function(){Tu(e,l,t,n)}),l}function Ru(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=lu(o);a.call(l)}}Tu(e,o,r,i)}else o=CS(t,e,r,i,n);return lu(o)}r0=function(r){switch(r.tag){case 3:var e=r.stateNode;if(e.current.memoizedState.isDehydrated){var t=jo(e.pendingLanes);t!==0&&(Qh(e,t|1),$r(e,Ut()),!(Oe&6)&&(ao=Ut()+500,_i()))}break;case 13:hs(function(){var n=si(r,1);if(n!==null){var i=Tr();Un(n,r,1,i)}}),Pf(r,1)}};Jh=function(r){if(r.tag===13){var e=si(r,134217728);if(e!==null){var t=Tr();Un(e,r,134217728,t)}Pf(r,134217728)}};n0=function(r){if(r.tag===13){var e=Ui(r),t=si(r,e);if(t!==null){var n=Tr();Un(t,r,e,n)}Pf(r,e)}};i0=function(){return Xe};s0=function(r,e){var t=Xe;try{return Xe=r,e()}finally{Xe=t}};Sd=function(r,e,t){switch(e){case"input":if(md(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=Cu(n);if(!i)throw Error(ee(90));By(n),md(n,i)}}}break;case"textarea":Ly(r,t);break;case"select":e=t.value,e!=null&&Xs(r,!!t.multiple,e,!1)}};jy=Mf;Yy=hs;var xS={usingClientEntryPoint:!1,Events:[Oa,_s,Cu,Hy,Vy,Mf]},Fo={findFiberByHostInstance:rs,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},SS={bundleType:Fo.bundleType,version:Fo.version,rendererPackageName:Fo.rendererPackageName,rendererConfig:Fo.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ai.ReactCurrentDispatcher,findHostInstanceByFiber:function(r){return r=Zy(r),r===null?null:r.stateNode},findFiberByHostInstance:Fo.findFiberByHostInstance||bS,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 cl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!cl.isDisabled&&cl.supportsFiber)try{yu=cl.inject(SS),Hn=cl}catch{}}Jr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=xS;Jr.createPortal=function(r,e){var t=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Df(e))throw Error(ee(200));return wS(r,e,null,t)};Jr.createRoot=function(r,e){if(!Df(r))throw Error(ee(299));var t=!1,n="",i=Mv;return e!=null&&(e.unstable_strictMode===!0&&(t=!0),e.identifierPrefix!==void 0&&(n=e.identifierPrefix),e.onRecoverableError!==void 0&&(i=e.onRecoverableError)),e=Rf(r,1,!1,null,null,t,!1,n,i),r[ii]=e.current,xa(r.nodeType===8?r.parentNode:r),new zf(e)};Jr.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(ee(188)):(r=Object.keys(r).join(","),Error(ee(268,r)));return r=Zy(e),r=r===null?null:r.stateNode,r};Jr.flushSync=function(r){return hs(r)};Jr.hydrate=function(r,e,t){if(!Au(e))throw Error(ee(200));return Ru(null,r,e,!0,t)};Jr.hydrateRoot=function(r,e,t){if(!Df(r))throw Error(ee(405));var n=t!=null&&t.hydratedSources||null,i=!1,s="",o=Mv;if(t!=null&&(t.unstable_strictMode===!0&&(i=!0),t.identifierPrefix!==void 0&&(s=t.identifierPrefix),t.onRecoverableError!==void 0&&(o=t.onRecoverableError)),e=Ev(e,null,r,1,t??null,i,!1,s,o),r[ii]=e.current,xa(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 Uu(e)};Jr.render=function(r,e,t){if(!Au(e))throw Error(ee(200));return Ru(null,r,e,!1,t)};Jr.unmountComponentAtNode=function(r){if(!Au(r))throw Error(ee(40));return r._reactRootContainer?(hs(function(){Ru(null,null,r,!1,function(){r._reactRootContainer=null,r[ii]=null})}),!0):!1};Jr.unstable_batchedUpdates=Mf;Jr.unstable_renderSubtreeIntoContainer=function(r,e,t,n){if(!Au(t))throw Error(ee(200));if(r==null||r._reactInternals===void 0)throw Error(ee(38));return Ru(r,e,t,!1,n)};Jr.version="18.3.1-next-f1338f8080-20240426";function Tv(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Tv)}catch(r){console.error(r)}}Tv(),Ty.exports=Jr;var IS=Ty.exports,Kg=IS;ud.createRoot=Kg.createRoot,ud.hydrateRoot=Kg.hydrateRoot;var Uv=Object.defineProperty,kS=(r,e,t)=>e in r?Uv(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ye=(r,e)=>Uv(r,"name",{value:e,configurable:!0}),ca=(r,e,t)=>(kS(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||{}),Ri=(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))(Ri||{});function ES(r){let e=Ri[r];return e!==void 0?e:null}Ye(ES,"keyCodeToKeyboardInput");function MS(r){return Ri[r]}Ye(MS,"keyboardInputToKeyCode");var _t=(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))(_t||{});function TS(r){return r<100}Ye(TS,"isMouseButton");function US(r){return r>=100}Ye(US,"isMouseAxis");var Of=(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))(Of||{});function AS(r){return r<100}Ye(AS,"isGamepadButton");function RS(r){return r>=100}Ye(RS,"isGamepadAxis");function PS(r){return r>=0&&r<=19?r:null}Ye(PS,"gamepadButtonIndexToInput");function zS(r){return{0:100,1:101,2:102,3:103}[r]??null}Ye(zS,"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 DS(r){return r<100}Ye(DS,"isTouchButton");function OS(r){return r>=100&&r<200}Ye(OS,"isTouchPosition");function BS(r){return r>=200}Ye(BS,"isTouchGesture");function FS(r){return r<0||r>9?null:100+r*2}Ye(FS,"getTouchXAxis");function LS(r){return r<0||r>9?null:101+r*2}Ye(LS,"getTouchYAxis");var Ff=(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))(Ff||{});function _S(r){return r<100}Ye(_S,"isTouchZoneButton");function $S(r){return r>=100}Ye($S,"isTouchZonePosition");function NS(r){return r<0||r>31?null:100+r*2}Ye(NS,"getTouchZoneXAxis");function WS(r){return r<0||r>31?null:101+r*2}Ye(WS,"getTouchZoneYAxis");var Lf=(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))(Lf||{});function HS(r){return r<100}Ye(HS,"isTVRemoteButton");function VS(r){return r>=100}Ye(VS,"isTVRemoteAxis");function jS(r,e){return{device:r,input:e}}Ye(jS,"createInputDescriptor");function da(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(da,"isButton");function Av(r){return!da(r)}Ye(Av,"isAxis");function YS(r){let e=new Uint8Array(3);return e[0]=r.device,e[1]=r.input&255,e[2]=r.input>>8&255,e}Ye(YS,"serializeInputDescriptor");function GS(r,e=0){let t=r[e],n=r[e+1]|r[e+2]<<8;return{device:t,input:n}}Ye(GS,"deserializeInputDescriptor");function XS(r){let e=ce[r.device],t;switch(r.device){case 0:t=Ri[r.input];break;case 1:t=_t[r.input];break;case 2:t=Of[r.input];break;case 3:t=Bf[r.input];break;case 7:t=Ff[r.input];break;case 4:t=Lf[r.input];break;default:t="Unknown"}return`${e}:${t}`}Ye(XS,"inputDescriptorToString");function ZS(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=Ri[t];break;case 1:i=_t[t];break;case 2:i=Of[t];break;case 3:i=Bf[t];break;case 4:i=Lf[t];break;case 7:i=Ff[t];break}return i===void 0?null:{device:n,input:i}}Ye(ZS,"parseInputDescriptor");var Rv=class Ir{constructor(e=0,t=0){ca(this,"x"),ca(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(Rv,"Vector2");var Ht=Rv,KS=class sr{constructor(e=0,t=0,n=0){ca(this,"x"),ca(this,"y"),ca(this,"z"),this.x=e,this.y=t,this.z=n}static zero(){return new sr(0,0,0)}static one(){return new sr(1,1,1)}static up(){return new sr(0,1,0)}static down(){return new sr(0,-1,0)}static left(){return new sr(-1,0,0)}static right(){return new sr(1,0,0)}static forward(){return new sr(0,0,1)}static back(){return new sr(0,0,-1)}add(e){return new sr(this.x+e.x,this.y+e.y,this.z+e.z)}subtract(e){return new sr(this.x-e.x,this.y-e.y,this.z-e.z)}multiply(e){return new sr(this.x*e,this.y*e,this.z*e)}divide(e){if(e===0)throw new Error("Division by zero");return new sr(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?sr.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 sr(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 sr(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t,this.z+(e.z-this.z)*t)}clone(){return new sr(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(KS,"Vector3");var Ge={scanlines:{opacity:.15,pattern:"horizontal",color:{r:0,g:0,b:0}},ambientEffect:{blur:30,scale:1.3,opacity:.7}},Ys={color:"rgba(144, 24, 24, 1)",lineWidth:1},$t=(r=>(r.None="none",r.Eighth="eighth",r.Quarter="quarter",r.Half="half",r.Integer="integer",r.Responsive="responsive",r))($t||{}),qS=(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))(qS||{});function Pv(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(Pv,"scalingModeToValue");function _f(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(_f,"valueToScalingMode");var on=(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))(on||{}),Fa=Object.defineProperty,QS=Object.getOwnPropertyDescriptor,JS=Object.getOwnPropertyNames,eI=Object.prototype.hasOwnProperty,tI=(r,e,t)=>e in r?Fa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,K=(r,e)=>Fa(r,"name",{value:e,configurable:!0}),dl=(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')}),rr=(r,e)=>()=>(r&&(e=r(r=0)),e),La=(r,e)=>{for(var t in e)Fa(r,t,{get:e[t],enumerable:!0})},rI=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of JS(e))!eI.call(r,i)&&i!==t&&Fa(r,i,{get:()=>e[i],enumerable:!(n=QS(e,i))||n.enumerable});return r},Go=r=>rI(Fa({},"__esModule",{value:!0}),r),F=(r,e,t)=>(tI(r,typeof e!="symbol"?e+"":e,t),t),$f,zv,Dv,Ov,Bv,Fv,Lv,_v,$v,Nv,Wv,Hv,Vv,jv,Yv,Gv,Xv,Zv,Kv,qv,Qv,Jv,e1,t1,r1,n1,i1,s1,o1,a1,l1,u1,c1,rh,nh,d1,ih,sh,oh,ah,lh,uh,yo=rr(()=>{$f=K(r=>r?2:1,"charCodeByteSize"),zv=6,Dv=6,Ov=6,Bv=7,Fv=5,Lv=3,_v=1,$v=6,Nv=4,Wv=5,Hv=2,Vv=8,jv=7,Yv=7,Gv=8,Xv=10,Zv=6,Kv=3,qv=9,Qv=15,Jv=51,e1=5,t1=6,r1=4,n1=3,i1=3,s1=4,o1=5,a1=4,l1=2,u1=5,c1=5,rh=5,nh=5,d1=3,ih=8,sh=6,oh=3,ah=8,lh=3,uh=4}),qg,nI=rr(()=>{qg=(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))(qg||{})});function iI(r){return r>=1&&r<=3}function sI(r){return r>=1&&r<=4}function oI(r){switch(r){case 1:return"CreateInstance";case 2:return"UpdateInstance";case 3:return"RemoveInstance";default:return`Unknown(0x${r.toString(16)})`}}function aI(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)})`}}var Qg,Jg,lI=rr(()=>{Qg=(r=>(r[r.CreateInstance=1]="CreateInstance",r[r.UpdateInstance=2]="UpdateInstance",r[r.RemoveInstance=3]="RemoveInstance",r))(Qg||{}),Jg=(r=>(r[r.Click=1]="Click",r[r.Change=2]="Change",r[r.Submit=3]="Submit",r[r.Select=4]="Select",r))(Jg||{}),K(iI,"isValidMacroOrderType"),K(sI,"isValidMacroEventType"),K(oI,"getMacroOrderTypeName"),K(aI,"getMacroEventTypeName")}),Fc,ie,tn=rr(()=>{Fc=class qi{constructor(e){F(this,"data"),F(this,"view"),this.data=new Uint8Array(e),this.view=new DataView(this.data.buffer)}static from(e){let t=new qi(0);return t.data=e,t.view=new DataView(e.buffer,e.byteOffset,e.byteLength),t}static allocUnsafe(e){return new qi(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 qi.from(n)}subarray(e,t){let n=this.data.subarray(e,t);return qi.from(n)}toBuffer(){return typeof Buffer<"u"&&Buffer.from?Buffer.from(this.data):this.data}static fromNodeBuffer(e){return e instanceof Uint8Array?qi.from(e):qi.from(new Uint8Array(e))}},K(Fc,"BufferCompat"),ie=Fc}),h1={};La(h1,{VibrationOrderType:()=>ch});var ch,f1=rr(()=>{ch=(r=>(r[r.MobileVibrate=1]="MobileVibrate",r[r.MobileCancel=2]="MobileCancel",r[r.GamepadVibrate=16]="GamepadVibrate",r[r.GamepadCancel=17]="GamepadCancel",r))(ch||{})}),p1={};La(p1,{GamepadVibrateFlags:()=>hh,MobileVibrateFlags:()=>dh});var dh,hh,g1=rr(()=>{dh=(r=>(r[r.HasIntensity=1]="HasIntensity",r))(dh||{}),hh=(r=>(r[r.HasStartDelay=1]="HasStartDelay",r[r.AllGamepads=2]="AllGamepads",r))(hh||{})}),m1={};La(m1,{AudioOrderType:()=>fh,AudioTargetType:()=>ph,getAudioOrderTypeName:()=>v1,isValidAudioOrderType:()=>y1});function y1(r){return r>=1&&r<=9}function v1(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 fh,ph,w1=rr(()=>{fh=(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))(fh||{}),ph=(r=>(r[r.InstanceId=0]="InstanceId",r[r.SoundId=1]="SoundId",r[r.All=2]="All",r))(ph||{}),K(y1,"isValidAudioOrderType"),K(v1,"getAudioOrderTypeName")}),b1={};La(b1,{PlaySoundFlags:()=>gh,SoundEffectsFlags:()=>mh});var gh,mh,C1=rr(()=>{gh=(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))(gh||{}),mh=(r=>(r[r.HasLowpass=1]="HasLowpass",r[r.HasHighpass=2]="HasHighpass",r[r.HasReverb=4]="HasReverb",r))(mh||{})}),uI=rr(()=>{}),Or,cI=rr(()=>{Or=(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))(Or||{})}),Lc,x1,dI=rr(()=>{Lc=class{decode(e,t=0){this.checkSize(e,t,7);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;return{display:{id:i,originX:s,originY:o,sizeX:a,sizeY:l},bytesRead:7}}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`)}},K(Lc,"DisplayDecoder"),x1=Lc}),_c,S1,hI=rr(()=>{yo(),_c=class{constructor(){F(this,"charCodeSize",$f)}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.decodeClearOrder(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 g=e.readUInt8(s++),x=e.readUInt8(s++);return{shapeData:{posX:l,posY:u,width:c,height:d,filled:h,charCode:f,bgColorCode:g,fgColorCode:x},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++),g=e.readUInt8(s++);return{shapeData:{centerX:l,centerY:u,radius:c,filled:d,charCode:h,bgColorCode:p,fgColorCode:g},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++),g=e.readUInt8(s++);return{shapeData:{x1:l,y1:u,x2:c,y2:d,charCode:h,bgColorCode:p,fgColorCode:g},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 g=e.readUInt8(s++),x=e.readUInt8(s++);return{shapeData:{centerX:l,centerY:u,radiusX:c,radiusY:d,filled:h,charCode:f,bgColorCode:g,fgColorCode:x},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,[g,x]=this.readCharCode(e,s,i);s=x;let y=e.readUInt8(s++),m=e.readUInt8(s++);return{shapeData:{x1:l,y1:u,x2:c,y2:d,x3:h,y3:f,filled:p,charCode:g,bgColorCode:y,fgColorCode:m},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,g=Math.ceil(l*u/8);this.checkSize(e,t,i+g);let x=new Uint8Array(g);for(let y=0;y<g;y++)x[y]=e.readUInt8(s+y);return{order:{type:17,posX:o,posY:a,sizeX:l,sizeY:u,charCode:c,bgColorCode:h,fgColorCode:f,override:p,mask:x},bytesRead:i+g}}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[g,x]=this.readCharCode(e,s,n);s=x,h.push({charCode:g,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[g,x]=this.readCharCode(e,s,n);s=x,h.push({charCode:g,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}}decodeClearOrder(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`)}},K(_c,"OrderDecoder"),S1=_c}),em,$c,I1,fI=rr(()=>{hI(),em=64,$c=class{constructor(){F(this,"orderDecoder"),this.orderDecoder=new S1}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&em)!==0,f=[],p=n;for(let g=0;g<d;g++){let x=this.orderDecoder.decode(e,p,h);f.push(x.order),p+=x.bytesRead}return{layer:{id:i,updateFlags:s,zIndex:o,originX:a,originY:l,width:u,height:c,orderCount:d,orders:f,is16bit:h},bytesRead:p-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`)}},K($c,"LayerDecoder"),I1=$c}),Nc,k1,E1=rr(()=>{Nc=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`)}},K(Nc,"AudioOrderDecoder"),k1=Nc}),Wc,M1,T1=rr(()=>{Wc=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}}},K(Wc,"VibrationOrderDecoder"),M1=Wc}),Hc,U1,pI=rr(()=>{Hc=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}}},K(Hc,"MacroOrderDecoder"),U1=Hc}),Vc,A1,R1=rr(()=>{Vc=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}}},K(Vc,"PostProcessOrderDecoder"),A1=Vc}),P1={};La(P1,{UpdatePacketDecoder:()=>z1});var jc,z1,D1=rr(()=>{dI(),fI(),E1(),T1(),pI(),R1(),tn(),jc=class{constructor(){F(this,"displayDecoder"),F(this,"layerDecoder"),F(this,"audioOrderDecoder"),F(this,"vibrationOrderDecoder"),F(this,"macroOrderDecoder"),F(this,"postProcessOrderDecoder"),this.displayDecoder=new x1,this.layerDecoder=new I1,this.audioOrderDecoder=new k1,this.vibrationOrderDecoder=new M1,this.macroOrderDecoder=new U1,this.postProcessOrderDecoder=new A1}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 U=0;U<o;U++){let z=this.displayDecoder.decode(n,i);a.push(z.display),i+=z.bytesRead,l+=z.bytesRead}this.checkSize(n,i,2);let u=n.readUInt16BE(i);i+=2;let c=[],d=0;for(let U=0;U<u;U++){let z=this.layerDecoder.decode(n,i);c.push({...z.layer,byteSize:z.bytesRead}),i+=z.bytesRead,d+=z.bytesRead}this.checkSize(n,i,1);let h=n.readUInt8(i);i+=1;let f=[],p=0;for(let U=0;U<h;U++){let z=this.audioOrderDecoder.decode(n,i);f.push(z.order),i+=z.bytesRead,p+=z.bytesRead}this.checkSize(n,i,1);let g=n.readUInt8(i);i+=1;let x=[],y=0;for(let U=0;U<g;U++){let z=this.vibrationOrderDecoder.decode(n,i);x.push(z.order),i+=z.bytesRead,y+=z.bytesRead}this.checkSize(n,i,1);let m=n.readUInt8(i);i+=1;let v=[],b=0;for(let U=0;U<m;U++){let z=this.macroOrderDecoder.decode(n,i);v.push(z.order),i+=z.bytesRead,b+=z.bytesRead}this.checkSize(n,i,1);let I=n.readUInt8(i);i+=1;let S=[],M=0;for(let U=0;U<I;U++){let z=this.postProcessOrderDecoder.decode(n.toUint8Array(),i);S.push(z.order),i+=z.bytesRead,M+=z.bytesRead}return{tick:s,displayCount:o,displays:a,layerCount:u,layers:c,audioOrderCount:h,audioOrders:f,vibrationOrderCount:g,vibrationOrders:x,macroOrderCount:m,macroOrders:v,postProcessOrderCount:I,postProcessOrders:S,__byteSizes:{displays:l,layers:d,audioOrders:p,vibrationOrders:y,macroOrders:b,postProcessOrders:M}}}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,i+=o*7,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`)}},K(jc,"UpdatePacketDecoder"),z1=jc}),O1=class{constructor(e=0,t=60,n=40){if(F(this,"id"),F(this,"origin"),F(this,"size"),F(this,"previousOrigin",new Ht(0,0)),F(this,"previousSize",new Ht(0,0)),F(this,"toDraw",[]),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 Ht(0,0),this.size=new Ht(t,n),this.toDraw=new Array(this.size.x*this.size.y).fill(null).map(()=>({charCode:0,fgColorCode:0,bgColorCode:0}))}getId(){return this.id}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,this.toDraw=new Array(this.size.x*this.size.y).fill(null).map(()=>({charCode:0,fgColorCode:0,bgColorCode:0}))}getDebugInfo(){return{id:this.id,origin:{x:this.origin.x,y:this.origin.y},size:{x:this.size.x,y:this.size.y}}}};K(O1,"Display");var gI=O1,B1=class{constructor(e=65536,t=!1){F(this,"charCodes"),F(this,"fgColors"),F(this,"bgColors"),F(this,"size"),F(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}};K(B1,"CellBuffer");var F1=B1,L1=class{constructor(e){F(this,"data"),F(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}};K(L1,"CharCodeBuffer");var mI=L1,yI=new Map([[9474,179],[9472,196],[9484,218],[9488,191],[9492,192],[9496,217],[9500,195],[9508,180],[9516,194],[9524,193],[9532,197],[9553,186],[9552,205],[9556,201],[9559,187],[9562,200],[9565,188],[9568,204],[9571,185],[9574,203],[9577,202],[9580,206],[9608,219],[9619,178],[9618,177],[9617,176],[9600,223],[9604,220],[9612,221],[9616,222]]);function uu(r){if(r<128)return r;let e=yI.get(r);return e!==void 0?e:r&255}K(uu,"unicodeToCp437");var _1=class{constructor(){F(this,"currentWidth",256),F(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.rasterizeClear(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),h=uu(d);t.set(c,h,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),g=uu(p);t.set(f,g,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 g=d*this.currentWidth+f;t.set(g,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 g=h*this.currentWidth+p;t.set(g,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,g=n,x=i;for(;this.setCell(g,x,a,l,u,t),!(g===s&&x===o);){let y=2*p;y>-d&&(p-=d,g+=h),y<c&&(p+=c,x+=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,g=t;for(;this.setCell(p,g,s,o,a,l),!(p===n&&g===i);){let x=2*f;x>-c&&(f-=c,p+=d),x<u&&(f+=u,g+=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 g=h*this.currentWidth+p;t.set(g,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)),g=Math.round(i+o*Math.sin(f));this.setCell(p,g,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((v,b)=>v.y-b.y),[p,g,x]=f,y=K((v,b,I)=>{let S=Math.round(Math.min(b,I)),M=Math.round(Math.max(b,I));for(let U=S;U<=M;U++)if(U>=0&&U<this.currentWidth&&v>=0&&v<this.currentHeight){let z=v*this.currentWidth+U;t.set(z,c,h,d)}},"drawLine"),m=K((v,b,I,S,M)=>S===b?I:I+(v-b)*(M-I)/(S-b),"interpolate");for(let v=p.y;v<=g.y;v++){let b=m(v,p.y,p.x,x.y,x.x),I=m(v,p.y,p.x,g.y,g.x);y(v,b,I)}for(let v=g.y+1;v<=x.y;v++){let b=m(v,p.y,p.x,x.y,x.x),I=m(v,g.y,g.x,x.y,x.x);y(v,b,I)}}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,g=t;for(;this.setCell(p,g,s,o,a,l),!(p===n&&g===i);){let x=2*f;x>-c&&(f-=c,p+=d),x<u&&(f+=u,g+=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 g=n+p;if(g<0||g>=this.currentWidth)continue;let x=h*s+p,y=Math.floor(x/8),m=x%8,v=(d[y]&1<<m)!==0,b=f*this.currentWidth+g;v?t.set(b,a,u,l):c&&t.set(b,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,g=Math.floor(p/4),x=p%4*2,y=u[g]>>x&3,m=d*this.currentWidth+f;if(y>0){let v=l[y-1];t.set(m,v.charCode,v.fgColorCode,v.bgColorCode)}else a&&t.set(m,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,g=Math.floor(p/2),x=p%2*4,y=u[g]>>x&15,m=d*this.currentWidth+f;if(y>0){let v=l[y-1];t.set(m,v.charCode,v.fgColorCode,v.bgColorCode)}else a&&t.set(m,255,255,255)}}}rasterizeClear(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 g=d*u.sizeX+h,x=c.get(g);this.setCell(f,p,x,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),g=l.getFgColorCode(f),x=l.getBgColorCode(f);this.setCell(d,h,p,x,g,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 g=d*l.sizeX+h,x=c.get(g);this.setCell(f,p,x,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),g=l.getFgColorCode(f),x=l.getBgColorCode(f);this.setCell(d,h,p,x,g,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),g=l.getFgColorCode(f),x=l.getBgColorCode(f);this.setCell(d,h,p,x,g,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}};K(_1,"LayerRasterizer");var vI=_1,Yc=255,yh=class Xo{constructor(e,t,n,i,s){if(F(this,"id",0),F(this,"name"),F(this,"origin"),F(this,"orders",[]),F(this,"zOrder",0),F(this,"data"),F(this,"width"),F(this,"height"),F(this,"isStatic",!1),F(this,"spriteRegistry"),F(this,"mode","server"),F(this,"charCodeMode"),F(this,"previousOrigin"),F(this,"previousZOrder"),F(this,"enabled",!0),F(this,"useSetMode",!1),F(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={isStatic:s}:s&&(o=s),this.origin=e,this.zOrder=t,this.name=o.name,this.width=n,this.height=i,this.isStatic=o.isStatic??!1,this.charCodeMode=o.charCodeMode??"8bit";let a=this.charCodeMode==="16bit";this.data=new F1(n*i,a),this.previousOrigin=new Ht(e.x,e.y),this.previousZOrder=t}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")&&Xo.rasterizer.rasterizeOrders(this.orders,this.data,this.width,this.height,this.spriteRegistry)}addTemporaryOrders(e){(this.mode==="client"||this.mode==="standalone")&&Xo.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")&&Xo.rasterizer.rasterizeOrders(e,this.data,this.width,this.height,this.spriteRegistry)}clearOrders(){this.orders=[],(this.mode==="client"||this.mode==="standalone")&&Xo.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,isStatic:this.isStatic,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}}setId(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)}setStatic(e){this.isStatic=e}getStatic(){return this.isStatic}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>Yc&&(console.error(`[UTSP] ⚠️ CRITICAL: Layer ${this.id} has ${this.orders.length} orders, but max is ${Yc}!
|
|
40
|
+
`+s.stack}return{value:r,source:e,stack:i,digest:null}}function zc(r,e,t){return{value:r,source:null,stack:t??null,digest:e??null}}function jd(r,e){try{console.error(e.value)}catch(t){setTimeout(function(){throw t})}}var oI=typeof WeakMap=="function"?WeakMap:Map;function av(r,e,t){t=ei(-1,t),t.tag=3,t.payload={element:null};var n=e.value;return t.callback=function(){su||(su=!0,th=n),jd(r,e)},t}function lv(r,e,t){t=ei(-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(){jd(r,e)}}var s=r.stateNode;return s!==null&&typeof s.componentDidCatch=="function"&&(t.callback=function(){jd(r,e),typeof n!="function"&&(Ti===null?Ti=new Set([this]):Ti.add(this));var o=e.stack;this.componentDidCatch(e.value,{componentStack:o!==null?o:""})}),t}function Og(r,e,t){var n=r.pingCache;if(n===null){n=r.pingCache=new oI;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=bI.bind(null,r,e,t),e.then(r,r))}function Bg(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 Fg(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=ei(-1,1),e.tag=2,Mi(t,e,1))),t.lanes|=1),r)}var aI=ai.ReactCurrentOwner,Fr=!1;function kr(r,e,t,n){e.child=r===null?F0(e,null,t,n):so(e,r.child,t,n)}function Lg(r,e,t,n,i){t=t.render;var s=e.ref;return Js(e,i),n=xf(r,e,t,n,s,i),t=If(),r!==null&&!Fr?(e.updateQueue=r.updateQueue,e.flags&=-2053,r.lanes&=~i,oi(r,e,i)):(gt&&t&&cf(e),e.flags|=1,kr(r,e,n,i),e.child)}function _g(r,e,t,n,i){if(r===null){var s=t.type;return typeof s=="function"&&!zf(s)&&s.defaultProps===void 0&&t.compare===null&&t.defaultProps===void 0?(e.tag=15,e.type=s,uv(r,e,s,n,i)):(r=Pl(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:Ca,t(o,n)&&r.ref===e.ref)return oi(r,e,i)}return e.flags|=1,r=Ai(s,n),r.ref=e.ref,r.return=e,e.child=r}function uv(r,e,t,n,i){if(r!==null){var s=r.memoizedProps;if(Ca(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,oi(r,e,i)}return Yd(r,e,t,n,i)}function cv(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(Ys,Xr),Xr|=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(Ys,Xr),Xr|=r,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=s!==null?s.baseLanes:t,rt(Ys,Xr),Xr|=n}else s!==null?(n=s.baseLanes|t,e.memoizedState=null):n=t,rt(Ys,Xr),Xr|=n;return kr(r,e,i,t),e.child}function dv(r,e){var t=e.ref;(r===null&&t!==null||r!==null&&r.ref!==t)&&(e.flags|=512,e.flags|=2097152)}function Yd(r,e,t,n,i){var s=_r(t)?ls:vr.current;return s=no(e,s),Js(e,i),t=xf(r,e,t,n,s,i),n=If(),r!==null&&!Fr?(e.updateQueue=r.updateQueue,e.flags&=-2053,r.lanes&=~i,oi(r,e,i)):(gt&&n&&cf(e),e.flags|=1,kr(r,e,t,i),e.child)}function $g(r,e,t,n,i){if(_r(t)){var s=!0;Zl(e)}else s=!1;if(Js(e,i),e.stateNode===null)Ul(r,e),ov(e,t,n),Vd(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=pn(u):(u=_r(t)?ls:vr.current,u=no(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)&&Dg(e,o,n,u),yi=!1;var h=e.memoizedState;o.state=h,eu(e,n,o,i),l=e.memoizedState,a!==n||h!==l||Lr.current||yi?(typeof c=="function"&&(Hd(e,t,c,n),l=e.memoizedState),(a=yi||zg(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,_0(r,e),a=e.memoizedProps,u=e.type===e.elementType?a:xn(e.type,a),o.props=u,d=e.pendingProps,h=o.context,l=t.contextType,typeof l=="object"&&l!==null?l=pn(l):(l=_r(t)?ls:vr.current,l=no(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)&&Dg(e,o,n,l),yi=!1,h=e.memoizedState,o.state=h,eu(e,n,o,i);var p=e.memoizedState;a!==d||h!==p||Lr.current||yi?(typeof f=="function"&&(Hd(e,t,f,n),p=e.memoizedState),(u=yi||zg(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 Gd(r,e,t,n,s,i)}function Gd(r,e,t,n,i,s){dv(r,e);var o=(e.flags&128)!==0;if(!n&&!o)return i&&kg(e,t,!1),oi(r,e,s);n=e.stateNode,aI.current=e;var a=o&&typeof t.getDerivedStateFromError!="function"?null:n.render();return e.flags|=1,r!==null&&o?(e.child=so(e,r.child,null,s),e.child=so(e,null,a,s)):kr(r,e,a,s),e.memoizedState=n.state,i&&kg(e,t,!0),e.child}function hv(r){var e=r.stateNode;e.pendingContext?Sg(r,e.pendingContext,e.pendingContext!==e.context):e.context&&Sg(r,e.context,!1),vf(r,e.containerInfo)}function Ng(r,e,t,n,i){return io(),hf(i),e.flags|=256,kr(r,e,t,n),e.child}var Xd={dehydrated:null,treeContext:null,retryLane:0};function Zd(r){return{baseLanes:r,cachePool:null,transitions:null}}function fv(r,e,t){var n=e.pendingProps,i=wt.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(wt,i&1),r===null)return Nd(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=Mu(o,n,0,null),r=os(r,n,t,null),s.return=e,r.return=e,s.sibling=r,e.child=s,e.child.memoizedState=Zd(t),e.memoizedState=Xd,r):Ef(e,o));if(i=r.memoizedState,i!==null&&(a=i.dehydrated,a!==null))return lI(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=Ai(i,l),n.subtreeFlags=i.subtreeFlags&14680064),a!==null?s=Ai(a,s):(s=os(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?Zd(t):{baseLanes:o.baseLanes|t,cachePool:null,transitions:o.transitions},s.memoizedState=o,s.childLanes=r.childLanes&~t,e.memoizedState=Xd,n}return s=r.child,r=s.sibling,n=Ai(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 Ef(r,e){return e=Mu({mode:"visible",children:e},r.mode,0,null),e.return=r,r.child=e}function al(r,e,t,n){return n!==null&&hf(n),so(e,r.child,null,t),r=Ef(e,e.pendingProps.children),r.flags|=2,e.memoizedState=null,r}function lI(r,e,t,n,i,s,o){if(t)return e.flags&256?(e.flags&=-257,n=zc(Error(ee(422))),al(r,e,o,n)):e.memoizedState!==null?(e.child=r.child,e.flags|=128,null):(s=n.fallback,i=e.mode,n=Mu({mode:"visible",children:n.children},i,0,null),s=os(s,i,o,null),s.flags|=2,n.return=e,s.return=e,n.sibling=s,e.child=n,e.mode&1&&so(e,r.child,null,o),e.child.memoizedState=Zd(o),e.memoizedState=Xd,s);if(!(e.mode&1))return al(r,e,o,null);if(i.data==="$!"){if(n=i.nextSibling&&i.nextSibling.dataset,n)var a=n.dgst;return n=a,s=Error(ee(419)),n=zc(s,n,void 0),al(r,e,o,n)}if(a=(o&r.childLanes)!==0,Fr||a){if(n=tr,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,si(r,i),Un(n,r,i,-1))}return Pf(),n=zc(Error(ee(421))),al(r,e,o,n)}return i.data==="$?"?(e.flags|=128,e.child=r.child,e=CI.bind(null,r),i._reactRetry=e,null):(r=s.treeContext,Kr=Ei(i.nextSibling),qr=e,gt=!0,En=null,r!==null&&(un[cn++]=Qn,un[cn++]=Jn,un[cn++]=us,Qn=r.id,Jn=r.overflow,us=e),e=Ef(e,n.children),e.flags|=4096,e)}function Wg(r,e,t){r.lanes|=e;var n=r.alternate;n!==null&&(n.lanes|=e),Wd(r.return,e,t)}function Dc(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 pv(r,e,t){var n=e.pendingProps,i=n.revealOrder,s=n.tail;if(kr(r,e,n.children,t),n=wt.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&&Wg(r,t,e);else if(r.tag===19)Wg(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(wt,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&&tu(r)===null&&(i=t),t=t.sibling;t=i,t===null?(i=e.child,e.child=null):(i=t.sibling,t.sibling=null),Dc(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&&tu(r)===null){e.child=i;break}r=i.sibling,i.sibling=t,t=i,i=r}Dc(e,!0,t,null,s);break;case"together":Dc(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function Ul(r,e){!(e.mode&1)&&r!==null&&(r.alternate=null,e.alternate=null,e.flags|=2)}function oi(r,e,t){if(r!==null&&(e.dependencies=r.dependencies),ds|=e.lanes,!(t&e.childLanes))return null;if(r!==null&&e.child!==r.child)throw Error(ee(153));if(e.child!==null){for(r=e.child,t=Ai(r,r.pendingProps),e.child=t,t.return=e;r.sibling!==null;)r=r.sibling,t=t.sibling=Ai(r,r.pendingProps),t.return=e;t.sibling=null}return e.child}function uI(r,e,t){switch(e.tag){case 3:hv(e),io();break;case 5:$0(e);break;case 1:_r(e.type)&&Zl(e);break;case 4:vf(e,e.stateNode.containerInfo);break;case 10:var n=e.type._context,i=e.memoizedProps.value;rt(Ql,n._currentValue),n._currentValue=i;break;case 13:if(n=e.memoizedState,n!==null)return n.dehydrated!==null?(rt(wt,wt.current&1),e.flags|=128,null):t&e.child.childLanes?fv(r,e,t):(rt(wt,wt.current&1),r=oi(r,e,t),r!==null?r.sibling:null);rt(wt,wt.current&1);break;case 19:if(n=(t&e.childLanes)!==0,r.flags&128){if(n)return pv(r,e,t);e.flags|=128}if(i=e.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),rt(wt,wt.current),n)break;return null;case 22:case 23:return e.lanes=0,cv(r,e,t)}return oi(r,e,t)}var gv,Kd,mv,yv;gv=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}};Kd=function(){};mv=function(r,e,t,n){var i=r.memoizedProps;if(i!==n){r=e.stateNode,is(Vn.current);var s=null;switch(t){case"input":i=vd(r,i),n=vd(r,n),s=[];break;case"select":i=Ct({},i,{value:void 0}),n=Ct({},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=Gl)}Id(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"&&(pa.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"&&(pa.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)}};yv=function(r,e,t,n){t!==n&&(e.flags|=4)};function Fo(r,e){if(!gt)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 gr(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 cI(r,e,t){var n=e.pendingProps;switch(df(e),e.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return gr(e),null;case 1:return _r(e.type)&&Xl(),gr(e),null;case 3:return n=e.stateNode,oo(),ut(Lr),ut(vr),bf(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(r===null||r.child===null)&&(sl(e)?e.flags|=4:r===null||r.memoizedState.isDehydrated&&!(e.flags&256)||(e.flags|=1024,En!==null&&(ih(En),En=null))),Kd(r,e),gr(e),null;case 5:wf(e);var i=is(Ea.current);if(t=e.type,r!==null&&e.stateNode!=null)mv(r,e,t,n,i),r.ref!==e.ref&&(e.flags|=512,e.flags|=2097152);else{if(!n){if(e.stateNode===null)throw Error(ee(166));return gr(e),null}if(r=is(Vn.current),sl(e)){n=e.stateNode,t=e.type;var s=e.memoizedProps;switch(n[Wn]=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<Go.length;i++)at(Go[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":qp(n,s),at("invalid",n);break;case"select":n._wrapperState={wasMultiple:!!s.multiple},at("invalid",n);break;case"textarea":Jp(n,s),at("invalid",n)}Id(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&&il(n.textContent,a,r),i=["children",a]):typeof a=="number"&&n.textContent!==""+a&&(s.suppressHydrationWarning!==!0&&il(n.textContent,a,r),i=["children",""+a]):pa.hasOwnProperty(o)&&a!=null&&o==="onScroll"&&at("scroll",n)}switch(t){case"input":Ka(n),Qp(n,s,!0);break;case"textarea":Ka(n),eg(n);break;case"select":case"option":break;default:typeof s.onClick=="function"&&(n.onclick=Gl)}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=jy(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[Wn]=e,r[Sa]=n,gv(r,e,!1,!1),e.stateNode=r;e:{switch(o=Sd(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<Go.length;i++)at(Go[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":qp(r,n),i=vd(r,n),at("invalid",r);break;case"option":i=n;break;case"select":r._wrapperState={wasMultiple:!!n.multiple},i=Ct({},n,{value:void 0}),at("invalid",r);break;case"textarea":Jp(r,n),i=Cd(r,n),at("invalid",r);break;default:i=n}Id(t,i),a=i;for(s in a)if(a.hasOwnProperty(s)){var l=a[s];s==="style"?Xy(r,l):s==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,l!=null&&Yy(r,l)):s==="children"?typeof l=="string"?(t!=="textarea"||l!=="")&&ga(r,l):typeof l=="number"&&ga(r,""+l):s!=="suppressContentEditableWarning"&&s!=="suppressHydrationWarning"&&s!=="autoFocus"&&(pa.hasOwnProperty(s)?l!=null&&s==="onScroll"&&at("scroll",r):l!=null&&Zh(r,s,l,o))}switch(t){case"input":Ka(r),Qp(r,n,!1);break;case"textarea":Ka(r),eg(r);break;case"option":n.value!=null&&r.setAttribute("value",""+Di(n.value));break;case"select":r.multiple=!!n.multiple,s=n.value,s!=null?Zs(r,!!n.multiple,s,!1):n.defaultValue!=null&&Zs(r,!!n.multiple,n.defaultValue,!0);break;default:typeof i.onClick=="function"&&(r.onclick=Gl)}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 gr(e),null;case 6:if(r&&e.stateNode!=null)yv(r,e,r.memoizedProps,n);else{if(typeof n!="string"&&e.stateNode===null)throw Error(ee(166));if(t=is(Ea.current),is(Vn.current),sl(e)){if(n=e.stateNode,t=e.memoizedProps,n[Wn]=e,(s=n.nodeValue!==t)&&(r=qr,r!==null))switch(r.tag){case 3:il(n.nodeValue,t,(r.mode&1)!==0);break;case 5:r.memoizedProps.suppressHydrationWarning!==!0&&il(n.nodeValue,t,(r.mode&1)!==0)}s&&(e.flags|=4)}else n=(t.nodeType===9?t:t.ownerDocument).createTextNode(n),n[Wn]=e,e.stateNode=n}return gr(e),null;case 13:if(ut(wt),n=e.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(gt&&Kr!==null&&e.mode&1&&!(e.flags&128))O0(),io(),e.flags|=98560,s=!1;else if(s=sl(e),n!==null&&n.dehydrated!==null){if(r===null){if(!s)throw Error(ee(318));if(s=e.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(ee(317));s[Wn]=e}else io(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;gr(e),s=!1}else En!==null&&(ih(En),En=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||wt.current&1?Vt===0&&(Vt=3):Pf())),e.updateQueue!==null&&(e.flags|=4),gr(e),null);case 4:return oo(),Kd(r,e),r===null&&xa(e.stateNode.containerInfo),gr(e),null;case 10:return gf(e.type._context),gr(e),null;case 17:return _r(e.type)&&Xl(),gr(e),null;case 19:if(ut(wt),s=e.memoizedState,s===null)return gr(e),null;if(n=(e.flags&128)!==0,o=s.rendering,o===null)if(n)Fo(s,!1);else{if(Vt!==0||r!==null&&r.flags&128)for(r=e.child;r!==null;){if(o=tu(r),o!==null){for(e.flags|=128,Fo(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(wt,wt.current&1|2),e.child}r=r.sibling}s.tail!==null&&Ut()>lo&&(e.flags|=128,n=!0,Fo(s,!1),e.lanes=4194304)}else{if(!n)if(r=tu(o),r!==null){if(e.flags|=128,n=!0,t=r.updateQueue,t!==null&&(e.updateQueue=t,e.flags|=4),Fo(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!gt)return gr(e),null}else 2*Ut()-s.renderingStartTime>lo&&t!==1073741824&&(e.flags|=128,n=!0,Fo(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=Ut(),e.sibling=null,t=wt.current,rt(wt,n?t&1|2:t&1),e):(gr(e),null);case 22:case 23:return Rf(),n=e.memoizedState!==null,r!==null&&r.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?Xr&1073741824&&(gr(e),e.subtreeFlags&6&&(e.flags|=8192)):gr(e),null;case 24:return null;case 25:return null}throw Error(ee(156,e.tag))}function dI(r,e){switch(df(e),e.tag){case 1:return _r(e.type)&&Xl(),r=e.flags,r&65536?(e.flags=r&-65537|128,e):null;case 3:return oo(),ut(Lr),ut(vr),bf(),r=e.flags,r&65536&&!(r&128)?(e.flags=r&-65537|128,e):null;case 5:return wf(e),null;case 13:if(ut(wt),r=e.memoizedState,r!==null&&r.dehydrated!==null){if(e.alternate===null)throw Error(ee(340));io()}return r=e.flags,r&65536?(e.flags=r&-65537|128,e):null;case 19:return ut(wt),null;case 4:return oo(),null;case 10:return gf(e.type._context),null;case 22:case 23:return Rf(),null;case 24:return null;default:return null}}var ll=!1,mr=!1,hI=typeof WeakSet=="function"?WeakSet:Set,fe=null;function js(r,e){var t=r.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(n){Et(r,e,n)}else t.current=null}function qd(r,e,t){try{t()}catch(n){Et(r,e,n)}}var Hg=!1;function fI(r,e){if(Dd=Vl,r=x0(),uf(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(Od={focusedElem:r,selectionRange:t},Vl=!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 g=p.memoizedProps,C=p.memoizedState,y=e.stateNode,m=y.getSnapshotBeforeUpdate(e.elementType===e.type?g:xn(e.type,g),C);y.__reactInternalSnapshotBeforeUpdate=m}break;case 3:var v=e.stateNode.containerInfo;v.nodeType===1?v.textContent="":v.nodeType===9&&v.documentElement&&v.removeChild(v.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ee(163))}}catch(b){Et(e,e.return,b)}if(r=e.sibling,r!==null){r.return=e.return,fe=r;break}fe=e.return}return p=Hg,Hg=!1,p}function aa(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&&qd(e,t,s)}i=i.next}while(i!==n)}}function ku(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 Qd(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 vv(r){var e=r.alternate;e!==null&&(r.alternate=null,vv(e)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(e=r.stateNode,e!==null&&(delete e[Wn],delete e[Sa],delete e[Ld],delete e[Z2],delete e[K2])),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 wv(r){return r.tag===5||r.tag===3||r.tag===4}function Vg(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||wv(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 Jd(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=Gl));else if(n!==4&&(r=r.child,r!==null))for(Jd(r,e,t),r=r.sibling;r!==null;)Jd(r,e,t),r=r.sibling}function eh(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(eh(r,e,t),r=r.sibling;r!==null;)eh(r,e,t),r=r.sibling}var ar=null,In=!1;function pi(r,e,t){for(t=t.child;t!==null;)bv(r,e,t),t=t.sibling}function bv(r,e,t){if(Hn&&typeof Hn.onCommitFiberUnmount=="function")try{Hn.onCommitFiberUnmount(yu,t)}catch{}switch(t.tag){case 5:mr||js(t,e);case 6:var n=ar,i=In;ar=null,pi(r,e,t),ar=n,In=i,ar!==null&&(In?(r=ar,t=t.stateNode,r.nodeType===8?r.parentNode.removeChild(t):r.removeChild(t)):ar.removeChild(t.stateNode));break;case 18:ar!==null&&(In?(r=ar,t=t.stateNode,r.nodeType===8?Mc(r.parentNode,t):r.nodeType===1&&Mc(r,t),wa(r)):Mc(ar,t.stateNode));break;case 4:n=ar,i=In,ar=t.stateNode.containerInfo,In=!0,pi(r,e,t),ar=n,In=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)&&qd(t,e,o),i=i.next}while(i!==n)}pi(r,e,t);break;case 1:if(!mr&&(js(t,e),n=t.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=t.memoizedProps,n.state=t.memoizedState,n.componentWillUnmount()}catch(a){Et(t,e,a)}pi(r,e,t);break;case 21:pi(r,e,t);break;case 22:t.mode&1?(mr=(n=mr)||t.memoizedState!==null,pi(r,e,t),mr=n):pi(r,e,t);break;default:pi(r,e,t)}}function jg(r){var e=r.updateQueue;if(e!==null){r.updateQueue=null;var t=r.stateNode;t===null&&(t=r.stateNode=new hI),e.forEach(function(n){var i=xI.bind(null,r,n);t.has(n)||(t.add(n),n.then(i,i))})}}function wn(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,In=!1;break e;case 3:ar=a.stateNode.containerInfo,In=!0;break e;case 4:ar=a.stateNode.containerInfo,In=!0;break e}a=a.return}if(ar===null)throw Error(ee(160));bv(s,o,i),ar=null,In=!1;var l=i.alternate;l!==null&&(l.return=null),i.return=null}catch(u){Et(i,e,u)}}if(e.subtreeFlags&12854)for(e=e.child;e!==null;)Cv(e,r),e=e.sibling}function Cv(r,e){var t=r.alternate,n=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:if(wn(e,r),_n(r),n&4){try{aa(3,r,r.return),ku(3,r)}catch(g){Et(r,r.return,g)}try{aa(5,r,r.return)}catch(g){Et(r,r.return,g)}}break;case 1:wn(e,r),_n(r),n&512&&t!==null&&js(t,t.return);break;case 5:if(wn(e,r),_n(r),n&512&&t!==null&&js(t,t.return),r.flags&32){var i=r.stateNode;try{ga(i,"")}catch(g){Et(r,r.return,g)}}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&&Hy(i,s),Sd(a,o);var u=Sd(a,s);for(o=0;o<l.length;o+=2){var c=l[o],d=l[o+1];c==="style"?Xy(i,d):c==="dangerouslySetInnerHTML"?Yy(i,d):c==="children"?ga(i,d):Zh(i,c,d,u)}switch(a){case"input":wd(i,s);break;case"textarea":Vy(i,s);break;case"select":var h=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!s.multiple;var f=s.value;f!=null?Zs(i,!!s.multiple,f,!1):h!==!!s.multiple&&(s.defaultValue!=null?Zs(i,!!s.multiple,s.defaultValue,!0):Zs(i,!!s.multiple,s.multiple?[]:"",!1))}i[Sa]=s}catch(g){Et(r,r.return,g)}}break;case 6:if(wn(e,r),_n(r),n&4){if(r.stateNode===null)throw Error(ee(162));i=r.stateNode,s=r.memoizedProps;try{i.nodeValue=s}catch(g){Et(r,r.return,g)}}break;case 3:if(wn(e,r),_n(r),n&4&&t!==null&&t.memoizedState.isDehydrated)try{wa(e.containerInfo)}catch(g){Et(r,r.return,g)}break;case 4:wn(e,r),_n(r);break;case 13:wn(e,r),_n(r),i=r.child,i.flags&8192&&(s=i.memoizedState!==null,i.stateNode.isHidden=s,!s||i.alternate!==null&&i.alternate.memoizedState!==null||(Uf=Ut())),n&4&&jg(r);break;case 22:if(c=t!==null&&t.memoizedState!==null,r.mode&1?(mr=(u=mr)||c,wn(e,r),mr=u):wn(e,r),_n(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:aa(4,h,h.return);break;case 1:js(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(g){Et(n,t,g)}}break;case 5:js(h,h.return);break;case 22:if(h.memoizedState!==null){Gg(d);continue}}f!==null?(f.return=h,fe=f):Gg(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=Gy("display",o))}catch(g){Et(r,r.return,g)}}}else if(d.tag===6){if(c===null)try{d.stateNode.nodeValue=u?"":d.memoizedProps}catch(g){Et(r,r.return,g)}}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:wn(e,r),_n(r),n&4&&jg(r);break;case 21:break;default:wn(e,r),_n(r)}}function _n(r){var e=r.flags;if(e&2){try{e:{for(var t=r.return;t!==null;){if(wv(t)){var n=t;break e}t=t.return}throw Error(ee(160))}switch(n.tag){case 5:var i=n.stateNode;n.flags&32&&(ga(i,""),n.flags&=-33);var s=Vg(r);eh(r,s,i);break;case 3:case 4:var o=n.stateNode.containerInfo,a=Vg(r);Jd(r,a,o);break;default:throw Error(ee(161))}}catch(l){Et(r,r.return,l)}r.flags&=-3}e&4096&&(r.flags&=-4097)}function pI(r,e,t){fe=r,xv(r)}function xv(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||ll;if(!o){var a=i.alternate,l=a!==null&&a.memoizedState!==null||mr;a=ll;var u=mr;if(ll=o,(mr=l)&&!u)for(fe=i;fe!==null;)o=fe,l=o.child,o.tag===22&&o.memoizedState!==null?Xg(i):l!==null?(l.return=o,fe=l):Xg(i);for(;s!==null;)fe=s,xv(s),s=s.sibling;fe=i,ll=a,mr=u}Yg(r)}else i.subtreeFlags&8772&&s!==null?(s.return=i,fe=s):Yg(r)}}function Yg(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||ku(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:xn(e.type,t.memoizedProps);n.componentDidUpdate(i,t.memoizedState,n.__reactInternalSnapshotBeforeUpdate)}var s=e.updateQueue;s!==null&&Ag(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}Ag(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&&wa(d)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(ee(163))}mr||e.flags&512&&Qd(e)}catch(h){Et(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 Gg(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 Xg(r){for(;fe!==null;){var e=fe;try{switch(e.tag){case 0:case 11:case 15:var t=e.return;try{ku(4,e)}catch(l){Et(e,t,l)}break;case 1:var n=e.stateNode;if(typeof n.componentDidMount=="function"){var i=e.return;try{n.componentDidMount()}catch(l){Et(e,i,l)}}var s=e.return;try{Qd(e)}catch(l){Et(e,s,l)}break;case 5:var o=e.return;try{Qd(e)}catch(l){Et(e,o,l)}}}catch(l){Et(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 gI=Math.ceil,iu=ai.ReactCurrentDispatcher,Mf=ai.ReactCurrentOwner,fn=ai.ReactCurrentBatchConfig,Oe=0,tr=null,zt=null,lr=0,Xr=0,Ys=Li(0),Vt=0,Aa=null,ds=0,Eu=0,Tf=0,la=null,Br=null,Uf=0,lo=1/0,Kn=null,su=!1,th=null,Ti=null,ul=!1,xi=null,ou=0,ua=0,rh=null,Al=-1,Rl=0;function Tr(){return Oe&6?Ut():Al!==-1?Al:Al=Ut()}function Ui(r){return r.mode&1?Oe&2&&lr!==0?lr&-lr:Q2.transition!==null?(Rl===0&&(Rl=o0()),Rl):(r=Xe,r!==0||(r=window.event,r=r===void 0?16:f0(r.type)),r):1}function Un(r,e,t,n){if(50<ua)throw ua=0,rh=null,Error(ee(185));za(r,t,n),(!(Oe&2)||r!==tr)&&(r===tr&&(!(Oe&2)&&(Eu|=t),Vt===4&&bi(r,lr)),$r(r,n),t===1&&Oe===0&&!(e.mode&1)&&(lo=Ut()+500,xu&&_i()))}function $r(r,e){var t=r.callbackNode;Qx(r,e);var n=Hl(r,r===tr?lr:0);if(n===0)t!==null&&ng(t),r.callbackNode=null,r.callbackPriority=0;else if(e=n&-n,r.callbackPriority!==e){if(t!=null&&ng(t),e===1)r.tag===0?q2(Zg.bind(null,r)):P0(Zg.bind(null,r)),G2(function(){!(Oe&6)&&_i()}),t=null;else{switch(a0(n)){case 1:t=ef;break;case 4:t=i0;break;case 16:t=Wl;break;case 536870912:t=s0;break;default:t=Wl}t=Av(t,Iv.bind(null,r))}r.callbackPriority=e,r.callbackNode=t}}function Iv(r,e){if(Al=-1,Rl=0,Oe&6)throw Error(ee(327));var t=r.callbackNode;if(eo()&&r.callbackNode!==t)return null;var n=Hl(r,r===tr?lr:0);if(n===0)return null;if(n&30||n&r.expiredLanes||e)e=au(r,n);else{e=n;var i=Oe;Oe|=2;var s=kv();(tr!==r||lr!==e)&&(Kn=null,lo=Ut()+500,ss(r,e));do try{vI();break}catch(a){Sv(r,a)}while(!0);pf(),iu.current=s,Oe=i,zt!==null?e=0:(tr=null,lr=0,e=Vt)}if(e!==0){if(e===2&&(i=Ud(r),i!==0&&(n=i,e=nh(r,i))),e===1)throw t=Aa,ss(r,0),bi(r,n),$r(r,Ut()),t;if(e===6)bi(r,n);else{if(i=r.current.alternate,!(n&30)&&!mI(i)&&(e=au(r,n),e===2&&(s=Ud(r),s!==0&&(n=s,e=nh(r,s))),e===1))throw t=Aa,ss(r,0),bi(r,n),$r(r,Ut()),t;switch(r.finishedWork=i,r.finishedLanes=n,e){case 0:case 1:throw Error(ee(345));case 2:Ki(r,Br,Kn);break;case 3:if(bi(r,n),(n&130023424)===n&&(e=Uf+500-Ut(),10<e)){if(Hl(r,0)!==0)break;if(i=r.suspendedLanes,(i&n)!==n){Tr(),r.pingedLanes|=r.suspendedLanes&i;break}r.timeoutHandle=Fd(Ki.bind(null,r,Br,Kn),e);break}Ki(r,Br,Kn);break;case 4:if(bi(r,n),(n&4194240)===n)break;for(e=r.eventTimes,i=-1;0<n;){var o=31-Tn(n);s=1<<o,o=e[o],o>i&&(i=o),n&=~s}if(n=i,n=Ut()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*gI(n/1960))-n,10<n){r.timeoutHandle=Fd(Ki.bind(null,r,Br,Kn),n);break}Ki(r,Br,Kn);break;case 5:Ki(r,Br,Kn);break;default:throw Error(ee(329))}}}return $r(r,Ut()),r.callbackNode===t?Iv.bind(null,r):null}function nh(r,e){var t=la;return r.current.memoizedState.isDehydrated&&(ss(r,e).flags|=256),r=au(r,e),r!==2&&(e=Br,Br=t,e!==null&&ih(e)),r}function ih(r){Br===null?Br=r:Br.push.apply(Br,r)}function mI(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 bi(r,e){for(e&=~Tf,e&=~Eu,r.suspendedLanes|=e,r.pingedLanes&=~e,r=r.expirationTimes;0<e;){var t=31-Tn(e),n=1<<t;r[t]=-1,e&=~n}}function Zg(r){if(Oe&6)throw Error(ee(327));eo();var e=Hl(r,0);if(!(e&1))return $r(r,Ut()),null;var t=au(r,e);if(r.tag!==0&&t===2){var n=Ud(r);n!==0&&(e=n,t=nh(r,n))}if(t===1)throw t=Aa,ss(r,0),bi(r,e),$r(r,Ut()),t;if(t===6)throw Error(ee(345));return r.finishedWork=r.current.alternate,r.finishedLanes=e,Ki(r,Br,Kn),$r(r,Ut()),null}function Af(r,e){var t=Oe;Oe|=1;try{return r(e)}finally{Oe=t,Oe===0&&(lo=Ut()+500,xu&&_i())}}function hs(r){xi!==null&&xi.tag===0&&!(Oe&6)&&eo();var e=Oe;Oe|=1;var t=fn.transition,n=Xe;try{if(fn.transition=null,Xe=1,r)return r()}finally{Xe=n,fn.transition=t,Oe=e,!(Oe&6)&&_i()}}function Rf(){Xr=Ys.current,ut(Ys)}function ss(r,e){r.finishedWork=null,r.finishedLanes=0;var t=r.timeoutHandle;if(t!==-1&&(r.timeoutHandle=-1,Y2(t)),zt!==null)for(t=zt.return;t!==null;){var n=t;switch(df(n),n.tag){case 1:n=n.type.childContextTypes,n!=null&&Xl();break;case 3:oo(),ut(Lr),ut(vr),bf();break;case 5:wf(n);break;case 4:oo();break;case 13:ut(wt);break;case 19:ut(wt);break;case 10:gf(n.type._context);break;case 22:case 23:Rf()}t=t.return}if(tr=r,zt=r=Ai(r.current,null),lr=Xr=e,Vt=0,Aa=null,Tf=Eu=ds=0,Br=la=null,ns!==null){for(e=0;e<ns.length;e++)if(t=ns[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}ns=null}return r}function Sv(r,e){do{var t=zt;try{if(pf(),Ml.current=nu,ru){for(var n=bt.memoizedState;n!==null;){var i=n.queue;i!==null&&(i.pending=null),n=n.next}ru=!1}if(cs=0,er=Nt=bt=null,oa=!1,Ma=0,Mf.current=null,t===null||t.return===null){Vt=1,Aa=e,zt=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=Bg(o);if(f!==null){f.flags&=-257,Fg(f,o,a,s,e),f.mode&1&&Og(s,u,e),e=f,l=u;var p=e.updateQueue;if(p===null){var g=new Set;g.add(l),e.updateQueue=g}else p.add(l);break e}else{if(!(e&1)){Og(s,u,e),Pf();break e}l=Error(ee(426))}}else if(gt&&a.mode&1){var C=Bg(o);if(C!==null){!(C.flags&65536)&&(C.flags|=256),Fg(C,o,a,s,e),hf(ao(l,a));break e}}s=l=ao(l,a),Vt!==4&&(Vt=2),la===null?la=[s]:la.push(s),s=o;do{switch(s.tag){case 3:s.flags|=65536,e&=-e,s.lanes|=e;var y=av(s,l,e);Ug(s,y);break e;case 1:a=l;var m=s.type,v=s.stateNode;if(!(s.flags&128)&&(typeof m.getDerivedStateFromError=="function"||v!==null&&typeof v.componentDidCatch=="function"&&(Ti===null||!Ti.has(v)))){s.flags|=65536,e&=-e,s.lanes|=e;var b=lv(s,a,e);Ug(s,b);break e}}s=s.return}while(s!==null)}Mv(t)}catch(S){e=S,zt===t&&t!==null&&(zt=t=t.return);continue}break}while(!0)}function kv(){var r=iu.current;return iu.current=nu,r===null?nu:r}function Pf(){(Vt===0||Vt===3||Vt===2)&&(Vt=4),tr===null||!(ds&268435455)&&!(Eu&268435455)||bi(tr,lr)}function au(r,e){var t=Oe;Oe|=2;var n=kv();(tr!==r||lr!==e)&&(Kn=null,ss(r,e));do try{yI();break}catch(i){Sv(r,i)}while(!0);if(pf(),Oe=t,iu.current=n,zt!==null)throw Error(ee(261));return tr=null,lr=0,Vt}function yI(){for(;zt!==null;)Ev(zt)}function vI(){for(;zt!==null&&!Hx();)Ev(zt)}function Ev(r){var e=Uv(r.alternate,r,Xr);r.memoizedProps=r.pendingProps,e===null?Mv(r):zt=e,Mf.current=null}function Mv(r){var e=r;do{var t=e.alternate;if(r=e.return,e.flags&32768){if(t=dI(t,e),t!==null){t.flags&=32767,zt=t;return}if(r!==null)r.flags|=32768,r.subtreeFlags=0,r.deletions=null;else{Vt=6,zt=null;return}}else if(t=cI(t,e,Xr),t!==null){zt=t;return}if(e=e.sibling,e!==null){zt=e;return}zt=e=r}while(e!==null);Vt===0&&(Vt=5)}function Ki(r,e,t){var n=Xe,i=fn.transition;try{fn.transition=null,Xe=1,wI(r,e,t,n)}finally{fn.transition=i,Xe=n}return null}function wI(r,e,t,n){do eo();while(xi!==null);if(Oe&6)throw Error(ee(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(ee(177));r.callbackNode=null,r.callbackPriority=0;var s=t.lanes|t.childLanes;if(Jx(r,s),r===tr&&(zt=tr=null,lr=0),!(t.subtreeFlags&2064)&&!(t.flags&2064)||ul||(ul=!0,Av(Wl,function(){return eo(),null})),s=(t.flags&15990)!==0,t.subtreeFlags&15990||s){s=fn.transition,fn.transition=null;var o=Xe;Xe=1;var a=Oe;Oe|=4,Mf.current=null,fI(r,t),Cv(t,r),_2(Od),Vl=!!Dd,Od=Dd=null,r.current=t,pI(t),Vx(),Oe=a,Xe=o,fn.transition=s}else r.current=t;if(ul&&(ul=!1,xi=r,ou=i),s=r.pendingLanes,s===0&&(Ti=null),Gx(t.stateNode),$r(r,Ut()),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(su)throw su=!1,r=th,th=null,r;return ou&1&&r.tag!==0&&eo(),s=r.pendingLanes,s&1?r===rh?ua++:(ua=0,rh=r):ua=0,_i(),null}function eo(){if(xi!==null){var r=a0(ou),e=fn.transition,t=Xe;try{if(fn.transition=null,Xe=16>r?16:r,xi===null)var n=!1;else{if(r=xi,xi=null,ou=0,Oe&6)throw Error(ee(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:aa(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(vv(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 g=p.child;if(g!==null){p.child=null;do{var C=g.sibling;g.sibling=null,g=C}while(g!==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:aa(9,s,s.return)}var y=s.sibling;if(y!==null){y.return=s.return,fe=y;break e}fe=s.return}}var m=r.current;for(fe=m;fe!==null;){o=fe;var v=o.child;if(o.subtreeFlags&2064&&v!==null)v.return=o,fe=v;else e:for(o=m;fe!==null;){if(a=fe,a.flags&2048)try{switch(a.tag){case 0:case 11:case 15:ku(9,a)}}catch(S){Et(a,a.return,S)}if(a===o){fe=null;break e}var b=a.sibling;if(b!==null){b.return=a.return,fe=b;break e}fe=a.return}}if(Oe=i,_i(),Hn&&typeof Hn.onPostCommitFiberRoot=="function")try{Hn.onPostCommitFiberRoot(yu,r)}catch{}n=!0}return n}finally{Xe=t,fn.transition=e}}return!1}function Kg(r,e,t){e=ao(t,e),e=av(r,e,1),r=Mi(r,e,1),e=Tr(),r!==null&&(za(r,1,e),$r(r,e))}function Et(r,e,t){if(r.tag===3)Kg(r,r,t);else for(;e!==null;){if(e.tag===3){Kg(e,r,t);break}else if(e.tag===1){var n=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(Ti===null||!Ti.has(n))){r=ao(t,r),r=lv(e,r,1),e=Mi(e,r,1),r=Tr(),e!==null&&(za(e,1,r),$r(e,r));break}}e=e.return}}function bI(r,e,t){var n=r.pingCache;n!==null&&n.delete(e),e=Tr(),r.pingedLanes|=r.suspendedLanes&t,tr===r&&(lr&t)===t&&(Vt===4||Vt===3&&(lr&130023424)===lr&&500>Ut()-Uf?ss(r,0):Tf|=t),$r(r,e)}function Tv(r,e){e===0&&(r.mode&1?(e=Ja,Ja<<=1,!(Ja&130023424)&&(Ja=4194304)):e=1);var t=Tr();r=si(r,e),r!==null&&(za(r,e,t),$r(r,t))}function CI(r){var e=r.memoizedState,t=0;e!==null&&(t=e.retryLane),Tv(r,t)}function xI(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(ee(314))}n!==null&&n.delete(e),Tv(r,t)}var Uv;Uv=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,uI(r,e,t);Fr=!!(r.flags&131072)}else Fr=!1,gt&&e.flags&1048576&&z0(e,ql,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;Ul(r,e),r=e.pendingProps;var i=no(e,vr.current);Js(e,t),i=xf(null,e,n,r,i,t);var s=If();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,Zl(e)):s=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,yf(e),i.updater=Su,e.stateNode=i,i._reactInternals=e,Vd(e,n,r,t),e=Gd(null,e,n,!0,s,t)):(e.tag=0,gt&&s&&cf(e),kr(null,e,i,t),e=e.child),e;case 16:n=e.elementType;e:{switch(Ul(r,e),r=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=SI(n),r=xn(n,r),i){case 0:e=Yd(null,e,n,r,t);break e;case 1:e=$g(null,e,n,r,t);break e;case 11:e=Lg(null,e,n,r,t);break e;case 14:e=_g(null,e,n,xn(n.type,r),t);break e}throw Error(ee(306,n,""))}return e;case 0:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:xn(n,i),Yd(r,e,n,i,t);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:xn(n,i),$g(r,e,n,i,t);case 3:e:{if(hv(e),r===null)throw Error(ee(387));n=e.pendingProps,s=e.memoizedState,i=s.element,_0(r,e),eu(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=ao(Error(ee(423)),e),e=Ng(r,e,n,t,i);break e}else if(n!==i){i=ao(Error(ee(424)),e),e=Ng(r,e,n,t,i);break e}else for(Kr=Ei(e.stateNode.containerInfo.firstChild),qr=e,gt=!0,En=null,t=F0(e,null,n,t),e.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(io(),n===i){e=oi(r,e,t);break e}kr(r,e,n,t)}e=e.child}return e;case 5:return $0(e),r===null&&Nd(e),n=e.type,i=e.pendingProps,s=r!==null?r.memoizedProps:null,o=i.children,Bd(n,i)?o=null:s!==null&&Bd(n,s)&&(e.flags|=32),dv(r,e),kr(r,e,o,t),e.child;case 6:return r===null&&Nd(e),null;case 13:return fv(r,e,t);case 4:return vf(e,e.stateNode.containerInfo),n=e.pendingProps,r===null?e.child=so(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:xn(n,i),Lg(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(Ql,n._currentValue),n._currentValue=o,s!==null)if(An(s.value,o)){if(s.children===i.children&&!Lr.current){e=oi(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=ei(-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),Wd(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(ee(341));o.lanes|=t,a=o.alternate,a!==null&&(a.lanes|=t),Wd(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,Js(e,t),i=pn(i),n=n(i),e.flags|=1,kr(r,e,n,t),e.child;case 14:return n=e.type,i=xn(n,e.pendingProps),i=xn(n.type,i),_g(r,e,n,i,t);case 15:return uv(r,e,e.type,e.pendingProps,t);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:xn(n,i),Ul(r,e),e.tag=1,_r(n)?(r=!0,Zl(e)):r=!1,Js(e,t),ov(e,n,i),Vd(e,n,i,t),Gd(null,e,n,!0,r,t);case 19:return pv(r,e,t);case 22:return cv(r,e,t)}throw Error(ee(156,e.tag))};function Av(r,e){return n0(r,e)}function II(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 hn(r,e,t,n){return new II(r,e,t,n)}function zf(r){return r=r.prototype,!(!r||!r.isReactComponent)}function SI(r){if(typeof r=="function")return zf(r)?1:0;if(r!=null){if(r=r.$$typeof,r===qh)return 11;if(r===Qh)return 14}return 2}function Ai(r,e){var t=r.alternate;return t===null?(t=hn(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 Pl(r,e,t,n,i,s){var o=2;if(n=r,typeof r=="function")zf(r)&&(o=1);else if(typeof r=="string")o=5;else e:switch(r){case Bs:return os(t.children,i,s,e);case Kh:o=8,i|=8;break;case pd:return r=hn(12,t,e,i|2),r.elementType=pd,r.lanes=s,r;case gd:return r=hn(13,t,e,i),r.elementType=gd,r.lanes=s,r;case md:return r=hn(19,t,e,i),r.elementType=md,r.lanes=s,r;case $y:return Mu(t,i,s,e);default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case Ly:o=10;break e;case _y:o=9;break e;case qh:o=11;break e;case Qh:o=14;break e;case mi:o=16,n=null;break e}throw Error(ee(130,r==null?r:typeof r,""))}return e=hn(o,t,e,i),e.elementType=r,e.type=n,e.lanes=s,e}function os(r,e,t,n){return r=hn(7,r,n,e),r.lanes=t,r}function Mu(r,e,t,n){return r=hn(22,r,n,e),r.elementType=$y,r.lanes=t,r.stateNode={isHidden:!1},r}function Oc(r,e,t){return r=hn(6,r,null,e),r.lanes=t,r}function Bc(r,e,t){return e=hn(4,r.children!==null?r.children:[],r.key,e),e.lanes=t,e.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},e}function kI(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=mc(0),this.expirationTimes=mc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=mc(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Df(r,e,t,n,i,s,o,a,l){return r=new kI(r,e,t,a,l),e===1?(e=1,s===!0&&(e|=8)):e=0,s=hn(3,null,null,e),r.current=s,s.stateNode=r,s.memoizedState={element:n,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},yf(s),r}function EI(r,e,t){var n=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:Os,key:n==null?null:""+n,children:r,containerInfo:e,implementation:t}}function Rv(r){if(!r)return Oi;r=r._reactInternals;e:{if(gs(r)!==r||r.tag!==1)throw Error(ee(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(ee(171))}if(r.tag===1){var t=r.type;if(_r(t))return R0(r,t,e)}return e}function Pv(r,e,t,n,i,s,o,a,l){return r=Df(t,n,!0,r,i,s,o,a,l),r.context=Rv(null),t=r.current,n=Tr(),i=Ui(t),s=ei(n,i),s.callback=e??null,Mi(t,s,i),r.current.lanes=i,za(r,i,n),$r(r,n),r}function Tu(r,e,t,n){var i=e.current,s=Tr(),o=Ui(i);return t=Rv(t),e.context===null?e.context=t:e.pendingContext=t,e=ei(s,o),e.payload={element:r},n=n===void 0?null:n,n!==null&&(e.callback=n),r=Mi(i,e,o),r!==null&&(Un(r,i,o,s),El(r,i,o)),o}function lu(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 qg(r,e){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var t=r.retryLane;r.retryLane=t!==0&&t<e?t:e}}function Of(r,e){qg(r,e),(r=r.alternate)&&qg(r,e)}function MI(){return null}var zv=typeof reportError=="function"?reportError:function(r){console.error(r)};function Bf(r){this._internalRoot=r}Uu.prototype.render=Bf.prototype.render=function(r){var e=this._internalRoot;if(e===null)throw Error(ee(409));Tu(r,e,null,null)};Uu.prototype.unmount=Bf.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var e=r.containerInfo;hs(function(){Tu(null,r,null,null)}),e[ii]=null}};function Uu(r){this._internalRoot=r}Uu.prototype.unstable_scheduleHydration=function(r){if(r){var e=c0();r={blockedOn:null,target:r,priority:e};for(var t=0;t<wi.length&&e!==0&&e<wi[t].priority;t++);wi.splice(t,0,r),t===0&&h0(r)}};function Ff(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function Au(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11&&(r.nodeType!==8||r.nodeValue!==" react-mount-point-unstable "))}function Qg(){}function TI(r,e,t,n,i){if(i){if(typeof n=="function"){var s=n;n=function(){var u=lu(o);s.call(u)}}var o=Pv(e,n,r,0,null,!1,!1,"",Qg);return r._reactRootContainer=o,r[ii]=o.current,xa(r.nodeType===8?r.parentNode:r),hs(),o}for(;i=r.lastChild;)r.removeChild(i);if(typeof n=="function"){var a=n;n=function(){var u=lu(l);a.call(u)}}var l=Df(r,0,!1,null,null,!1,!1,"",Qg);return r._reactRootContainer=l,r[ii]=l.current,xa(r.nodeType===8?r.parentNode:r),hs(function(){Tu(e,l,t,n)}),l}function Ru(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=lu(o);a.call(l)}}Tu(e,o,r,i)}else o=TI(t,e,r,i,n);return lu(o)}l0=function(r){switch(r.tag){case 3:var e=r.stateNode;if(e.current.memoizedState.isDehydrated){var t=Yo(e.pendingLanes);t!==0&&(tf(e,t|1),$r(e,Ut()),!(Oe&6)&&(lo=Ut()+500,_i()))}break;case 13:hs(function(){var n=si(r,1);if(n!==null){var i=Tr();Un(n,r,1,i)}}),Of(r,1)}};rf=function(r){if(r.tag===13){var e=si(r,134217728);if(e!==null){var t=Tr();Un(e,r,134217728,t)}Of(r,134217728)}};u0=function(r){if(r.tag===13){var e=Ui(r),t=si(r,e);if(t!==null){var n=Tr();Un(t,r,e,n)}Of(r,e)}};c0=function(){return Xe};d0=function(r,e){var t=Xe;try{return Xe=r,e()}finally{Xe=t}};Ed=function(r,e,t){switch(e){case"input":if(wd(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=Cu(n);if(!i)throw Error(ee(90));Wy(n),wd(n,i)}}}break;case"textarea":Vy(r,t);break;case"select":e=t.value,e!=null&&Zs(r,!!t.multiple,e,!1)}};qy=Af;Qy=hs;var UI={usingClientEntryPoint:!1,Events:[Oa,$s,Cu,Zy,Ky,Af]},Lo={findFiberByHostInstance:rs,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},AI={bundleType:Lo.bundleType,version:Lo.version,rendererPackageName:Lo.rendererPackageName,rendererConfig:Lo.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ai.ReactCurrentDispatcher,findHostInstanceByFiber:function(r){return r=t0(r),r===null?null:r.stateNode},findFiberByHostInstance:Lo.findFiberByHostInstance||MI,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 cl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!cl.isDisabled&&cl.supportsFiber)try{yu=cl.inject(AI),Hn=cl}catch{}}en.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=UI;en.createPortal=function(r,e){var t=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Ff(e))throw Error(ee(200));return EI(r,e,null,t)};en.createRoot=function(r,e){if(!Ff(r))throw Error(ee(299));var t=!1,n="",i=zv;return e!=null&&(e.unstable_strictMode===!0&&(t=!0),e.identifierPrefix!==void 0&&(n=e.identifierPrefix),e.onRecoverableError!==void 0&&(i=e.onRecoverableError)),e=Df(r,1,!1,null,null,t,!1,n,i),r[ii]=e.current,xa(r.nodeType===8?r.parentNode:r),new Bf(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(ee(188)):(r=Object.keys(r).join(","),Error(ee(268,r)));return r=t0(e),r=r===null?null:r.stateNode,r};en.flushSync=function(r){return hs(r)};en.hydrate=function(r,e,t){if(!Au(e))throw Error(ee(200));return Ru(null,r,e,!0,t)};en.hydrateRoot=function(r,e,t){if(!Ff(r))throw Error(ee(405));var n=t!=null&&t.hydratedSources||null,i=!1,s="",o=zv;if(t!=null&&(t.unstable_strictMode===!0&&(i=!0),t.identifierPrefix!==void 0&&(s=t.identifierPrefix),t.onRecoverableError!==void 0&&(o=t.onRecoverableError)),e=Pv(e,null,r,1,t??null,i,!1,s,o),r[ii]=e.current,xa(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 Uu(e)};en.render=function(r,e,t){if(!Au(e))throw Error(ee(200));return Ru(null,r,e,!1,t)};en.unmountComponentAtNode=function(r){if(!Au(r))throw Error(ee(40));return r._reactRootContainer?(hs(function(){Ru(null,null,r,!1,function(){r._reactRootContainer=null,r[ii]=null})}),!0):!1};en.unstable_batchedUpdates=Af;en.unstable_renderSubtreeIntoContainer=function(r,e,t,n){if(!Au(t))throw Error(ee(200));if(r==null||r._reactInternals===void 0)throw Error(ee(38));return Ru(r,e,t,!1,n)};en.version="18.3.1-next-f1338f8080-20240426";function Dv(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Dv)}catch(r){console.error(r)}}Dv(),Dy.exports=en;var RI=Dy.exports,Jg=RI;hd.createRoot=Jg.createRoot,hd.hydrateRoot=Jg.hydrateRoot;var Ov=Object.defineProperty,PI=(r,e,t)=>e in r?Ov(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ye=(r,e)=>Ov(r,"name",{value:e,configurable:!0}),ca=(r,e,t)=>(PI(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||{}),Ri=(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))(Ri||{});function zI(r){let e=Ri[r];return e!==void 0?e:null}Ye(zI,"keyCodeToKeyboardInput");function DI(r){return Ri[r]}Ye(DI,"keyboardInputToKeyCode");var _t=(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))(_t||{});function OI(r){return r<100}Ye(OI,"isMouseButton");function BI(r){return r>=100}Ye(BI,"isMouseAxis");var Lf=(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))(Lf||{});function FI(r){return r<100}Ye(FI,"isGamepadButton");function LI(r){return r>=100}Ye(LI,"isGamepadAxis");function _I(r){return r>=0&&r<=19?r:null}Ye(_I,"gamepadButtonIndexToInput");function $I(r){return{0:100,1:101,2:102,3:103}[r]??null}Ye($I,"gamepadAxisIndexToInput");var _f=(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))(_f||{});function NI(r){return r<100}Ye(NI,"isTouchButton");function WI(r){return r>=100&&r<200}Ye(WI,"isTouchPosition");function HI(r){return r>=200}Ye(HI,"isTouchGesture");function VI(r){return r<0||r>9?null:100+r*2}Ye(VI,"getTouchXAxis");function jI(r){return r<0||r>9?null:101+r*2}Ye(jI,"getTouchYAxis");var $f=(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))($f||{});function YI(r){return r<100}Ye(YI,"isTouchZoneButton");function GI(r){return r>=100}Ye(GI,"isTouchZonePosition");function XI(r){return r<0||r>31?null:100+r*2}Ye(XI,"getTouchZoneXAxis");function ZI(r){return r<0||r>31?null:101+r*2}Ye(ZI,"getTouchZoneYAxis");var Nf=(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))(Nf||{});function KI(r){return r<100}Ye(KI,"isTVRemoteButton");function qI(r){return r>=100}Ye(qI,"isTVRemoteAxis");function QI(r,e){return{device:r,input:e}}Ye(QI,"createInputDescriptor");function da(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(da,"isButton");function Bv(r){return!da(r)}Ye(Bv,"isAxis");function JI(r){let e=new Uint8Array(3);return e[0]=r.device,e[1]=r.input&255,e[2]=r.input>>8&255,e}Ye(JI,"serializeInputDescriptor");function eS(r,e=0){let t=r[e],n=r[e+1]|r[e+2]<<8;return{device:t,input:n}}Ye(eS,"deserializeInputDescriptor");function tS(r){let e=ce[r.device],t;switch(r.device){case 0:t=Ri[r.input];break;case 1:t=_t[r.input];break;case 2:t=Lf[r.input];break;case 3:t=_f[r.input];break;case 7:t=$f[r.input];break;case 4:t=Nf[r.input];break;default:t="Unknown"}return`${e}:${t}`}Ye(tS,"inputDescriptorToString");function rS(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=Ri[t];break;case 1:i=_t[t];break;case 2:i=Lf[t];break;case 3:i=_f[t];break;case 4:i=Nf[t];break;case 7:i=$f[t];break}return i===void 0?null:{device:n,input:i}}Ye(rS,"parseInputDescriptor");var Fv=class Sr{constructor(e=0,t=0){ca(this,"x"),ca(this,"y"),this.x=e,this.y=t}static zero(){return new Sr(0,0)}static one(){return new Sr(1,1)}static up(){return new Sr(0,-1)}static down(){return new Sr(0,1)}static left(){return new Sr(-1,0)}static right(){return new Sr(1,0)}add(e){return new Sr(this.x+e.x,this.y+e.y)}subtract(e){return new Sr(this.x-e.x,this.y-e.y)}multiply(e){return new Sr(this.x*e,this.y*e)}divide(e){if(e===0)throw new Error("Division by zero");return new Sr(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?Sr.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 Sr(this.x*t-this.y*n,this.x*n+this.y*t)}lerp(e,t){return new Sr(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t)}clone(){return new Sr(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(Fv,"Vector2");var Ht=Fv,nS=class sr{constructor(e=0,t=0,n=0){ca(this,"x"),ca(this,"y"),ca(this,"z"),this.x=e,this.y=t,this.z=n}static zero(){return new sr(0,0,0)}static one(){return new sr(1,1,1)}static up(){return new sr(0,1,0)}static down(){return new sr(0,-1,0)}static left(){return new sr(-1,0,0)}static right(){return new sr(1,0,0)}static forward(){return new sr(0,0,1)}static back(){return new sr(0,0,-1)}add(e){return new sr(this.x+e.x,this.y+e.y,this.z+e.z)}subtract(e){return new sr(this.x-e.x,this.y-e.y,this.z-e.z)}multiply(e){return new sr(this.x*e,this.y*e,this.z*e)}divide(e){if(e===0)throw new Error("Division by zero");return new sr(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?sr.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 sr(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 sr(this.x+(e.x-this.x)*t,this.y+(e.y-this.y)*t,this.z+(e.z-this.z)*t)}clone(){return new sr(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(nS,"Vector3");var Ge={scanlines:{opacity:.15,pattern:"horizontal",color:{r:0,g:0,b:0}},ambientEffect:{blur:30,scale:1.3,opacity:.7}},Gs={color:"rgba(144, 24, 24, 1)",lineWidth:1},$t=(r=>(r.None="none",r.Eighth="eighth",r.Quarter="quarter",r.Half="half",r.Integer="integer",r.Responsive="responsive",r))($t||{}),iS=(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))(iS||{});function Lv(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(Lv,"scalingModeToValue");function Wf(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(Wf,"valueToScalingMode");var on=(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))(on||{}),Fa=Object.defineProperty,sS=Object.getOwnPropertyDescriptor,oS=Object.getOwnPropertyNames,aS=Object.prototype.hasOwnProperty,lS=(r,e,t)=>e in r?Fa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,K=(r,e)=>Fa(r,"name",{value:e,configurable:!0}),dl=(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')}),rr=(r,e)=>()=>(r&&(e=r(r=0)),e),La=(r,e)=>{for(var t in e)Fa(r,t,{get:e[t],enumerable:!0})},uS=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of oS(e))!aS.call(r,i)&&i!==t&&Fa(r,i,{get:()=>e[i],enumerable:!(n=sS(e,i))||n.enumerable});return r},Xo=r=>uS(Fa({},"__esModule",{value:!0}),r),F=(r,e,t)=>(lS(r,typeof e!="symbol"?e+"":e,t),t),Hf,_v,$v,Nv,Wv,Hv,Vv,jv,Yv,Gv,Xv,Zv,Kv,qv,Qv,Jv,e1,t1,r1,n1,i1,s1,o1,a1,l1,u1,c1,d1,h1,f1,p1,g1,m1,sh,oh,y1,ah,lh,uh,ch,dh,hh,vo=rr(()=>{Hf=K(r=>r?2:1,"charCodeByteSize"),_v=6,$v=6,Nv=6,Wv=7,Hv=5,Vv=3,jv=1,Yv=6,Gv=4,Xv=5,Zv=2,Kv=8,qv=7,Qv=7,Jv=8,e1=10,t1=6,r1=3,n1=9,i1=15,s1=51,o1=5,a1=6,l1=4,u1=3,c1=3,d1=4,h1=5,f1=4,p1=2,g1=5,m1=5,sh=5,oh=5,y1=3,ah=8,lh=6,uh=3,ch=8,dh=3,hh=4}),em,cS=rr(()=>{em=(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))(em||{})});function dS(r){return r>=1&&r<=3}function hS(r){return r>=1&&r<=4}function fS(r){switch(r){case 1:return"CreateInstance";case 2:return"UpdateInstance";case 3:return"RemoveInstance";default:return`Unknown(0x${r.toString(16)})`}}function pS(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)})`}}var tm,rm,gS=rr(()=>{tm=(r=>(r[r.CreateInstance=1]="CreateInstance",r[r.UpdateInstance=2]="UpdateInstance",r[r.RemoveInstance=3]="RemoveInstance",r))(tm||{}),rm=(r=>(r[r.Click=1]="Click",r[r.Change=2]="Change",r[r.Submit=3]="Submit",r[r.Select=4]="Select",r))(rm||{}),K(dS,"isValidMacroOrderType"),K(hS,"isValidMacroEventType"),K(fS,"getMacroOrderTypeName"),K(pS,"getMacroEventTypeName")}),Fc,ne,Wr=rr(()=>{Fc=class qi{constructor(e){F(this,"data"),F(this,"view"),this.data=new Uint8Array(e),this.view=new DataView(this.data.buffer)}static from(e){let t=new qi(0);return t.data=e,t.view=new DataView(e.buffer,e.byteOffset,e.byteLength),t}static allocUnsafe(e){return new qi(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 qi.from(n)}subarray(e,t){let n=this.data.subarray(e,t);return qi.from(n)}toBuffer(){return typeof Buffer<"u"&&Buffer.from?Buffer.from(this.data):this.data}static fromNodeBuffer(e){return e instanceof Uint8Array?qi.from(e):qi.from(new Uint8Array(e))}},K(Fc,"BufferCompat"),ne=Fc}),v1={};La(v1,{VibrationOrderType:()=>fh});var fh,w1=rr(()=>{fh=(r=>(r[r.MobileVibrate=1]="MobileVibrate",r[r.MobileCancel=2]="MobileCancel",r[r.GamepadVibrate=16]="GamepadVibrate",r[r.GamepadCancel=17]="GamepadCancel",r))(fh||{})}),b1={};La(b1,{GamepadVibrateFlags:()=>gh,MobileVibrateFlags:()=>ph});var ph,gh,C1=rr(()=>{ph=(r=>(r[r.HasIntensity=1]="HasIntensity",r))(ph||{}),gh=(r=>(r[r.HasStartDelay=1]="HasStartDelay",r[r.AllGamepads=2]="AllGamepads",r))(gh||{})}),x1={};La(x1,{AudioOrderType:()=>mh,AudioTargetType:()=>yh,getAudioOrderTypeName:()=>S1,isValidAudioOrderType:()=>I1});function I1(r){return r>=1&&r<=9}function S1(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 mh,yh,k1=rr(()=>{mh=(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))(mh||{}),yh=(r=>(r[r.InstanceId=0]="InstanceId",r[r.SoundId=1]="SoundId",r[r.All=2]="All",r))(yh||{}),K(I1,"isValidAudioOrderType"),K(S1,"getAudioOrderTypeName")}),E1={};La(E1,{PlaySoundFlags:()=>vh,SoundEffectsFlags:()=>wh});var vh,wh,M1=rr(()=>{vh=(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))(vh||{}),wh=(r=>(r[r.HasLowpass=1]="HasLowpass",r[r.HasHighpass=2]="HasHighpass",r[r.HasReverb=4]="HasReverb",r))(wh||{})}),mS=rr(()=>{}),Or,yS=rr(()=>{Or=(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))(Or||{})}),nm,Lc,_c,$c,T1,vS=rr(()=>{nm=4,Lc=4,_c=8,$c=class{decode(e,t=0){this.checkSize(e,t,_c);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>Lc)throw new Error(`Invalid renderPass count: ${u} (max ${Lc})`);let c=u*nm;this.checkSize(e,n,c);let d=[];for(let h=0;h<u;h++){let f=e.readUInt8(n++),p=e.readUInt8(n++),g=e.readUInt8(n++),C=e.readUInt8(n++);d.push({id:f,zMin:p,zMax:g,enabled:(C&1)!==0})}return{display:{id:i,originX:s,originY:o,sizeX:a,sizeY:l,renderPasses:d.length>0?d:void 0},bytesRead:_c+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`)}},K($c,"DisplayDecoder"),T1=$c}),Nc,U1,wS=rr(()=>{vo(),Nc=class{constructor(){F(this,"charCodeSize",Hf)}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.decodeClearOrder(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 g=e.readUInt8(s++),C=e.readUInt8(s++);return{shapeData:{posX:l,posY:u,width:c,height:d,filled:h,charCode:f,bgColorCode:g,fgColorCode:C},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++),g=e.readUInt8(s++);return{shapeData:{centerX:l,centerY:u,radius:c,filled:d,charCode:h,bgColorCode:p,fgColorCode:g},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++),g=e.readUInt8(s++);return{shapeData:{x1:l,y1:u,x2:c,y2:d,charCode:h,bgColorCode:p,fgColorCode:g},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 g=e.readUInt8(s++),C=e.readUInt8(s++);return{shapeData:{centerX:l,centerY:u,radiusX:c,radiusY:d,filled:h,charCode:f,bgColorCode:g,fgColorCode:C},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,[g,C]=this.readCharCode(e,s,i);s=C;let y=e.readUInt8(s++),m=e.readUInt8(s++);return{shapeData:{x1:l,y1:u,x2:c,y2:d,x3:h,y3:f,filled:p,charCode:g,bgColorCode:y,fgColorCode:m},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,g=Math.ceil(l*u/8);this.checkSize(e,t,i+g);let C=new Uint8Array(g);for(let y=0;y<g;y++)C[y]=e.readUInt8(s+y);return{order:{type:17,posX:o,posY:a,sizeX:l,sizeY:u,charCode:c,bgColorCode:h,fgColorCode:f,override:p,mask:C},bytesRead:i+g}}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[g,C]=this.readCharCode(e,s,n);s=C,h.push({charCode:g,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[g,C]=this.readCharCode(e,s,n);s=C,h.push({charCode:g,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}}decodeClearOrder(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`)}},K(Nc,"OrderDecoder"),U1=Nc}),im,Wc,A1,bS=rr(()=>{wS(),im=64,Wc=class{constructor(){F(this,"orderDecoder"),this.orderDecoder=new U1}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&im)!==0,f=[],p=n;for(let g=0;g<d;g++){let C=this.orderDecoder.decode(e,p,h);f.push(C.order),p+=C.bytesRead}return{layer:{id:i,updateFlags:s,zIndex:o,originX:a,originY:l,width:u,height:c,orderCount:d,orders:f,is16bit:h},bytesRead:p-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`)}},K(Wc,"LayerDecoder"),A1=Wc}),Hc,R1,P1=rr(()=>{Hc=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`)}},K(Hc,"AudioOrderDecoder"),R1=Hc}),Vc,z1,D1=rr(()=>{Vc=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}}},K(Vc,"VibrationOrderDecoder"),z1=Vc}),jc,O1,CS=rr(()=>{jc=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}}},K(jc,"MacroOrderDecoder"),O1=jc}),Yc,B1,F1=rr(()=>{Yc=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}}},K(Yc,"PostProcessOrderDecoder"),B1=Yc}),L1={};La(L1,{UpdatePacketDecoder:()=>_1});var Gc,_1,$1=rr(()=>{vS(),bS(),P1(),D1(),CS(),F1(),Wr(),Gc=class{constructor(){F(this,"displayDecoder"),F(this,"layerDecoder"),F(this,"audioOrderDecoder"),F(this,"vibrationOrderDecoder"),F(this,"macroOrderDecoder"),F(this,"postProcessOrderDecoder"),this.displayDecoder=new T1,this.layerDecoder=new A1,this.audioOrderDecoder=new R1,this.vibrationOrderDecoder=new z1,this.macroOrderDecoder=new O1,this.postProcessOrderDecoder=new B1}decode(e,t=0){let n=ne.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 U=0;U<o;U++){let z=this.displayDecoder.decode(n,i);a.push(z.display),i+=z.bytesRead,l+=z.bytesRead}this.checkSize(n,i,2);let u=n.readUInt16BE(i);i+=2;let c=[],d=0;for(let U=0;U<u;U++){let z=this.layerDecoder.decode(n,i);c.push({...z.layer,byteSize:z.bytesRead}),i+=z.bytesRead,d+=z.bytesRead}this.checkSize(n,i,1);let h=n.readUInt8(i);i+=1;let f=[],p=0;for(let U=0;U<h;U++){let z=this.audioOrderDecoder.decode(n,i);f.push(z.order),i+=z.bytesRead,p+=z.bytesRead}this.checkSize(n,i,1);let g=n.readUInt8(i);i+=1;let C=[],y=0;for(let U=0;U<g;U++){let z=this.vibrationOrderDecoder.decode(n,i);C.push(z.order),i+=z.bytesRead,y+=z.bytesRead}this.checkSize(n,i,1);let m=n.readUInt8(i);i+=1;let v=[],b=0;for(let U=0;U<m;U++){let z=this.macroOrderDecoder.decode(n,i);v.push(z.order),i+=z.bytesRead,b+=z.bytesRead}this.checkSize(n,i,1);let S=n.readUInt8(i);i+=1;let I=[],E=0;for(let U=0;U<S;U++){let z=this.postProcessOrderDecoder.decode(n.toUint8Array(),i);I.push(z.order),i+=z.bytesRead,E+=z.bytesRead}return{tick:s,displayCount:o,displays:a,layerCount:u,layers:c,audioOrderCount:h,audioOrders:f,vibrationOrderCount:g,vibrationOrders:C,macroOrderCount:m,macroOrders:v,postProcessOrderCount:S,postProcessOrders:I,__byteSizes:{displays:l,layers:d,audioOrders:p,vibrationOrders:y,macroOrders:b,postProcessOrders:E}}}isValid(e,t=0){let n=ne.from(e);try{return this.checkSize(n,t,15),!0}catch{return!1}}decodeHeader(e,t=0){let n=ne.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`)}},K(Gc,"UpdatePacketDecoder"),_1=Gc}),N1=class{constructor(e=0,t=60,n=40){if(F(this,"id"),F(this,"origin"),F(this,"size"),F(this,"previousOrigin",new Ht(0,0)),F(this,"previousSize",new Ht(0,0)),F(this,"toDraw",[]),F(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 Ht(0,0),this.size=new Ht(t,n),this.toDraw=new Array(this.size.x*this.size.y).fill(null).map(()=>({charCode:0,fgColorCode:0,bgColorCode:0}))}getId(){return this.id}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,this.toDraw=new Array(this.size.x*this.size.y).fill(null).map(()=>({charCode:0,fgColorCode:0,bgColorCode:0}))}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}}};K(N1,"Display");var xS=N1,W1=class{constructor(e=65536,t=!1){F(this,"charCodes"),F(this,"fgColors"),F(this,"bgColors"),F(this,"size"),F(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}};K(W1,"CellBuffer");var H1=W1,V1=class{constructor(e){F(this,"data"),F(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}};K(V1,"CharCodeBuffer");var IS=V1,SS=new Map([[9474,179],[9472,196],[9484,218],[9488,191],[9492,192],[9496,217],[9500,195],[9508,180],[9516,194],[9524,193],[9532,197],[9553,186],[9552,205],[9556,201],[9559,187],[9562,200],[9565,188],[9568,204],[9571,185],[9574,203],[9577,202],[9580,206],[9608,219],[9619,178],[9618,177],[9617,176],[9600,223],[9604,220],[9612,221],[9616,222]]);function uu(r){if(r<128)return r;let e=SS.get(r);return e!==void 0?e:r&255}K(uu,"unicodeToCp437");var j1=class{constructor(){F(this,"currentWidth",256),F(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.rasterizeClear(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),h=uu(d);t.set(c,h,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),g=uu(p);t.set(f,g,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 g=d*this.currentWidth+f;t.set(g,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 g=h*this.currentWidth+p;t.set(g,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,g=n,C=i;for(;this.setCell(g,C,a,l,u,t),!(g===s&&C===o);){let y=2*p;y>-d&&(p-=d,g+=h),y<c&&(p+=c,C+=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,g=t;for(;this.setCell(p,g,s,o,a,l),!(p===n&&g===i);){let C=2*f;C>-c&&(f-=c,p+=d),C<u&&(f+=u,g+=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 g=h*this.currentWidth+p;t.set(g,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)),g=Math.round(i+o*Math.sin(f));this.setCell(p,g,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((v,b)=>v.y-b.y),[p,g,C]=f,y=K((v,b,S)=>{let I=Math.round(Math.min(b,S)),E=Math.round(Math.max(b,S));for(let U=I;U<=E;U++)if(U>=0&&U<this.currentWidth&&v>=0&&v<this.currentHeight){let z=v*this.currentWidth+U;t.set(z,c,h,d)}},"drawLine"),m=K((v,b,S,I,E)=>I===b?S:S+(v-b)*(E-S)/(I-b),"interpolate");for(let v=p.y;v<=g.y;v++){let b=m(v,p.y,p.x,C.y,C.x),S=m(v,p.y,p.x,g.y,g.x);y(v,b,S)}for(let v=g.y+1;v<=C.y;v++){let b=m(v,p.y,p.x,C.y,C.x),S=m(v,g.y,g.x,C.y,C.x);y(v,b,S)}}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,g=t;for(;this.setCell(p,g,s,o,a,l),!(p===n&&g===i);){let C=2*f;C>-c&&(f-=c,p+=d),C<u&&(f+=u,g+=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 g=n+p;if(g<0||g>=this.currentWidth)continue;let C=h*s+p,y=Math.floor(C/8),m=C%8,v=(d[y]&1<<m)!==0,b=f*this.currentWidth+g;v?t.set(b,a,u,l):c&&t.set(b,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,g=Math.floor(p/4),C=p%4*2,y=u[g]>>C&3,m=d*this.currentWidth+f;if(y>0){let v=l[y-1];t.set(m,v.charCode,v.fgColorCode,v.bgColorCode)}else a&&t.set(m,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,g=Math.floor(p/2),C=p%2*4,y=u[g]>>C&15,m=d*this.currentWidth+f;if(y>0){let v=l[y-1];t.set(m,v.charCode,v.fgColorCode,v.bgColorCode)}else a&&t.set(m,255,255,255)}}}rasterizeClear(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 g=d*u.sizeX+h,C=c.get(g);this.setCell(f,p,C,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),g=l.getFgColorCode(f),C=l.getBgColorCode(f);this.setCell(d,h,p,C,g,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 g=d*l.sizeX+h,C=c.get(g);this.setCell(f,p,C,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),g=l.getFgColorCode(f),C=l.getBgColorCode(f);this.setCell(d,h,p,C,g,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),g=l.getFgColorCode(f),C=l.getBgColorCode(f);this.setCell(d,h,p,C,g,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}};K(j1,"LayerRasterizer");var kS=j1,Xc=255,bh=class Zo{constructor(e,t,n,i,s){if(F(this,"id",0),F(this,"name"),F(this,"origin"),F(this,"orders",[]),F(this,"zOrder",0),F(this,"data"),F(this,"width"),F(this,"height"),F(this,"isStatic",!1),F(this,"spriteRegistry"),F(this,"mode","server"),F(this,"charCodeMode"),F(this,"previousOrigin"),F(this,"previousZOrder"),F(this,"enabled",!0),F(this,"useSetMode",!1),F(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={isStatic:s}:s&&(o=s),this.origin=e,this.zOrder=t,this.name=o.name,this.width=n,this.height=i,this.isStatic=o.isStatic??!1,this.charCodeMode=o.charCodeMode??"8bit";let a=this.charCodeMode==="16bit";this.data=new H1(n*i,a),this.previousOrigin=new Ht(e.x,e.y),this.previousZOrder=t}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")&&Zo.rasterizer.rasterizeOrders(this.orders,this.data,this.width,this.height,this.spriteRegistry)}addTemporaryOrders(e){(this.mode==="client"||this.mode==="standalone")&&Zo.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")&&Zo.rasterizer.rasterizeOrders(e,this.data,this.width,this.height,this.spriteRegistry)}clearOrders(){this.orders=[],(this.mode==="client"||this.mode==="standalone")&&Zo.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,isStatic:this.isStatic,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}}setId(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)}setStatic(e){this.isStatic=e}getStatic(){return this.isStatic}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>Xc&&(console.error(`[UTSP] ⚠️ CRITICAL: Layer ${this.id} has ${this.orders.length} orders, but max is ${Xc}!
|
|
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,Yc)),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}};K(yh,"Layer"),F(yh,"rasterizer",new vI);var wI=yh,$1=class{constructor(){F(this,"macros",new Map),F(this,"macroNameToId",new Map),F(this,"nextMacroId",0),F(this,"instances",new Map),F(this,"instanceNameToId",new Map),F(this,"nextInstanceId",0),F(this,"layerNameToId",new Map),F(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()}};K($1,"MacroRegistry");var bI=$1;function Pi(r){return typeof r=="number"?r:r.charCodeAt(0)}K(Pi,"toCharCode");function cu(r){return typeof r=="string"?r.charAt(0):String.fromCharCode(r)}K(cu,"toCharString");var CI=(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.Clear=19]="Clear",r[r.FillChar=20]="FillChar",r[r.FillSprite=21]="FillSprite",r[r.FillSpriteMultiColor=22]="FillSpriteMultiColor",r))(CI||{});function xI(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}K(xI,"isValidOrderType");function SI(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"Clear";case 20:return"FillChar";case 21:return"FillSprite";case 22:return"FillSpriteMultiColor";default:return`Unknown(0x${r.toString(16)})`}}K(SI,"getOrderTypeName");var II={single:{topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",horizontal:"─",vertical:"│"},double:{topLeft:"╔",topRight:"╗",bottomLeft:"╚",bottomRight:"╝",horizontal:"═",vertical:"║"},rounded:{topLeft:"╭",topRight:"╮",bottomLeft:"╰",bottomRight:"╯",horizontal:"─",vertical:"│"}},tm={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=N1(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=Nf(r),i=e.states[n]??e.states.normal,s={...r.params,...i},o=[];if(e.subtype==="button"&&e.button)W1(r,e,s,o,t);else if(e.base)for(let a of e.base){let l=j1(a,r.x,r.y,s,t);l&&o.push(l)}return o}};function N1(r,e,t,n,i,s){return r>=t&&r<t+i&&e>=n&&e<n+s}K(N1,"isPointInRect");function Nf(r){return r.isDisabled?"disabled":r.isActive?"active":r.isHovered?"hover":r.isFocused?"focused":"normal"}K(Nf,"getUIState");function Ps(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}K(Ps,"toColorIndex");function W1(r,e,t,n,i){let s=e.button,o=Nf(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),g=a.offsetY??0,x=r.x,y=r.y+g;d==="none"?H1(x,y,l,u,c,h,f,p,n):V1(x,y,l,u,c,h,f,p,d,n)}K(W1,"renderButton");function H1(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})}K(H1,"renderButtonNoBorder");function V1(r,e,t,n,i,s,o,a,l,u){let c=II[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 g=1;g<n-1;g++)u.push({type:2,posX:r,posY:e+g,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})}K(V1,"renderButtonWithBorder");function j1(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:Ps(i.resolveValue(c,n)),bgColorCode:Ps(i.resolveValue(d,n)),frame:Array(i.resolveValue(a,n)*i.resolveValue(l,n)).fill(Pi(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:Ps(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:Pi(i.resolveValue(a,n)),fgColorCode:Ps(i.resolveValue(l,n)),bgColorCode:Ps(i.resolveValue(u,n))}}return null}K(j1,"executeRenderCommand");function Y1(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}}K(Y1,"createUIInstance");var G1=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 g=[];for(let x of e.particles){let y=Math.floor(x.x),m=Math.floor(x.y);if(y<d||y>=d+f||m<h||m>=h+p)continue;let v=x.fg;if(t.particle.fade&&x.maxLifetime>0){let b=x.lifetime/x.maxLifetime;v=this.fadeColorIndex(x.fg,b)}g.push({charCode:Pi(x.char),fgColorCode:v,bgColorCode:x.bg??255,posX:y,posY:m})}return[{type:12,dots:g}]}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,g=0;if("x"in a.velocity&&"y"in a.velocity)p=i(a.velocity.x,e.params),g=i(a.velocity.y,e.params);else if("angle"in a.velocity&&"speed"in a.velocity){let M=s(a.velocity.angle),U=s(a.velocity.speed,e.params),z=M*Math.PI/180;p=Math.cos(z)*U,g=Math.sin(z)*U}let x=s(a.lifetime),y=Array.isArray(a.char)?a.char[Math.floor(Math.random()*a.char.length)]:a.char,m=cu(y),v=Array.isArray(a.fg)?a.fg[Math.floor(Math.random()*a.fg.length)]:a.fg,b=typeof v=="number"?v:parseInt(v,10)||243,I=a.bg?Array.isArray(a.bg)?a.bg[Math.floor(Math.random()*a.bg.length)]:a.bg:void 0,S=I!==void 0?typeof I=="number"?I:parseInt(I,10)||255:void 0;return{x:h,y:f,vx:p,vy:g,char:m,fg:b,bg:S,lifetime:x,maxLifetime:x}}fadeColorIndex(e,t){return t<.1?255:e}};K(G1,"ParticleHandler");var kI=G1,X1=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}};K(X1,"EffectHandler");var EI=X1,Z1=class{constructor(){F(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:Pi(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,g=d.get(p);g.charCode!==0&&i.push({char:String.fromCharCode(g.charCode),fg:g.fgColorCode,bg:g.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 g=f*l+p,x=c.get(g);x!==0&&i.push({char:String.fromCharCode(x),fg:d,bg:h,x:p,y:f,revealOrder:0})}}break}case"cells":{for(let o of s.cells)i.push({char:cu(o.char),fg:o.fg,bg:o.bg,x:o.x,y:o.y,revealOrder:0});break}case"fill":{let o=cu(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}};K(Z1,"RevealHandler");var MI=Z1,K1=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:Pi(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:Pi(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:Pi(s),fgColorCode:f,bgColorCode:a,points:h.map(p=>({x:p.x&255,y:p.y&255}))})}return u}};K(K1,"LineHandler");var TI=K1;function Qi(...r){}K(Qi,"macroLog");var q1=class{constructor(){F(this,"templates",new Map),F(this,"instances",new Map),F(this,"spriteRegistry",null),F(this,"playSound",null),F(this,"focusedInstanceId",null),F(this,"focusableInstances",[]),F(this,"mouseX",0),F(this,"mouseY",0),F(this,"mouseDown",!1),F(this,"particleHandler",new kI),F(this,"effectHandler",new EI),F(this,"revealHandler",new MI),F(this,"lineHandler",new TI),F(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){Qi(`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(Qi(`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){Qi(`createInstance: FAILED - template ${e.macroId} not found`);return}Qi(`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=Y1(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&&Qi(`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":tm.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;Qi(`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 tm.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=[]}};K(q1,"MacroEngine");var UI=q1,Q1=class{constructor(){F(this,"axes",new Map),F(this,"buttons",new Map),F(this,"touchZones",new Map),F(this,"axisNameToId",new Map),F(this,"buttonNameToId",new Map),F(this,"touchZoneNameToId",new Map),F(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,Xc)),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}};K(bh,"Layer"),F(bh,"rasterizer",new kS);var ES=bh,Y1=class{constructor(){F(this,"macros",new Map),F(this,"macroNameToId",new Map),F(this,"nextMacroId",0),F(this,"instances",new Map),F(this,"instanceNameToId",new Map),F(this,"nextInstanceId",0),F(this,"layerNameToId",new Map),F(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()}};K(Y1,"MacroRegistry");var MS=Y1;function Pi(r){return typeof r=="number"?r:r.charCodeAt(0)}K(Pi,"toCharCode");function cu(r){return typeof r=="string"?r.charAt(0):String.fromCharCode(r)}K(cu,"toCharString");var TS=(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.Clear=19]="Clear",r[r.FillChar=20]="FillChar",r[r.FillSprite=21]="FillSprite",r[r.FillSpriteMultiColor=22]="FillSpriteMultiColor",r))(TS||{});function US(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}K(US,"isValidOrderType");function AS(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"Clear";case 20:return"FillChar";case 21:return"FillSprite";case 22:return"FillSpriteMultiColor";default:return`Unknown(0x${r.toString(16)})`}}K(AS,"getOrderTypeName");var RS={single:{topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",horizontal:"─",vertical:"│"},double:{topLeft:"╔",topRight:"╗",bottomLeft:"╚",bottomRight:"╝",horizontal:"═",vertical:"║"},rounded:{topLeft:"╭",topRight:"╮",bottomLeft:"╰",bottomRight:"╯",horizontal:"─",vertical:"│"}},sm={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=G1(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=Vf(r),i=e.states[n]??e.states.normal,s={...r.params,...i},o=[];if(e.subtype==="button"&&e.button)X1(r,e,s,o,t);else if(e.base)for(let a of e.base){let l=q1(a,r.x,r.y,s,t);l&&o.push(l)}return o}};function G1(r,e,t,n,i,s){return r>=t&&r<t+i&&e>=n&&e<n+s}K(G1,"isPointInRect");function Vf(r){return r.isDisabled?"disabled":r.isActive?"active":r.isHovered?"hover":r.isFocused?"focused":"normal"}K(Vf,"getUIState");function Ps(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}K(Ps,"toColorIndex");function X1(r,e,t,n,i){let s=e.button,o=Vf(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),g=a.offsetY??0,C=r.x,y=r.y+g;d==="none"?Z1(C,y,l,u,c,h,f,p,n):K1(C,y,l,u,c,h,f,p,d,n)}K(X1,"renderButton");function Z1(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})}K(Z1,"renderButtonNoBorder");function K1(r,e,t,n,i,s,o,a,l,u){let c=RS[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 g=1;g<n-1;g++)u.push({type:2,posX:r,posY:e+g,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})}K(K1,"renderButtonWithBorder");function q1(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:Ps(i.resolveValue(c,n)),bgColorCode:Ps(i.resolveValue(d,n)),frame:Array(i.resolveValue(a,n)*i.resolveValue(l,n)).fill(Pi(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:Ps(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:Pi(i.resolveValue(a,n)),fgColorCode:Ps(i.resolveValue(l,n)),bgColorCode:Ps(i.resolveValue(u,n))}}return null}K(q1,"executeRenderCommand");function Q1(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}}K(Q1,"createUIInstance");var J1=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 g=[];for(let C of e.particles){let y=Math.floor(C.x),m=Math.floor(C.y);if(y<d||y>=d+f||m<h||m>=h+p)continue;let v=C.fg;if(t.particle.fade&&C.maxLifetime>0){let b=C.lifetime/C.maxLifetime;v=this.fadeColorIndex(C.fg,b)}g.push({charCode:Pi(C.char),fgColorCode:v,bgColorCode:C.bg??255,posX:y,posY:m})}return[{type:12,dots:g}]}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,g=0;if("x"in a.velocity&&"y"in a.velocity)p=i(a.velocity.x,e.params),g=i(a.velocity.y,e.params);else if("angle"in a.velocity&&"speed"in a.velocity){let E=s(a.velocity.angle),U=s(a.velocity.speed,e.params),z=E*Math.PI/180;p=Math.cos(z)*U,g=Math.sin(z)*U}let C=s(a.lifetime),y=Array.isArray(a.char)?a.char[Math.floor(Math.random()*a.char.length)]:a.char,m=cu(y),v=Array.isArray(a.fg)?a.fg[Math.floor(Math.random()*a.fg.length)]:a.fg,b=typeof v=="number"?v:parseInt(v,10)||243,S=a.bg?Array.isArray(a.bg)?a.bg[Math.floor(Math.random()*a.bg.length)]:a.bg:void 0,I=S!==void 0?typeof S=="number"?S:parseInt(S,10)||255:void 0;return{x:h,y:f,vx:p,vy:g,char:m,fg:b,bg:I,lifetime:C,maxLifetime:C}}fadeColorIndex(e,t){return t<.1?255:e}};K(J1,"ParticleHandler");var PS=J1,ew=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}};K(ew,"EffectHandler");var zS=ew,tw=class{constructor(){F(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:Pi(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,g=d.get(p);g.charCode!==0&&i.push({char:String.fromCharCode(g.charCode),fg:g.fgColorCode,bg:g.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 g=f*l+p,C=c.get(g);C!==0&&i.push({char:String.fromCharCode(C),fg:d,bg:h,x:p,y:f,revealOrder:0})}}break}case"cells":{for(let o of s.cells)i.push({char:cu(o.char),fg:o.fg,bg:o.bg,x:o.x,y:o.y,revealOrder:0});break}case"fill":{let o=cu(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}};K(tw,"RevealHandler");var DS=tw,rw=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:Pi(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:Pi(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:Pi(s),fgColorCode:f,bgColorCode:a,points:h.map(p=>({x:p.x&255,y:p.y&255}))})}return u}};K(rw,"LineHandler");var OS=rw;function Qi(...r){}K(Qi,"macroLog");var nw=class{constructor(){F(this,"templates",new Map),F(this,"instances",new Map),F(this,"spriteRegistry",null),F(this,"playSound",null),F(this,"focusedInstanceId",null),F(this,"focusableInstances",[]),F(this,"mouseX",0),F(this,"mouseY",0),F(this,"mouseDown",!1),F(this,"particleHandler",new PS),F(this,"effectHandler",new zS),F(this,"revealHandler",new DS),F(this,"lineHandler",new OS),F(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){Qi(`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(Qi(`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){Qi(`createInstance: FAILED - template ${e.macroId} not found`);return}Qi(`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=Q1(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&&Qi(`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":sm.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;Qi(`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 sm.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=[]}};K(nw,"MacroEngine");var BS=nw,iw=class{constructor(){F(this,"axes",new Map),F(this,"buttons",new Map),F(this,"touchZones",new Map),F(this,"axisNameToId",new Map),F(this,"buttonNameToId",new Map),F(this,"touchZoneNameToId",new Map),F(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}};K(Q1,"InputBindingRegistry");var AI=Q1;function J1(r=0n){return{tick:r,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[]}}K(J1,"createEmptyCompressedInputPacket");function ew(r){let e=Math.max(-1,Math.min(1,r));return Math.round(e*127)}K(ew,"encodeAxisToInt8");function tw(r){return r/127}K(tw,"decodeInt8ToAxis");function Pu(r){return r===0?0:Math.ceil(r/8)}K(Pu,"getButtonByteCount");function rw(r,e){let t=r,n=Pu(e);return 8+t+n+4}K(rw,"getCompressedPacketSize");var nw=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}}};K(nw,"MacroEventDecoder");var RI=nw;tn();function iw(r,e){let t=e.getAllAxes().length,n=e.getAllButtons().length,i=Pu(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=J1();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=tw(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,a+=1,a<r.length){let c=r[a];a+=1;let d=new TextDecoder;l.textInputs=[];for(let h=0;h<c&&a<r.length;h++){let f=r[a];if(a+=1,a+f<=r.length){let p=r.slice(a,a+f),g=d.decode(p);l.textInputs.push(g),a+=f}}}if(a<r.length){let c=r[a];a+=1;let d=new RI,h=[],f=ie.from(r);for(let p=0;p<c&&a<r.length;p++){let g=d.decode(f,a);h.push(g.event),a+=g.bytesRead}l.macroEvents=h}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 g=(r[a]&1)!==0;a+=1,l.touchPositions.push({id:h,x:f,y:p,over:g})}}return l}K(iw,"decodeCompressedInput");var sw=class{constructor(e,t){F(this,"enabled",!1),F(this,"currentStats",null),F(this,"_userId"),F(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}};K(sw,"UserStats");var PI=sw,ow=class{constructor(e,t,n){this.id=e,this.name=t,F(this,"displays",[]),F(this,"layers",[]),F(this,"spriteRegistry"),F(this,"mode"),F(this,"axes",new Map),F(this,"buttons",new Map),F(this,"textInputs",[]),F(this,"mouseX",0),F(this,"mouseY",0),F(this,"mouseOver",!1),F(this,"mouseDisplayId",0),F(this,"touchPositions",new Map),F(this,"activeTouchId",null),F(this,"inputBindings",new AI),F(this,"stats"),F(this,"soundCommands",[]),F(this,"nextSoundInstanceId",1),F(this,"audioConfigCommands",[]),F(this,"lastListenerX",-1),F(this,"lastListenerY",-1),F(this,"pendingSendSounds",!1),F(this,"audioProcessor"),F(this,"loadedSounds",new Map),F(this,"soundLoadErrors",new Map),F(this,"playingSounds",new Map),F(this,"mobileVibrationCommands",[]),F(this,"mobileVibrationProcessor"),F(this,"gamepadVibrationCommands",[]),F(this,"gamepadVibrationProcessor"),F(this,"macroRegistry",new bI),F(this,"macroEngine",new UI),F(this,"macroEventHandlers",new Map),F(this,"postProcessCommands",[]),F(this,"currentPostProcessConfig",null),F(this,"bridgeMessages",[]),F(this,"totalBytesSent",0),F(this,"totalBytesReceived",0),F(this,"bytesSentPerTick",[]),F(this,"bytesReceivedPerTick",[]),F(this,"bytesTickIndex",0),F(this,"bytesTickRate",20),F(this,"currentTickBytesSent",0),F(this,"currentTickBytesReceived",0),F(this,"availableViewports",new Map),F(this,"data"),F(this,"currentScalingModes",new Map),F(this,"currentCellSizes",new Map),F(this,"currentGridConfigs",new Map),F(this,"currentPaletteSlotIds",new Map),this.mode=n,this.stats=new PI(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){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;e.setId(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 gI(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=n}n.setOrigin(new Ht(t.originX,t.originY)),n.setSize(new Ht(t.sizeX,t.sizeY))}}updateLayersFromPacket(e){for(let t of e){let n=this.findLayerById(t.id);n||(n=new wI(new Ht(t.originX,t.originY),t.zIndex,t.width,t.height,{isStatic:!1,charCodeMode:t.is16bit?"16bit":"8bit"}),n.setId(t.id),n.setMode(this.mode),this.spriteRegistry&&n.setSpriteRegistry(this.spriteRegistry),this.addLayer(n)),t.updateFlags&1&&n.setOrigin(new Ht(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}`);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=iw(e,this.inputBindings),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];this.setButton(u.name,l)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId;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}=(f1(),Go(h1)),{MobileVibrateFlags:n,GamepadVibrateFlags:i}=(g1(),Go(p1));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}=(w1(),Go(m1)),{PlaySoundFlags:i}=(C1(),Go(b1));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:Ys.color,lineWidth:Ys.lineWidth}:n={enabled:t.enabled,color:t.color??Ys.color,lineWidth:t.lineWidth??Ys.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())}}};K(ow,"User");var zI=ow;yo();yo();tn();var aw=class{constructor(){F(this,"charCodeSize",$f)}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.encodeClearOrder(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(zv+(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(Dv+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(Ov+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(Bv+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(Fv+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(Lv+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(_v+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($v),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(Nv),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(Wv+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(Hv+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(Vv+(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(jv+(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(Yv+(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(Gv+(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(Xv+(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(Zv+(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(Kv+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(qv+(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(Qv+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(Jv+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(e1+(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(t1+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(r1+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(n1+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(i1+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()}encodeClearOrder(e,t){let n=ie.allocUnsafe(s1+(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(o1+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(a1),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(l1),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.spriteIndex,n++),t.toUint8Array()}};K(aw,"OrderEncoder");var DI=aw;tn();var rm=255,nm=64,lw=class{constructor(){F(this,"orderEncoder"),this.orderEncoder=new DI}encode(e){let t=e.is16bit;if(e.orders.length>rm)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${rm}. 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;t?u|=nm:u&=~nm,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)}};K(lw,"LayerEncoder");var OI=lw;tn();yo();var uw=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 rh;case 8:return nh;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=u1;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=c1,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(rh),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(nh),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}};K(uw,"AudioOrderEncoder");var BI=uw;tn();var cw=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()}};K(cw,"VibrationOrderEncoder");var FI=cw;tn();var dw=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()}};K(dw,"MacroOrderEncoder");var LI=dw;tn();yo();var hw=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 ih;case 3:return sh;case 4:return oh;case 5:return ah;case 6:return lh;case 7:return uh;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=d1;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=ie.allocUnsafe(ih),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(sh),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(oh),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(ah),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(lh),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(uh),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()}};K(hw,"PostProcessOrderEncoder");var _I=hw;tn();var fw=class{constructor(){F(this,"layerEncoder"),F(this,"audioOrderEncoder"),F(this,"vibrationOrderEncoder"),F(this,"macroOrderEncoder"),F(this,"postProcessOrderEncoder"),this.layerEncoder=new OI,this.audioOrderEncoder=new BI,this.vibrationOrderEncoder=new FI,this.macroOrderEncoder=new LI,this.postProcessOrderEncoder=new _I}encode(e){let t=e.layers.map(R=>this.layerEncoder.encode(R)),n=e.audioOrders||[],i=n.map(R=>this.audioOrderEncoder.encode(R)),s=e.vibrationOrders||[],o=s.map(R=>this.vibrationOrderEncoder.encode(R)),a=e.macroOrders||[],l=a.map(R=>this.macroOrderEncoder.encode(R)),u=e.postProcessOrders||[],c=u.map(R=>this.postProcessOrderEncoder.encode(R)),d=9,h=e.displays.length*7,f=2,p=t.reduce((R,B)=>R+B.length,0),g=1,x=i.reduce((R,B)=>R+B.length,0),y=1,m=o.reduce((R,B)=>R+B.length,0),v=1,b=l.reduce((R,B)=>R+B.length,0),I=1,S=c.reduce((R,B)=>R+B.length,0),M=d+h+f+p+g+x+y+m+v+b+I+S,U=ie.allocUnsafe(M),z=0,O=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);U.writeBigUInt64BE(O,z),z+=8,U.writeUInt8(e.displays.length,z),z+=1;for(let R of e.displays)U.writeUInt8(R.id,z++),U.writeUInt16BE(R.originX,z),z+=2,U.writeUInt16BE(R.originY,z),z+=2,U.writeUInt8(Math.max(1,Math.min(256,R.sizeX))-1,z++),U.writeUInt8(Math.max(1,Math.min(256,R.sizeY))-1,z++);U.writeUInt16BE(e.layers.length,z),z+=2;for(let R of t)ie.from(R).copy(U,z),z+=R.length;U.writeUInt8(n.length,z),z+=1;for(let R of i)ie.from(R).copy(U,z),z+=R.length;U.writeUInt8(s.length,z),z+=1;for(let R of o)ie.from(R).copy(U,z),z+=R.length;U.writeUInt8(a.length,z),z+=1;for(let R of l)ie.from(R).copy(U,z),z+=R.length;U.writeUInt8(u.length,z),z+=1;for(let R of c)ie.from(R).copy(U,z),z+=R.length;return U.toUint8Array()}calculateSize(e){let t=e.displays.length*7,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()}};K(fw,"UpdatePacketEncoder");var $I=fw,NI=(r=>(r[r.ColorPalette=1]="ColorPalette",r[r.Sprite=2]="Sprite",r[r.MulticolorSprite=3]="MulticolorSprite",r[r.BitmapFont=4]="BitmapFont",r[r.Sound=5]="Sound",r[r.WebFont=6]="WebFont",r[r.Macro=7]="Macro",r[r.ImageFont=8]="ImageFont",r))(NI||{});tn();var pw=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}};K(pw,"MacroLoadEncoder");var WI=pw;tn();var gw=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 4:return this.encodeBitmapFont(e);case 5:return this.encodeSound(e);case 6:return this.encodeWebFont(e);case 8:return this.encodeImageFont(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,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()}encodeBitmapFont(e){let t=e.characters.length;if(t>255)throw new Error(`Character count ${t} exceeds maximum of 255`);let n=Math.ceil(e.width*e.height/8),i=7+t*(1+n),s=ie.allocUnsafe(i),o=0;s.writeUInt8(4,o++),s.writeUInt8(e.fontId,o++),s.writeUInt8(e.width,o++),s.writeUInt8(e.height,o++),s.writeUInt8(e.cellWidth,o++),s.writeUInt8(e.cellHeight,o++),s.writeUInt8(t,o++);for(let a of e.characters){if(a.bitmap.length!==n)throw new Error(`Character ${a.charCode}: bitmap size ${a.bitmap.length} does not match expected ${n} bytes`);s.writeUInt8(a.charCode,o++);for(let l=0;l<a.bitmap.length;l++)s.writeUInt8(a.bitmap[l],o++)}return s.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()}encodeWebFont(e){let t=new TextEncoder,n=t.encode(e.fontFamily),i=e.fontWeight?t.encode(e.fontWeight):new Uint8Array(0),s=e.fontStyle?t.encode(e.fontStyle):new Uint8Array(0),o=0;e.offsetX!==void 0&&(o|=1),e.offsetY!==void 0&&(o|=2),e.charSpacing!==void 0&&(o|=4),e.lineHeight!==void 0&&(o|=8),e.fontWeight!==void 0&&(o|=16),e.fontStyle!==void 0&&(o|=32);let a=4;a+=n.length,a+=2,e.offsetX!==void 0&&(a+=2),e.offsetY!==void 0&&(a+=2),e.charSpacing!==void 0&&(a+=2),e.lineHeight!==void 0&&(a+=2),e.fontWeight!==void 0&&(a+=1+i.length),e.fontStyle!==void 0&&(a+=1+s.length);let l=ie.allocUnsafe(a),u=0;l.writeUInt8(6,u++),l.writeUInt8(e.fontId,u++),l.writeUInt8(o,u++),l.writeUInt8(n.length,u++);for(let c=0;c<n.length;c++)l.writeUInt8(n[c],u++);if(l.writeUInt16BE(e.fontSize,u),u+=2,e.offsetX!==void 0&&(l.writeInt16BE(e.offsetX,u),u+=2),e.offsetY!==void 0&&(l.writeInt16BE(e.offsetY,u),u+=2),e.charSpacing!==void 0&&(l.writeInt16BE(e.charSpacing,u),u+=2),e.lineHeight!==void 0&&(l.writeUInt16BE(Math.round(e.lineHeight*100),u),u+=2),e.fontWeight!==void 0){l.writeUInt8(i.length,u++);for(let c=0;c<i.length;c++)l.writeUInt8(i[c],u++)}if(e.fontStyle!==void 0){l.writeUInt8(s.length,u++);for(let c=0;c<s.length;c++)l.writeUInt8(s[c],u++)}return l.toUint8Array()}encodeImageFont(e){if(![1,4,16].includes(e.atlasBlocks))throw new Error(`Invalid atlasBlocks: ${e.atlasBlocks}. Must be 1, 4, or 16.`);if(e.imageData.length>16*1024*1024)throw new Error(`Image data size ${e.imageData.length} exceeds maximum of 16MB`);let t=11+e.imageData.length,n=ie.allocUnsafe(t),i=0;n.writeUInt8(8,i++),n.writeUInt8(e.fontId,i++),n.writeUInt8(e.glyphWidth,i++),n.writeUInt8(e.glyphHeight,i++),n.writeUInt8(e.cellWidth,i++),n.writeUInt8(e.cellHeight,i++),n.writeUInt8(e.atlasBlocks,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()}};K(gw,"LoadEncoder");var Us=gw;tn();var mw=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}}};K(mw,"MacroLoadDecoder");var HI=mw,yw=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 4:return this.decodeBitmapFont(n,t);case 5:return this.decodeSound(n,t);case 6:return this.decodeWebFont(n,t);case 7:return this.decodeMacro(n,t);case 8:return this.decodeImageFont(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,d=c*3;this.checkSize(e,t,d,`MulticolorSprite ${o} data`);let h=[];for(let f=0;f<c;f++)h.push({charCode:e.readUInt8(t++),fgColorId:e.readUInt8(t++),bgColorId:e.readUInt8(t++)});s.push({spriteId:a,sizeX:l,sizeY:u,data:h})}return{load:{loadType:3,sprites:s},bytesRead:t-n}}decodeBitmapFont(e,t){let n=t;this.checkSize(e,t,7,"BitmapFont 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++),u=e.readUInt8(t++),c=Math.ceil(s*o/8),d=[];for(let h=0;h<u;h++){this.checkSize(e,t,1+c,`BitmapFont character ${h}`);let f=e.readUInt8(t++),p=new Uint8Array(c);for(let g=0;g<c;g++)p[g]=e.readUInt8(t++);d.push({charCode:f,bitmap:p})}return{load:{loadType:4,fontId:i,width:s,height:o,cellWidth:a,cellHeight:l,characters:d},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`)}decodeWebFont(e,t){let n=t,i=new TextDecoder;this.checkSize(e,t,5,"WebFont header"),e.readUInt8(t++);let s=e.readUInt8(t++),o=e.readUInt8(t++),a=e.readUInt8(t++);this.checkSize(e,t,a,"WebFont family string");let l=new Uint8Array(a);for(let h=0;h<a;h++)l[h]=e.readUInt8(t++);let u=i.decode(l);this.checkSize(e,t,2,"WebFont fontSize");let c=e.readUInt16BE(t);t+=2;let d={loadType:6,fontId:s,fontFamily:u,fontSize:c};if(o&1&&(this.checkSize(e,t,2,"WebFont offsetX"),d.offsetX=e.readInt16BE(t),t+=2),o&2&&(this.checkSize(e,t,2,"WebFont offsetY"),d.offsetY=e.readInt16BE(t),t+=2),o&4&&(this.checkSize(e,t,2,"WebFont charSpacing"),d.charSpacing=e.readInt16BE(t),t+=2),o&8){this.checkSize(e,t,2,"WebFont lineHeight");let h=e.readUInt16BE(t);d.lineHeight=h/100,t+=2}if(o&16){this.checkSize(e,t,1,"WebFont weight length");let h=e.readUInt8(t++);this.checkSize(e,t,h,"WebFont weight string");let f=new Uint8Array(h);for(let p=0;p<h;p++)f[p]=e.readUInt8(t++);d.fontWeight=i.decode(f)}if(o&32){this.checkSize(e,t,1,"WebFont style length");let h=e.readUInt8(t++);this.checkSize(e,t,h,"WebFont style string");let f=new Uint8Array(h);for(let p=0;p<h;p++)f[p]=e.readUInt8(t++);d.fontStyle=i.decode(f)}return{load:d,bytesRead:t-n}}decodeMacro(e,t){return new HI().decode(e,t)}decodeImageFont(e,t){let n=t;this.checkSize(e,t,7,"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++),u=e.readUInt8(t++);if(![1,4,16].includes(u))throw new Error(`Invalid atlasBlocks value: ${u}. Must be 1, 4, or 16.`);let c=u;this.checkSize(e,t,4,"ImageFont image data size");let d=e.readUInt32LE(t);t+=4,this.checkSize(e,t,d,"ImageFont image data");let h=new Uint8Array(d);for(let f=0;f<d;f++)h[f]=e.readUInt8(t++);return{load:{loadType:8,fontId:i,glyphWidth:s,glyphHeight:o,cellWidth:a,cellHeight:l,atlasBlocks:c,imageData:h},bytesRead:t-n}}};K(yw,"LoadDecoder");var VI=yw,vh=class Zo{constructor(e){this.engine=e,F(this,"colorCache",new Array(256)),F(this,"cellsBuffer",[]),F(this,"opacityBuffer",new Uint8Array(0)),F(this,"visibleLayersBuffer",[]),F(this,"visibleLayerIdsBuffer",[]),this.rebuildColorCache()}static getChar(e){let t=Zo.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),Zo.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){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 g=o[p],x=h-g.getOrigin().x,y=f-g.getOrigin().y,m=g.getWidth(),v=g.getHeight();if(x<0||x>=m||y<0||y>=v)continue;let b=y*m+x,I=g.getData(),S=I.getCharCode(b),M=I.getFgColorCode(b),U=I.getBgColorCode(b),z=i[d];if(S!==0&&z.char===" "&&(z.char=Zo.getChar(S)),M!==255&&z.fgColorIndex===255&&(z.fgColorIndex=M,z.fgEmission=this.getColorEmission(M)),U!==255){z.bgColorIndex===255&&(z.bgColorIndex=U,z.bgEmission=this.getColorEmission(U)),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}}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],g=d-p.getOrigin().x,x=h-p.getOrigin().y,y=p.getWidth(),m=p.getHeight();if(g<0||g>=y||x<0||x>=m)continue;let v=x*y+g,b=p.getData(),I=b.getCharCode(v),S=b.getFgColorCode(v),M=b.getBgColorCode(v),U=i[c];if(I!==0&&U.char===" "&&(U.char=Zo.getChar(I)),S!==255&&U.fgColorIndex===255&&(U.fgColorIndex=S,U.fgEmission=this.getColorEmission(S)),M!==255){U.bgColorIndex===255&&(U.bgColorIndex=M,U.bgEmission=this.getColorEmission(M)),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}}}};K(vh,"DisplayRasterizer"),F(vh,"charCache",(()=>{let r=new Map;for(let e=0;e<256;e++)r.set(e,String.fromCharCode(e));return r})());var jI=vh,vw=class{constructor(){F(this,"enabled",!1),F(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,isStatic: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}};K(vw,"CoreStats");var YI=vw,ww=class{constructor(){F(this,"unicolorSprites",new Map),F(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){for(let t of e.sprites){let n=new mI(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){for(let t of e.sprites){let n=new F1(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}};K(ww,"SpriteRegistry");var GI=ww,XI=(r=>(r.Web="web",r.Bitmap="bitmap",r.Image="image",r))(XI||{});function Wf(r){return Math.sqrt(r)*16}K(Wf,"getAtlasColumns");function bw(r){return r*256-1}K(bw,"getMaxCharCode");function ZI(r,e){let t=Wf(r)*e;return{width:t,height:t}}K(ZI,"getAtlasDimensions");var Cw=class{constructor(e,t){this.fontId=e,this.config=t}getFontId(){return this.fontId}getConfig(){return{...this.config}}getFontFamily(){return this.config.fontFamily}getFontSize(){return this.config.fontSize}getOffsetX(){return this.config.offsetX??0}getOffsetY(){return this.config.offsetY??0}getCharSpacing(){return this.config.charSpacing??0}getLineHeight(){return this.config.lineHeight??1.2}getFontWeight(){return this.config.fontWeight??"normal"}getFontStyle(){return this.config.fontStyle??"normal"}toCSS(){let e=[];e.push(`font-family: ${this.config.fontFamily}`),e.push(`font-size: ${this.config.fontSize}px`);let t=this.config.fontWeight??"normal";t!=="normal"&&e.push(`font-weight: ${t}`);let n=this.config.fontStyle??"normal";return n!=="normal"&&e.push(`font-style: ${n}`),e.join("; ")+";"}};K(Cw,"WebFont");var xw=Cw,Sw=class{constructor(e,t){this.fontId=e,this.config=t}getFontId(){return this.fontId}getConfig(){return{charWidth:this.config.charWidth,charHeight:this.config.charHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,glyphs:new Map(this.config.glyphs)}}getCharWidth(){return this.config.charWidth}getCharHeight(){return this.config.charHeight}getCellWidth(){return this.config.cellWidth??this.config.charWidth}getCellHeight(){return this.config.cellHeight??this.config.charHeight}getGlyph(e){return this.config.glyphs.get(e)}hasGlyph(e){return this.config.glyphs.has(e)}getGlyphCount(){return this.config.glyphs.size}getCharCodes(){return Array.from(this.config.glyphs.keys())}};K(Sw,"BitmapFont");var KI=Sw,Iw=class{constructor(e,t){this.fontId=e,this.config=t,F(this,"atlasColumns"),F(this,"maxCharCode"),this.atlasColumns=Wf(t.atlasBlocks),this.maxCharCode=bw(t.atlasBlocks)}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,imageData:this.config.imageData}}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}getImageData(){return this.config.imageData}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}};K(Iw,"ImageFont");var im=Iw,kw=class{constructor(){F(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`WebFont with ID ${e} already exists`);let n=new xw(e,t);this.fonts.set(e,n)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};K(kw,"WebFontRegistry");var qI=kw,Ew=class{constructor(){F(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`BitmapFont with ID ${e} already exists`);let n=new KI(e,t);this.fonts.set(e,n)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};K(Ew,"BitmapFontRegistry");var QI=Ew,Mw=class{constructor(){F(this,"fonts",new Map),F(this,"nameToId",new Map),F(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,n){if(this.nameToId.has(e))throw new Error(`ImageFont with name "${e}" already exists`);let i=this.allocateId(e),s={glyphWidth:t.glyphWidth,glyphHeight:t.glyphHeight,cellWidth:t.cellWidth,cellHeight:t.cellHeight,atlasBlocks:t.atlasBlocks??1,imageData:n},o=new im(i,s);return this.fonts.set(i,o),this.nameToId.set(e,i),i}loadFont(e,t){if(this.fonts.has(e))throw new Error(`ImageFont with ID ${e} already exists`);let n=new im(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}};K(Mw,"ImageFontRegistry");var JI=Mw,Tw=class{constructor(){F(this,"sounds",new Map),F(this,"nameToId",new Map),F(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`)}};K(Tw,"SoundRegistry");var ek=Tw,Uw=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)}};K(Uw,"AudioOrderCollector");var tk=Uw,Aw=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}}};K(Aw,"VibrationOrderCollector");var rk=Aw,Rw=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:Pv(t)}}createSetGridOrder(e,t){let{r:n,g:i,b:s,a:o}=this.parseColor(t.color??Ys.color);return{type:5,displayId:e,enabled:t.enabled,colorR:n,colorG:i,colorB:s,colorA:o,lineWidth:t.lineWidth??Ys.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}}};K(Rw,"PostProcessOrderCollector");var Hf=Rw,wh=class zl{constructor(e={}){F(this,"users",new Map),F(this,"mode"),F(this,"maxUsers"),F(this,"strictMode"),F(this,"currentTick",0),F(this,"encoder"),F(this,"displayRasterizer"),F(this,"colorPalette",new Map),F(this,"stats",new YI),F(this,"spriteRegistry",new GI),F(this,"webFontRegistry",new qI),F(this,"bitmapFontRegistry",new QI),F(this,"imageFontRegistry",new JI),F(this,"soundRegistry",new ek),F(this,"audioOrderCollector"),F(this,"vibrationOrderCollector"),F(this,"postProcessOrderCollector"),F(this,"activeWebFontId",0),F(this,"_renderCallCount",0),F(this,"paletteSlots",new Map),F(this,"onPaletteChangedCallback"),F(this,"onBitmapFontChangedCallback"),F(this,"onImageFontChangedCallback"),this.mode=e.mode??"server",this.maxUsers=e.maxUsers??64,this.strictMode=e.strictMode??!1,this.encoder=new $I,this.displayRasterizer=new jI(this),this.audioOrderCollector=new tk(this.soundRegistry),this.vibrationOrderCollector=new rk,this.postProcessOrderCollector=new Hf,this.initializeDefaultPalette(),this.displayRasterizer.rebuildColorCache(),this.loadDefaultWebFont()}initializeDefaultPalette(){zl.ANSI_VGA_COLORS.forEach(e=>{this.colorPalette.set(e.colorId,{r:e.r,g:e.g,b:e.b,a:e.a,e:e.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0})}getMode(){return this.mode}getMaxUsers(){return this.maxUsers}isStrictMode(){return this.strictMode}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 zI(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}onBitmapFontChanged(e){this.onBitmapFontChangedCallback=e}getColor(e){return this.colorPalette.get(e)??null}loadPalette(e){for(let t of e)t.colorId<0||t.colorId>255||this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e??0});zl.ANSI_VGA_COLORS.forEach(t=>{this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0}),this.displayRasterizer.rebuildColorCache(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}getPalette(){return new Map(this.colorPalette)}resetPalette(){this.colorPalette.clear(),this.initializeDefaultPalette(),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,e:i.e??0});zl.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(y=>{let m=y.getOrigin(),v=y.getSize();return{id:y.getId(),originX:m.x,originY:m.y,sizeX:v.x,sizeY:v.y}});a.forEach(y=>y.resetChangeTracking());let u=[],c=[];o.forEach((y,m)=>{if(!y.getNeedsCommit())return;let v=y.getOrigin(),b=y.getOrders(),I=y.getStatic(),S=y.calculateUpdateFlags();y.resetChangeTracking(),y.resetCommit(),y.getId()===0&&y.setId(m);let M={id:y.getId(),updateFlags:S,zIndex:y.getZOrder(),originX:v.x,originY:v.y,width:y.getWidth(),height:y.getHeight(),is16bit:y.getCharCodeMode()==="16bit",orderCount:b.length,orders:b};b.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(y.getId(),I,b.length,S),I?u.push(M):c.push(M)}),n+=u.length+c.length;let d=this.audioOrderCollector.collectFromUser(i),h=this.vibrationOrderCollector.collectFromUser(i),f=this.postProcessOrderCollector.collectFromUser(i),p=i.flushMacroOrders(),g=null,x=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(s,l.length,u.length,c.length),u.length>0&&(g=this.encoder.encode({tick:this.currentTick,displayCount:l.length,displays:l,layerCount:u.length,layers:u,audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})),x=this.encoder.encode({tick:this.currentTick,displayCount:l.length,displays:l,layerCount:c.length,layers:c,audioOrderCount:d.length,audioOrders:d,vibrationOrderCount:h.length,vibrationOrders:h,macroOrderCount:p.length,macroOrders:p,postProcessOrderCount:f.length,postProcessOrders:f}),e.set(s,{static:g,dynamic:x}),i.getStats().isEnabled()){let y=a.reduce((I,S)=>{let M=S.getSize();return I+M.x*M.y},0);i.getStats().recordDisplays(a.length,y),i.getStats().recordLayers(o.length,u.length+c.length,u.length,c.length),[...u,...c].forEach(I=>{i.getStats().recordLayerOrders(I.id,I.orders.length)});let m=(g==null?void 0:g.length)||0,v=(x==null?void 0:x.length)||0;i.getStats().recordPacketSizes(m,v);let b=i.getInputBindingRegistry();i.getStats().recordInput(!1,b.getAxisCount(),b.getButtonCount()),i.getStats().endTick()}if(i.endTickBytes(),this.stats.isEnabled()){let y=[...u,...c];y.forEach((S,M)=>{this.stats.recordLayerOrders(M,S.orders)}),a.forEach((S,M)=>{this.stats.recordDisplayLayers(M,y.length)});let m=((g==null?void 0:g.length)||0)+((x==null?void 0:x.length)||0),v=a.length*12,b=y.length*20,I=m-v-b;this.stats.recordUpdatePacketSize(m,v,b,I>0?I: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}}),o=i.map((a,l)=>{let u=a.getOrigin(),c=a.getOrders();return a.getId()===0&&a.setId(l),{id:a.getId(),updateFlags:7,zIndex:a.getZOrder(),originX:u.x,originY:u.y,width:a.getWidth(),height:a.getHeight(),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{UpdatePacketDecoder:n}=(D1(),Go(P1)),i=new n().decode(t);return this.applyUpdatePacket(e,i)?i:null}applyLoadPacket(e){try{let t=new VI().decode(e).load;switch(t.loadType){case 1:t.slotId!==void 0?this.loadPaletteToSlot(t.slotId,t.colors):this.loadPalette(t.colors);break;case 2:this.loadUnicolorSprites(t);break;case 3:this.loadMulticolorSprites(t);break;case 4:{let n=this.getBitmapFontRegistry();n.hasFont(t.fontId)&&n.unloadFont(t.fontId),n.loadFont(t.fontId,{charWidth:t.width,charHeight:t.height,cellWidth:t.cellWidth,cellHeight:t.cellHeight,glyphs:new Map(t.characters.map(i=>[i.charCode,i.bitmap]))});break}case 6:{let n=this.getWebFontRegistry();n.hasFont(t.fontId)&&n.unloadFont(t.fontId),this.loadWebFontById(t.fontId,{fontFamily:t.fontFamily,fontSize:t.fontSize,offsetX:t.offsetX,offsetY:t.offsetY,charSpacing:t.charSpacing,lineHeight:t.lineHeight,fontWeight:t.fontWeight,fontStyle:t.fontStyle});break}case 5:console.warn("[Core] Sound loading not yet implemented");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}}generatePaletteLoadPacket(){let e=this.getPalette();if(e.size===0)return null;let t=new Us,n=[];return e.forEach((i,s)=>{s!==255&&n.push({colorId:s,r:i.r,g:i.g,b:i.b,a:i.a,e:i.e})}),t.encode({loadType:1,colors:n})}generatePaletteSlotLoadPacket(e){let t=this.getPaletteFromSlot(e);if(!t||t.size===0)return null;let n=new Us,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(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let i=e.getUnicolorSprite(n);if(i){let s=[];for(let o=0;o<i.sizeX*i.sizeY;o++)s.push(i.data.get(o));t.push({spriteId:i.id,sizeX:i.sizeX,sizeY:i.sizeY,data:s})}}return t.length===0?null:new Us().encode({loadType:2,sprites:t})}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 Us().encode({loadType:3,sprites:t})}generateWebFontsLoadPackets(){let e=this.getWebFontRegistry(),t=e.getFontIds(),n=[],i=new Us;for(let s of t){let o=e.getFont(s);if(o){let a=o.getConfig(),l=i.encode({loadType:6,fontId:s,fontFamily:a.fontFamily,fontSize:a.fontSize,offsetX:a.offsetX,offsetY:a.offsetY,charSpacing:a.charSpacing,lineHeight:a.lineHeight,fontWeight:a.fontWeight,fontStyle:a.fontStyle});n.push(l)}}return n}generateBitmapFontsLoadPackets(){let e=this.getBitmapFontRegistry(),t=e.getFontIds(),n=[],i=new Us;for(let s of t){let o=e.getFont(s);if(o){let a=[];for(let l=0;l<256;l++){let u=o.getGlyph(l);u&&a.push({charCode:l,bitmap:u})}if(a.length>0){let l=i.encode({loadType:4,fontId:s,width:o.getCharWidth(),height:o.getCharHeight(),cellWidth:o.getCellWidth(),cellHeight:o.getCellHeight(),characters:a});n.push(l)}}}return n}generateAllLoadPackets(){let e=[],t=this.generatePaletteLoadPacket();t&&e.push(t);let n=this.generateAllPaletteSlotLoadPackets();e.push(...n);let i=this.generateUnicolorSpritesLoadPacket();i&&e.push(i);let s=this.generateMulticolorSpritesLoadPacket();s&&e.push(s);let o=this.generateWebFontsLoadPackets();e.push(...o);let a=this.generateBitmapFontsLoadPackets();return e.push(...a),e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let n=t.getMacroLoads();if(n.length===0)return[];let i=new WI;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)),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)}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.loadSoundData(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 loadSoundData(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 sound "${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 sound "${e}": ${p}`)}let a=typeof dl<"u"?dl: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()}loadDefaultWebFont(){this.webFontRegistry.loadFont(0,{fontFamily:"Courier New",fontSize:16,offsetX:0,offsetY:0,charSpacing:0,lineHeight:1,fontWeight:"normal",fontStyle:"normal"}),this.activeWebFontId=0}loadWebFont(e){let t=e.getFontId(),n=e.getConfig();this.webFontRegistry.loadFont(t,n)}getWebFont(e){return this.webFontRegistry.getFont(e)??null}hasWebFont(e){return this.webFontRegistry.hasFont(e)}unloadWebFont(e){if(e===0)throw new Error("Cannot unload default font (fontId 0)");return this.webFontRegistry.unloadFont(e)}clearWebFonts(){this.webFontRegistry.clearFonts(),this.loadDefaultWebFont()}setActiveWebFont(e){if(!this.webFontRegistry.hasFont(e))throw new Error(`WebFont with ID ${e} does not exist`);this.activeWebFontId=e}getActiveWebFontId(){return this.activeWebFontId}getActiveWebFont(){let e=this.webFontRegistry.getFont(this.activeWebFontId);if(!e)throw new Error(`Active WebFont ${this.activeWebFontId} not found. This should not happen.`);return e}getWebFontCount(){return this.webFontRegistry.getFontCount()}getWebFontIds(){return this.webFontRegistry.getFontIds()}getWebFontRegistry(){return this.webFontRegistry}getBitmapFontRegistry(){return this.bitmapFontRegistry}loadWebFontById(e,t){let n=new xw(e,t);this.loadWebFont(n)}loadBitmapFontById(e,t){this.bitmapFontRegistry.loadFont(e,t),this.onBitmapFontChangedCallback&&this.onBitmapFontChangedCallback(e)}getBitmapFont(e){return this.bitmapFontRegistry.getFont(e)??null}hasBitmapFont(e){return this.bitmapFontRegistry.hasFont(e)}unloadBitmapFont(e){return this.bitmapFontRegistry.unloadFont(e)}clearBitmapFonts(){this.bitmapFontRegistry.clearFonts()}getBitmapFontCount(){return this.bitmapFontRegistry.getFontCount()}getBitmapFontIds(){return this.bitmapFontRegistry.getFontIds()}async loadImageFont(e,t,n){let i=await this.loadImageData(t),s=this.imageFontRegistry.registerFont(e,n,i);return this.onImageFontChangedCallback&&this.onImageFontChangedCallback(s),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 dl<"u"?dl: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}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()}};K(wh,"Core"),F(wh,"ANSI_VGA_COLORS",[{colorId:240,r:16,g:16,b:16,a:255,e:0},{colorId:241,r:128,g:128,b:128,a:255,e:0},{colorId:242,r:192,g:192,b:192,a:255,e:0},{colorId:243,r:240,g:240,b:240,a:255,e:0},{colorId:244,r:200,g:50,b:50,a:255,e:0},{colorId:245,r:50,g:200,b:50,a:255,e:0},{colorId:246,r:220,g:180,b:50,a:255,e:0},{colorId:247,r:50,g:100,b:220,a:255,e:0},{colorId:248,r:50,g:200,b:200,a:255,e:0},{colorId:249,r:200,g:50,b:200,a:255,e:0},{colorId:250,r:220,g:120,b:50,a:255,e:0},{colorId:251,r:120,g:220,b:120,a:255,e:0},{colorId:252,r:120,g:180,b:220,a:255,e:0},{colorId:253,r:220,g:150,b:200,a:255,e:0},{colorId:254,r:250,g:220,b:150,a:255,e:0}]);var Pw=wh,_a=new Map([[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])],[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])],[179,new Uint8Array([24,24,24,24,24,24,24,24])],[196,new Uint8Array([0,0,0,255,0,0,0,0])],[218,new Uint8Array([0,0,0,31,24,24,24,24])],[191,new Uint8Array([0,0,0,248,24,24,24,24])],[192,new Uint8Array([24,24,24,31,0,0,0,0])],[217,new Uint8Array([24,24,24,248,0,0,0,0])],[195,new Uint8Array([24,24,24,31,24,24,24,24])],[180,new Uint8Array([24,24,24,248,24,24,24,24])],[194,new Uint8Array([0,0,0,255,24,24,24,24])],[193,new Uint8Array([24,24,24,255,0,0,0,0])],[197,new Uint8Array([24,24,24,255,24,24,24,24])],[186,new Uint8Array([54,54,54,54,54,54,54,54])],[205,new Uint8Array([0,0,0,255,0,255,0,0])],[201,new Uint8Array([0,0,0,63,54,54,54,54])],[187,new Uint8Array([0,0,0,252,54,54,54,54])],[200,new Uint8Array([54,54,54,63,0,0,0,0])],[188,new Uint8Array([54,54,54,252,0,0,0,0])],[204,new Uint8Array([54,54,54,63,54,54,54,54])],[185,new Uint8Array([54,54,54,252,54,54,54,54])],[203,new Uint8Array([0,0,0,255,54,54,54,54])],[202,new Uint8Array([54,54,54,255,0,0,0,0])],[206,new Uint8Array([54,54,54,255,54,54,54,54])],[219,new Uint8Array([255,255,255,255,255,255,255,255])],[178,new Uint8Array([170,85,170,85,170,85,170,85])],[177,new Uint8Array([136,34,136,34,136,34,136,34])],[176,new Uint8Array([34,136,34,136,34,136,34,136])],[223,new Uint8Array([255,255,255,255,0,0,0,0])],[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])]]);function nk(r){return _a.get(r)}K(nk,"getCharBitmap");function ik(r){return _a.has(r)}K(ik,"hasChar");function sk(){return Array.from(_a.keys()).sort((r,e)=>r-e)}K(sk,"getAllCharCodes");function ok(r){let e=Array.from(_a.entries()).map(([t,n])=>({charCode:t,bitmap:n}));return{loadType:4,fontId:r,width:8,height:8,cellWidth:8,cellHeight:8,characters:e}}K(ok,"createASCII8x8FontLoad");function ak(){return{charWidth:8,charHeight:8,glyphs:new Map(_a)}}K(ak,"getASCII8x8FontConfig");tn();var zw=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()}};K(zw,"MacroEventEncoder");var lk=zw;function Dw(r,e,t,n,i,s,o,a=[],l=[],u=[],c=[]){let d=Array.from(e.entries()).sort((H,P)=>H[0]-P[0]),h=Array.from(t.entries()).sort((H,P)=>H[0]-P[0]),f=d.length,p=h.length,g=rw(f,p),x=new TextEncoder,y=a.map(H=>x.encode(H)),m=1+y.reduce((H,P)=>H+1+P.length,0),v=new lk,b=l.map(H=>v.encode(H)),I=1+b.reduce((H,P)=>H+P.length,0),S=Math.min(u.length,255),M=1+S*5,U=Math.min(c.length,10),z=1+U*4,O=g+m+I+M+z,R=new Uint8Array(O),B=new DataView(R.buffer),A=0;B.setBigUint64(A,r,!0),A+=8;for(let[,H]of d){let P=ew(H);R[A]=P+256&255,A+=1}let V=Pu(p);for(let H=0;H<V;H++){let P=0;for(let W=0;W<8;W++){let j=H*8+W;if(j<p){let[,X]=h[j];X&&(P|=1<<W)}}R[A]=P,A+=1}R[A]=n&255,A+=1,R[A]=i&255,A+=1,R[A]=s&255,A+=1;let N=0;o&&(N|=1),R[A]=N,A+=1,R[A]=Math.min(a.length,255),A+=1;for(let H of y)R[A]=Math.min(H.length,255),A+=1,R.set(H.slice(0,255),A),A+=H.length;R[A]=Math.min(l.length,255),A+=1;for(let H of b)R.set(H,A),A+=H.length;R[A]=S,A+=1;for(let H=0;H<S;H++){let P=u[H];R[A]=P.displayId&255,A+=1,B.setUint16(A,Math.min(P.pixelWidth,65535),!1),A+=2,B.setUint16(A,Math.min(P.pixelHeight,65535),!1),A+=2}R[A]=U,A+=1;for(let H=0;H<U;H++){let P=c[H];R[A]=P.id&15,A+=1,R[A]=P.x&255,A+=1,R[A]=P.y&255,A+=1,R[A]=P.over?1:0,A+=1}return R}K(Dw,"encodeCompressedInput");var uk=class kt{static toCharCode(e){if(typeof e=="number")return e&65535;let t=e.charCodeAt(0);return uu(t)}static dedent(e){let t=e.split(`
|
|
52
|
+
`}),e}};K(iw,"InputBindingRegistry");var FS=iw;function sw(r=0n){return{tick:r,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[]}}K(sw,"createEmptyCompressedInputPacket");function ow(r){let e=Math.max(-1,Math.min(1,r));return Math.round(e*127)}K(ow,"encodeAxisToInt8");function aw(r){return r/127}K(aw,"decodeInt8ToAxis");function Pu(r){return r===0?0:Math.ceil(r/8)}K(Pu,"getButtonByteCount");function lw(r,e){let t=r,n=Pu(e);return 8+t+n+4}K(lw,"getCompressedPacketSize");var uw=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}}};K(uw,"MacroEventDecoder");var LS=uw;Wr();function cw(r,e){let t=e.getAllAxes().length,n=e.getAllButtons().length,i=Pu(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=sw();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=aw(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,a+=1,a<r.length){let c=r[a];a+=1;let d=new TextDecoder;l.textInputs=[];for(let h=0;h<c&&a<r.length;h++){let f=r[a];if(a+=1,a+f<=r.length){let p=r.slice(a,a+f),g=d.decode(p);l.textInputs.push(g),a+=f}}}if(a<r.length){let c=r[a];a+=1;let d=new LS,h=[],f=ne.from(r);for(let p=0;p<c&&a<r.length;p++){let g=d.decode(f,a);h.push(g.event),a+=g.bytesRead}l.macroEvents=h}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 g=(r[a]&1)!==0;a+=1,l.touchPositions.push({id:h,x:f,y:p,over:g})}}return l}K(cw,"decodeCompressedInput");var dw=class{constructor(e,t){F(this,"enabled",!1),F(this,"currentStats",null),F(this,"_userId"),F(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}};K(dw,"UserStats");var _S=dw,hw=class{constructor(e,t,n){this.id=e,this.name=t,F(this,"displays",[]),F(this,"layers",[]),F(this,"spriteRegistry"),F(this,"mode"),F(this,"axes",new Map),F(this,"buttons",new Map),F(this,"textInputs",[]),F(this,"mouseX",0),F(this,"mouseY",0),F(this,"mouseOver",!1),F(this,"mouseDisplayId",0),F(this,"touchPositions",new Map),F(this,"activeTouchId",null),F(this,"inputBindings",new FS),F(this,"stats"),F(this,"soundCommands",[]),F(this,"nextSoundInstanceId",1),F(this,"audioConfigCommands",[]),F(this,"lastListenerX",-1),F(this,"lastListenerY",-1),F(this,"pendingSendSounds",!1),F(this,"audioProcessor"),F(this,"loadedSounds",new Map),F(this,"soundLoadErrors",new Map),F(this,"playingSounds",new Map),F(this,"mobileVibrationCommands",[]),F(this,"mobileVibrationProcessor"),F(this,"gamepadVibrationCommands",[]),F(this,"gamepadVibrationProcessor"),F(this,"macroRegistry",new MS),F(this,"macroEngine",new BS),F(this,"macroEventHandlers",new Map),F(this,"postProcessCommands",[]),F(this,"currentPostProcessConfig",null),F(this,"bridgeMessages",[]),F(this,"totalBytesSent",0),F(this,"totalBytesReceived",0),F(this,"bytesSentPerTick",[]),F(this,"bytesReceivedPerTick",[]),F(this,"bytesTickIndex",0),F(this,"bytesTickRate",20),F(this,"currentTickBytesSent",0),F(this,"currentTickBytesReceived",0),F(this,"availableViewports",new Map),F(this,"data"),F(this,"currentScalingModes",new Map),F(this,"currentCellSizes",new Map),F(this,"currentGridConfigs",new Map),F(this,"currentPaletteSlotIds",new Map),this.mode=n,this.stats=new _S(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){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;e.setId(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 xS(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=n}n.setOrigin(new Ht(t.originX,t.originY)),n.setSize(new Ht(t.sizeX,t.sizeY)),n.setRenderPasses(t.renderPasses)}}updateLayersFromPacket(e){for(let t of e){let n=this.findLayerById(t.id);n||(n=new ES(new Ht(t.originX,t.originY),t.zIndex,t.width,t.height,{isStatic:!1,charCodeMode:t.is16bit?"16bit":"8bit"}),n.setId(t.id),n.setMode(this.mode),this.spriteRegistry&&n.setSpriteRegistry(this.spriteRegistry),this.addLayer(n)),t.updateFlags&1&&n.setOrigin(new Ht(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}`);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=cw(e,this.inputBindings),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];this.setButton(u.name,l)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId;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}=(w1(),Xo(v1)),{MobileVibrateFlags:n,GamepadVibrateFlags:i}=(C1(),Xo(b1));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}=(k1(),Xo(x1)),{PlaySoundFlags:i}=(M1(),Xo(E1));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:Gs.color,lineWidth:Gs.lineWidth}:n={enabled:t.enabled,color:t.color??Gs.color,lineWidth:t.lineWidth??Gs.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())}}};K(hw,"User");var $S=hw;vo();vo();Wr();var fw=class{constructor(){F(this,"charCodeSize",Hf)}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.encodeClearOrder(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=ne.allocUnsafe(_v+(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=ne.allocUnsafe($v+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=ne.allocUnsafe(Nv+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=ne.allocUnsafe(Wv+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=ne.allocUnsafe(Hv+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=ne.allocUnsafe(Vv+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=ne.allocUnsafe(jv+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=ne.allocUnsafe(Yv),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=ne.allocUnsafe(Gv),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=ne.allocUnsafe(Xv+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=ne.allocUnsafe(Zv+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=ne.allocUnsafe(Kv+(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=ne.allocUnsafe(qv+(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=ne.allocUnsafe(Qv+(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=ne.allocUnsafe(Jv+(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=ne.allocUnsafe(e1+(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=ne.allocUnsafe(t1+(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=ne.allocUnsafe(r1+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=ne.allocUnsafe(n1+(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=ne.allocUnsafe(i1+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=ne.allocUnsafe(s1+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=ne.allocUnsafe(o1+(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=ne.allocUnsafe(a1+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=ne.allocUnsafe(l1+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=ne.allocUnsafe(u1+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=ne.allocUnsafe(c1+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()}encodeClearOrder(e,t){let n=ne.allocUnsafe(d1+(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=ne.allocUnsafe(h1+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=ne.allocUnsafe(f1),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=ne.allocUnsafe(p1),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.spriteIndex,n++),t.toUint8Array()}};K(fw,"OrderEncoder");var NS=fw;Wr();var om=255,am=64,pw=class{constructor(){F(this,"orderEncoder"),this.orderEncoder=new NS}encode(e){let t=e.is16bit;if(e.orders.length>om)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${om}. 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=ne.allocUnsafe(o),l=0;a.writeUInt16BE(e.id,l),l+=2;let u=e.updateFlags;t?u|=am:u&=~am,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)ne.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)}};K(pw,"LayerEncoder");var WS=pw;Wr();vo();var gw=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 sh;case 8:return oh;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),n=ne.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=ne.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=g1;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=m1,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=ne.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=ne.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=ne.allocUnsafe(sh),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=ne.allocUnsafe(oh),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=ne.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}};K(gw,"AudioOrderEncoder");var HS=gw;Wr();var mw=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=ne.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=ne.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=ne.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=ne.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()}};K(mw,"VibrationOrderEncoder");var VS=mw;Wr();var yw=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=ne.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=ne.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=ne.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};K(yw,"MacroOrderEncoder");var jS=yw;Wr();vo();var vw=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 ah;case 3:return lh;case 4:return uh;case 5:return ch;case 6:return dh;case 7:return hh;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),n=ne.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=y1;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=ne.allocUnsafe(ah),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=ne.allocUnsafe(lh),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=ne.allocUnsafe(uh),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.mode,n++),t.toUint8Array()}encodeSetGridOrder(e){let t=ne.allocUnsafe(ch),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=ne.allocUnsafe(dh),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.slotId,n++),t.toUint8Array()}encodeSetCellSizeOrder(e){let t=ne.allocUnsafe(hh),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()}};K(vw,"PostProcessOrderEncoder");var YS=vw;Wr();var lm=4,Zc=4,um=8,ww=class{encode(e){var o;let t=((o=e.renderPasses)==null?void 0:o.length)??0;if(t>Zc)throw new Error(`renderPasses supports up to ${Zc} entries, got ${t}`);let n=um+t*lm,i=ne.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,Zc);return um+t*lm}};K(ww,"DisplayEncoder");var GS=ww;Wr();var bw=class{constructor(){F(this,"layerEncoder"),F(this,"audioOrderEncoder"),F(this,"vibrationOrderEncoder"),F(this,"macroOrderEncoder"),F(this,"postProcessOrderEncoder"),F(this,"displayEncoder"),this.layerEncoder=new WS,this.audioOrderEncoder=new HS,this.vibrationOrderEncoder=new VS,this.macroOrderEncoder=new jS,this.postProcessOrderEncoder=new YS,this.displayEncoder=new GS}encode(e){let t=e.layers.map(R=>this.layerEncoder.encode(R)),n=e.audioOrders||[],i=n.map(R=>this.audioOrderEncoder.encode(R)),s=e.vibrationOrders||[],o=s.map(R=>this.vibrationOrderEncoder.encode(R)),a=e.macroOrders||[],l=a.map(R=>this.macroOrderEncoder.encode(R)),u=e.postProcessOrders||[],c=u.map(R=>this.postProcessOrderEncoder.encode(R)),d=9,h=e.displays.reduce((R,O)=>R+this.displayEncoder.calculateSize(O),0),f=2,p=t.reduce((R,O)=>R+O.length,0),g=1,C=i.reduce((R,O)=>R+O.length,0),y=1,m=o.reduce((R,O)=>R+O.length,0),v=1,b=l.reduce((R,O)=>R+O.length,0),S=1,I=c.reduce((R,O)=>R+O.length,0),E=d+h+f+p+g+C+y+m+v+b+S+I,U=ne.allocUnsafe(E),z=0,B=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);U.writeBigUInt64BE(B,z),z+=8,U.writeUInt8(e.displays.length,z),z+=1;for(let R of e.displays){let O=this.displayEncoder.encode(R);ne.from(O).copy(U,z),z+=O.length}U.writeUInt16BE(e.layers.length,z),z+=2;for(let R of t)ne.from(R).copy(U,z),z+=R.length;U.writeUInt8(n.length,z),z+=1;for(let R of i)ne.from(R).copy(U,z),z+=R.length;U.writeUInt8(s.length,z),z+=1;for(let R of o)ne.from(R).copy(U,z),z+=R.length;U.writeUInt8(a.length,z),z+=1;for(let R of l)ne.from(R).copy(U,z),z+=R.length;U.writeUInt8(u.length,z),z+=1;for(let R of c)ne.from(R).copy(U,z),z+=R.length;return U.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=ne.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()}};K(bw,"UpdatePacketEncoder");var XS=bw,ZS=(r=>(r[r.ColorPalette=1]="ColorPalette",r[r.Sprite=2]="Sprite",r[r.MulticolorSprite=3]="MulticolorSprite",r[r.BitmapFont=4]="BitmapFont",r[r.Sound=5]="Sound",r[r.WebFont=6]="WebFont",r[r.Macro=7]="Macro",r[r.ImageFont=8]="ImageFont",r))(ZS||{});Wr();var Cw=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=ne.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}};K(Cw,"MacroLoadEncoder");var KS=Cw;Wr();var xw=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 4:return this.encodeBitmapFont(e);case 5:return this.encodeSound(e);case 6:return this.encodeWebFont(e);case 8:return this.encodeImageFont(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=ne.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,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=ne.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=ne.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()}encodeBitmapFont(e){let t=e.characters.length;if(t>255)throw new Error(`Character count ${t} exceeds maximum of 255`);let n=Math.ceil(e.width*e.height/8),i=7+t*(1+n),s=ne.allocUnsafe(i),o=0;s.writeUInt8(4,o++),s.writeUInt8(e.fontId,o++),s.writeUInt8(e.width,o++),s.writeUInt8(e.height,o++),s.writeUInt8(e.cellWidth,o++),s.writeUInt8(e.cellHeight,o++),s.writeUInt8(t,o++);for(let a of e.characters){if(a.bitmap.length!==n)throw new Error(`Character ${a.charCode}: bitmap size ${a.bitmap.length} does not match expected ${n} bytes`);s.writeUInt8(a.charCode,o++);for(let l=0;l<a.bitmap.length;l++)s.writeUInt8(a.bitmap[l],o++)}return s.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=ne.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()}encodeWebFont(e){let t=new TextEncoder,n=t.encode(e.fontFamily),i=e.fontWeight?t.encode(e.fontWeight):new Uint8Array(0),s=e.fontStyle?t.encode(e.fontStyle):new Uint8Array(0),o=0;e.offsetX!==void 0&&(o|=1),e.offsetY!==void 0&&(o|=2),e.charSpacing!==void 0&&(o|=4),e.lineHeight!==void 0&&(o|=8),e.fontWeight!==void 0&&(o|=16),e.fontStyle!==void 0&&(o|=32);let a=4;a+=n.length,a+=2,e.offsetX!==void 0&&(a+=2),e.offsetY!==void 0&&(a+=2),e.charSpacing!==void 0&&(a+=2),e.lineHeight!==void 0&&(a+=2),e.fontWeight!==void 0&&(a+=1+i.length),e.fontStyle!==void 0&&(a+=1+s.length);let l=ne.allocUnsafe(a),u=0;l.writeUInt8(6,u++),l.writeUInt8(e.fontId,u++),l.writeUInt8(o,u++),l.writeUInt8(n.length,u++);for(let c=0;c<n.length;c++)l.writeUInt8(n[c],u++);if(l.writeUInt16BE(e.fontSize,u),u+=2,e.offsetX!==void 0&&(l.writeInt16BE(e.offsetX,u),u+=2),e.offsetY!==void 0&&(l.writeInt16BE(e.offsetY,u),u+=2),e.charSpacing!==void 0&&(l.writeInt16BE(e.charSpacing,u),u+=2),e.lineHeight!==void 0&&(l.writeUInt16BE(Math.round(e.lineHeight*100),u),u+=2),e.fontWeight!==void 0){l.writeUInt8(i.length,u++);for(let c=0;c<i.length;c++)l.writeUInt8(i[c],u++)}if(e.fontStyle!==void 0){l.writeUInt8(s.length,u++);for(let c=0;c<s.length;c++)l.writeUInt8(s[c],u++)}return l.toUint8Array()}encodeImageFont(e){if(![1,4,16].includes(e.atlasBlocks))throw new Error(`Invalid atlasBlocks: ${e.atlasBlocks}. Must be 1, 4, or 16.`);if(e.imageData.length>16*1024*1024)throw new Error(`Image data size ${e.imageData.length} exceeds maximum of 16MB`);let t=11+e.imageData.length,n=ne.allocUnsafe(t),i=0;n.writeUInt8(8,i++),n.writeUInt8(e.fontId,i++),n.writeUInt8(e.glyphWidth,i++),n.writeUInt8(e.glyphHeight,i++),n.writeUInt8(e.cellWidth,i++),n.writeUInt8(e.cellHeight,i++),n.writeUInt8(e.atlasBlocks,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()}};K(xw,"LoadEncoder");var Us=xw;Wr();var Iw=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}}};K(Iw,"MacroLoadDecoder");var qS=Iw,Sw=class{decode(e,t=0){let n=ne.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 4:return this.decodeBitmapFont(n,t);case 5:return this.decodeSound(n,t);case 6:return this.decodeWebFont(n,t);case 7:return this.decodeMacro(n,t);case 8:return this.decodeImageFont(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,d=c*3;this.checkSize(e,t,d,`MulticolorSprite ${o} data`);let h=[];for(let f=0;f<c;f++)h.push({charCode:e.readUInt8(t++),fgColorId:e.readUInt8(t++),bgColorId:e.readUInt8(t++)});s.push({spriteId:a,sizeX:l,sizeY:u,data:h})}return{load:{loadType:3,sprites:s},bytesRead:t-n}}decodeBitmapFont(e,t){let n=t;this.checkSize(e,t,7,"BitmapFont 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++),u=e.readUInt8(t++),c=Math.ceil(s*o/8),d=[];for(let h=0;h<u;h++){this.checkSize(e,t,1+c,`BitmapFont character ${h}`);let f=e.readUInt8(t++),p=new Uint8Array(c);for(let g=0;g<c;g++)p[g]=e.readUInt8(t++);d.push({charCode:f,bitmap:p})}return{load:{loadType:4,fontId:i,width:s,height:o,cellWidth:a,cellHeight:l,characters:d},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`)}decodeWebFont(e,t){let n=t,i=new TextDecoder;this.checkSize(e,t,5,"WebFont header"),e.readUInt8(t++);let s=e.readUInt8(t++),o=e.readUInt8(t++),a=e.readUInt8(t++);this.checkSize(e,t,a,"WebFont family string");let l=new Uint8Array(a);for(let h=0;h<a;h++)l[h]=e.readUInt8(t++);let u=i.decode(l);this.checkSize(e,t,2,"WebFont fontSize");let c=e.readUInt16BE(t);t+=2;let d={loadType:6,fontId:s,fontFamily:u,fontSize:c};if(o&1&&(this.checkSize(e,t,2,"WebFont offsetX"),d.offsetX=e.readInt16BE(t),t+=2),o&2&&(this.checkSize(e,t,2,"WebFont offsetY"),d.offsetY=e.readInt16BE(t),t+=2),o&4&&(this.checkSize(e,t,2,"WebFont charSpacing"),d.charSpacing=e.readInt16BE(t),t+=2),o&8){this.checkSize(e,t,2,"WebFont lineHeight");let h=e.readUInt16BE(t);d.lineHeight=h/100,t+=2}if(o&16){this.checkSize(e,t,1,"WebFont weight length");let h=e.readUInt8(t++);this.checkSize(e,t,h,"WebFont weight string");let f=new Uint8Array(h);for(let p=0;p<h;p++)f[p]=e.readUInt8(t++);d.fontWeight=i.decode(f)}if(o&32){this.checkSize(e,t,1,"WebFont style length");let h=e.readUInt8(t++);this.checkSize(e,t,h,"WebFont style string");let f=new Uint8Array(h);for(let p=0;p<h;p++)f[p]=e.readUInt8(t++);d.fontStyle=i.decode(f)}return{load:d,bytesRead:t-n}}decodeMacro(e,t){return new qS().decode(e,t)}decodeImageFont(e,t){let n=t;this.checkSize(e,t,7,"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++),u=e.readUInt8(t++);if(![1,4,16].includes(u))throw new Error(`Invalid atlasBlocks value: ${u}. Must be 1, 4, or 16.`);let c=u;this.checkSize(e,t,4,"ImageFont image data size");let d=e.readUInt32LE(t);t+=4,this.checkSize(e,t,d,"ImageFont image data");let h=new Uint8Array(d);for(let f=0;f<d;f++)h[f]=e.readUInt8(t++);return{load:{loadType:8,fontId:i,glyphWidth:s,glyphHeight:o,cellWidth:a,cellHeight:l,atlasBlocks:c,imageData:h},bytesRead:t-n}}};K(Sw,"LoadDecoder");var QS=Sw,Ch=class zs{constructor(e){this.engine=e,F(this,"colorCache",new Array(256)),F(this,"cellsBuffer",[]),F(this,"opacityBuffer",new Uint8Array(0)),F(this,"visibleLayersBuffer",[]),F(this,"visibleLayerIdsBuffer",[]),F(this,"passCellsBuffers",[]),F(this,"passOpacityBuffers",[]),this.rebuildColorCache()}static getChar(e){let t=zs.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),zs.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 g=o[p],C=h-g.getOrigin().x,y=f-g.getOrigin().y,m=g.getWidth(),v=g.getHeight();if(C<0||C>=m||y<0||y>=v)continue;let b=y*m+C,S=g.getData(),I=S.getCharCode(b),E=S.getFgColorCode(b),U=S.getBgColorCode(b),z=i[d];if(I!==0&&z.char===" "&&(z.char=zs.getChar(I)),E!==255&&z.fgColorIndex===255&&(z.fgColorIndex=E,z.fgEmission=this.getColorEmission(E)),U!==255){z.bgColorIndex===255&&(z.bgColorIndex=U,z.bgEmission=this.getColorEmission(U)),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 C=0;C<s.length;C++){let y=s[C],m=y.getZOrder();m<d.zMin||m>d.zMax||p.push(y)}let g=this.visibleLayerIdsBuffer.length;for(let C=0;C<p.length;C++)this.visibleLayerIdsBuffer[g+C]=p[C].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=0;h<n.length;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,g=d-f.getOrigin().y,C=f.getWidth(),y=f.getHeight();if(p<0||p>=C||g<0||g>=y)continue;let m=g*C+p,v=f.getData(),b=v.getCharCode(m),S=v.getFgColorCode(m),I=v.getBgColorCode(m),E=n[u];if(b!==0&&E.char===" "&&(E.char=zs.getChar(b)),S!==255&&E.fgColorIndex===255&&(E.fgColorIndex=S,E.fgEmission=this.getColorEmission(S)),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],g=d-p.getOrigin().x,C=h-p.getOrigin().y,y=p.getWidth(),m=p.getHeight();if(g<0||g>=y||C<0||C>=m)continue;let v=C*y+g,b=p.getData(),S=b.getCharCode(v),I=b.getFgColorCode(v),E=b.getBgColorCode(v),U=i[c];if(S!==0&&U.char===" "&&(U.char=zs.getChar(S)),I!==255&&U.fgColorIndex===255&&(U.fgColorIndex=I,U.fgEmission=this.getColorEmission(I)),E!==255){U.bgColorIndex===255&&(U.bgColorIndex=E,U.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}}}};K(Ch,"DisplayRasterizer"),F(Ch,"charCache",(()=>{let r=new Map;for(let e=0;e<256;e++)r.set(e,String.fromCharCode(e));return r})());var JS=Ch,kw=class{constructor(){F(this,"enabled",!1),F(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,isStatic: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}};K(kw,"CoreStats");var ek=kw,Ew=class{constructor(){F(this,"unicolorSprites",new Map),F(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){for(let t of e.sprites){let n=new IS(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){for(let t of e.sprites){let n=new H1(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}};K(Ew,"SpriteRegistry");var tk=Ew,rk=(r=>(r.Web="web",r.Bitmap="bitmap",r.Image="image",r))(rk||{});function jf(r){return Math.sqrt(r)*16}K(jf,"getAtlasColumns");function Mw(r){return r*256-1}K(Mw,"getMaxCharCode");function nk(r,e){let t=jf(r)*e;return{width:t,height:t}}K(nk,"getAtlasDimensions");var Tw=class{constructor(e,t){this.fontId=e,this.config=t}getFontId(){return this.fontId}getConfig(){return{...this.config}}getFontFamily(){return this.config.fontFamily}getFontSize(){return this.config.fontSize}getOffsetX(){return this.config.offsetX??0}getOffsetY(){return this.config.offsetY??0}getCharSpacing(){return this.config.charSpacing??0}getLineHeight(){return this.config.lineHeight??1.2}getFontWeight(){return this.config.fontWeight??"normal"}getFontStyle(){return this.config.fontStyle??"normal"}toCSS(){let e=[];e.push(`font-family: ${this.config.fontFamily}`),e.push(`font-size: ${this.config.fontSize}px`);let t=this.config.fontWeight??"normal";t!=="normal"&&e.push(`font-weight: ${t}`);let n=this.config.fontStyle??"normal";return n!=="normal"&&e.push(`font-style: ${n}`),e.join("; ")+";"}};K(Tw,"WebFont");var Uw=Tw,Aw=class{constructor(e,t){this.fontId=e,this.config=t}getFontId(){return this.fontId}getConfig(){return{charWidth:this.config.charWidth,charHeight:this.config.charHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,glyphs:new Map(this.config.glyphs)}}getCharWidth(){return this.config.charWidth}getCharHeight(){return this.config.charHeight}getCellWidth(){return this.config.cellWidth??this.config.charWidth}getCellHeight(){return this.config.cellHeight??this.config.charHeight}getGlyph(e){return this.config.glyphs.get(e)}hasGlyph(e){return this.config.glyphs.has(e)}getGlyphCount(){return this.config.glyphs.size}getCharCodes(){return Array.from(this.config.glyphs.keys())}};K(Aw,"BitmapFont");var ik=Aw,Rw=class{constructor(e,t){this.fontId=e,this.config=t,F(this,"atlasColumns"),F(this,"maxCharCode"),this.atlasColumns=jf(t.atlasBlocks),this.maxCharCode=Mw(t.atlasBlocks)}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,imageData:this.config.imageData}}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}getImageData(){return this.config.imageData}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}};K(Rw,"ImageFont");var cm=Rw,Pw=class{constructor(){F(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`WebFont with ID ${e} already exists`);let n=new Uw(e,t);this.fonts.set(e,n)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};K(Pw,"WebFontRegistry");var sk=Pw,zw=class{constructor(){F(this,"fonts",new Map)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`BitmapFont with ID ${e} already exists`);let n=new ik(e,t);this.fonts.set(e,n)}getFont(e){return this.fonts.get(e)}hasFont(e){return this.fonts.has(e)}unloadFont(e){return this.fonts.delete(e)}clearFonts(){this.fonts.clear()}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};K(zw,"BitmapFontRegistry");var ok=zw,Dw=class{constructor(){F(this,"fonts",new Map),F(this,"nameToId",new Map),F(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,n){if(this.nameToId.has(e))throw new Error(`ImageFont with name "${e}" already exists`);let i=this.allocateId(e),s={glyphWidth:t.glyphWidth,glyphHeight:t.glyphHeight,cellWidth:t.cellWidth,cellHeight:t.cellHeight,atlasBlocks:t.atlasBlocks??1,imageData:n},o=new cm(i,s);return this.fonts.set(i,o),this.nameToId.set(e,i),i}loadFont(e,t){if(this.fonts.has(e))throw new Error(`ImageFont with ID ${e} already exists`);let n=new cm(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}};K(Dw,"ImageFontRegistry");var ak=Dw,Ow=class{constructor(){F(this,"sounds",new Map),F(this,"nameToId",new Map),F(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`)}};K(Ow,"SoundRegistry");var lk=Ow,Bw=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)}};K(Bw,"AudioOrderCollector");var uk=Bw,Fw=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}}};K(Fw,"VibrationOrderCollector");var ck=Fw,Lw=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:Lv(t)}}createSetGridOrder(e,t){let{r:n,g:i,b:s,a:o}=this.parseColor(t.color??Gs.color);return{type:5,displayId:e,enabled:t.enabled,colorR:n,colorG:i,colorB:s,colorA:o,lineWidth:t.lineWidth??Gs.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}}};K(Lw,"PostProcessOrderCollector");var Yf=Lw,xh=class zl{constructor(e={}){F(this,"users",new Map),F(this,"mode"),F(this,"maxUsers"),F(this,"strictMode"),F(this,"currentTick",0),F(this,"encoder"),F(this,"displayRasterizer"),F(this,"colorPalette",new Map),F(this,"stats",new ek),F(this,"spriteRegistry",new tk),F(this,"webFontRegistry",new sk),F(this,"bitmapFontRegistry",new ok),F(this,"imageFontRegistry",new ak),F(this,"soundRegistry",new lk),F(this,"audioOrderCollector"),F(this,"vibrationOrderCollector"),F(this,"postProcessOrderCollector"),F(this,"activeWebFontId",0),F(this,"_renderCallCount",0),F(this,"paletteSlots",new Map),F(this,"onPaletteChangedCallback"),F(this,"onBitmapFontChangedCallback"),F(this,"onImageFontChangedCallback"),this.mode=e.mode??"server",this.maxUsers=e.maxUsers??64,this.strictMode=e.strictMode??!1,this.encoder=new XS,this.displayRasterizer=new JS(this),this.audioOrderCollector=new uk(this.soundRegistry),this.vibrationOrderCollector=new ck,this.postProcessOrderCollector=new Yf,this.initializeDefaultPalette(),this.displayRasterizer.rebuildColorCache(),this.loadDefaultWebFont()}initializeDefaultPalette(){zl.ANSI_VGA_COLORS.forEach(e=>{this.colorPalette.set(e.colorId,{r:e.r,g:e.g,b:e.b,a:e.a,e:e.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0})}getMode(){return this.mode}getMaxUsers(){return this.maxUsers}isStrictMode(){return this.strictMode}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 $S(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}onBitmapFontChanged(e){this.onBitmapFontChangedCallback=e}getColor(e){return this.colorPalette.get(e)??null}loadPalette(e){for(let t of e)t.colorId<0||t.colorId>255||this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e??0});zl.ANSI_VGA_COLORS.forEach(t=>{this.colorPalette.set(t.colorId,{r:t.r,g:t.g,b:t.b,a:t.a,e:t.e})}),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0}),this.displayRasterizer.rebuildColorCache(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}getPalette(){return new Map(this.colorPalette)}resetPalette(){this.colorPalette.clear(),this.initializeDefaultPalette(),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,e:i.e??0});zl.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(y=>{let m=y.getOrigin(),v=y.getSize();return{id:y.getId(),originX:m.x,originY:m.y,sizeX:v.x,sizeY:v.y,renderPasses:y.getRenderPasses()}});a.forEach(y=>y.resetChangeTracking());let u=[],c=[];o.forEach((y,m)=>{if(!y.getNeedsCommit())return;let v=y.getOrigin(),b=y.getOrders(),S=y.getStatic(),I=y.calculateUpdateFlags();y.resetChangeTracking(),y.resetCommit(),y.getId()===0&&y.setId(m);let E={id:y.getId(),updateFlags:I,zIndex:y.getZOrder(),originX:v.x,originY:v.y,width:y.getWidth(),height:y.getHeight(),is16bit:y.getCharCodeMode()==="16bit",orderCount:b.length,orders:b};b.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(y.getId(),S,b.length,I),S?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(),g=null,C=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(s,l.length,u.length,c.length),u.length>0&&(g=this.encoder.encode({tick:this.currentTick,displayCount:l.length,displays:l,layerCount:u.length,layers:u,audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})),C=this.encoder.encode({tick:this.currentTick,displayCount:l.length,displays:l,layerCount:c.length,layers:c,audioOrderCount:d.length,audioOrders:d,vibrationOrderCount:h.length,vibrationOrders:h,macroOrderCount:p.length,macroOrders:p,postProcessOrderCount:f.length,postProcessOrders:f}),e.set(s,{static:g,dynamic:C}),i.getStats().isEnabled()){let y=a.reduce((S,I)=>{let E=I.getSize();return S+E.x*E.y},0);i.getStats().recordDisplays(a.length,y),i.getStats().recordLayers(o.length,u.length+c.length,u.length,c.length),[...u,...c].forEach(S=>{i.getStats().recordLayerOrders(S.id,S.orders.length)});let m=(g==null?void 0:g.length)||0,v=(C==null?void 0:C.length)||0;i.getStats().recordPacketSizes(m,v);let b=i.getInputBindingRegistry();i.getStats().recordInput(!1,b.getAxisCount(),b.getButtonCount()),i.getStats().endTick()}if(i.endTickBytes(),this.stats.isEnabled()){let y=[...u,...c];y.forEach((I,E)=>{this.stats.recordLayerOrders(E,I.orders)}),a.forEach((I,E)=>{this.stats.recordDisplayLayers(E,y.length)});let m=((g==null?void 0:g.length)||0)+((C==null?void 0:C.length)||0),v=l.reduce((I,E)=>{var z;let U=Math.min(((z=E.renderPasses)==null?void 0:z.length)??0,4);return I+8+U*4},0),b=y.length*20,S=m-v-b;this.stats.recordUpdatePacketSize(m,v,b,S>0?S: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&&a.setId(l),{id:a.getId(),updateFlags:7,zIndex:a.getZOrder(),originX:u.x,originY:u.y,width:a.getWidth(),height:a.getHeight(),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{UpdatePacketDecoder:n}=($1(),Xo(L1)),i=new n().decode(t);return this.applyUpdatePacket(e,i)?i:null}applyLoadPacket(e){try{let t=new QS().decode(e).load;switch(t.loadType){case 1:t.slotId!==void 0?this.loadPaletteToSlot(t.slotId,t.colors):this.loadPalette(t.colors);break;case 2:this.loadUnicolorSprites(t);break;case 3:this.loadMulticolorSprites(t);break;case 4:{let n=this.getBitmapFontRegistry();n.hasFont(t.fontId)&&n.unloadFont(t.fontId),n.loadFont(t.fontId,{charWidth:t.width,charHeight:t.height,cellWidth:t.cellWidth,cellHeight:t.cellHeight,glyphs:new Map(t.characters.map(i=>[i.charCode,i.bitmap]))});break}case 6:{let n=this.getWebFontRegistry();n.hasFont(t.fontId)&&n.unloadFont(t.fontId),this.loadWebFontById(t.fontId,{fontFamily:t.fontFamily,fontSize:t.fontSize,offsetX:t.offsetX,offsetY:t.offsetY,charSpacing:t.charSpacing,lineHeight:t.lineHeight,fontWeight:t.fontWeight,fontStyle:t.fontStyle});break}case 5:console.warn("[Core] Sound loading not yet implemented");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}}generatePaletteLoadPacket(){let e=this.getPalette();if(e.size===0)return null;let t=new Us,n=[];return e.forEach((i,s)=>{s!==255&&n.push({colorId:s,r:i.r,g:i.g,b:i.b,a:i.a,e:i.e})}),t.encode({loadType:1,colors:n})}generatePaletteSlotLoadPacket(e){let t=this.getPaletteFromSlot(e);if(!t||t.size===0)return null;let n=new Us,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(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let i=e.getUnicolorSprite(n);if(i){let s=[];for(let o=0;o<i.sizeX*i.sizeY;o++)s.push(i.data.get(o));t.push({spriteId:i.id,sizeX:i.sizeX,sizeY:i.sizeY,data:s})}}return t.length===0?null:new Us().encode({loadType:2,sprites:t})}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 Us().encode({loadType:3,sprites:t})}generateWebFontsLoadPackets(){let e=this.getWebFontRegistry(),t=e.getFontIds(),n=[],i=new Us;for(let s of t){let o=e.getFont(s);if(o){let a=o.getConfig(),l=i.encode({loadType:6,fontId:s,fontFamily:a.fontFamily,fontSize:a.fontSize,offsetX:a.offsetX,offsetY:a.offsetY,charSpacing:a.charSpacing,lineHeight:a.lineHeight,fontWeight:a.fontWeight,fontStyle:a.fontStyle});n.push(l)}}return n}generateBitmapFontsLoadPackets(){let e=this.getBitmapFontRegistry(),t=e.getFontIds(),n=[],i=new Us;for(let s of t){let o=e.getFont(s);if(o){let a=[];for(let l=0;l<256;l++){let u=o.getGlyph(l);u&&a.push({charCode:l,bitmap:u})}if(a.length>0){let l=i.encode({loadType:4,fontId:s,width:o.getCharWidth(),height:o.getCharHeight(),cellWidth:o.getCellWidth(),cellHeight:o.getCellHeight(),characters:a});n.push(l)}}}return n}generateAllLoadPackets(){let e=[],t=this.generatePaletteLoadPacket();t&&e.push(t);let n=this.generateAllPaletteSlotLoadPackets();e.push(...n);let i=this.generateUnicolorSpritesLoadPacket();i&&e.push(i);let s=this.generateMulticolorSpritesLoadPacket();s&&e.push(s);let o=this.generateWebFontsLoadPackets();e.push(...o);let a=this.generateBitmapFontsLoadPackets();return e.push(...a),e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let n=t.getMacroLoads();if(n.length===0)return[];let i=new KS;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)}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.loadSoundData(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 loadSoundData(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 sound "${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 sound "${e}": ${p}`)}let a=typeof dl<"u"?dl: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()}loadDefaultWebFont(){this.webFontRegistry.loadFont(0,{fontFamily:"Courier New",fontSize:16,offsetX:0,offsetY:0,charSpacing:0,lineHeight:1,fontWeight:"normal",fontStyle:"normal"}),this.activeWebFontId=0}loadWebFont(e){let t=e.getFontId(),n=e.getConfig();this.webFontRegistry.loadFont(t,n)}getWebFont(e){return this.webFontRegistry.getFont(e)??null}hasWebFont(e){return this.webFontRegistry.hasFont(e)}unloadWebFont(e){if(e===0)throw new Error("Cannot unload default font (fontId 0)");return this.webFontRegistry.unloadFont(e)}clearWebFonts(){this.webFontRegistry.clearFonts(),this.loadDefaultWebFont()}setActiveWebFont(e){if(!this.webFontRegistry.hasFont(e))throw new Error(`WebFont with ID ${e} does not exist`);this.activeWebFontId=e}getActiveWebFontId(){return this.activeWebFontId}getActiveWebFont(){let e=this.webFontRegistry.getFont(this.activeWebFontId);if(!e)throw new Error(`Active WebFont ${this.activeWebFontId} not found. This should not happen.`);return e}getWebFontCount(){return this.webFontRegistry.getFontCount()}getWebFontIds(){return this.webFontRegistry.getFontIds()}getWebFontRegistry(){return this.webFontRegistry}getBitmapFontRegistry(){return this.bitmapFontRegistry}loadWebFontById(e,t){let n=new Uw(e,t);this.loadWebFont(n)}loadBitmapFontById(e,t){this.bitmapFontRegistry.loadFont(e,t),this.onBitmapFontChangedCallback&&this.onBitmapFontChangedCallback(e)}getBitmapFont(e){return this.bitmapFontRegistry.getFont(e)??null}hasBitmapFont(e){return this.bitmapFontRegistry.hasFont(e)}unloadBitmapFont(e){return this.bitmapFontRegistry.unloadFont(e)}clearBitmapFonts(){this.bitmapFontRegistry.clearFonts()}getBitmapFontCount(){return this.bitmapFontRegistry.getFontCount()}getBitmapFontIds(){return this.bitmapFontRegistry.getFontIds()}async loadImageFont(e,t,n){let i=await this.loadImageData(t),s=this.imageFontRegistry.registerFont(e,n,i);return this.onImageFontChangedCallback&&this.onImageFontChangedCallback(s),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 dl<"u"?dl: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}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()}};K(xh,"Core"),F(xh,"ANSI_VGA_COLORS",[{colorId:240,r:16,g:16,b:16,a:255,e:0},{colorId:241,r:128,g:128,b:128,a:255,e:0},{colorId:242,r:192,g:192,b:192,a:255,e:0},{colorId:243,r:240,g:240,b:240,a:255,e:0},{colorId:244,r:200,g:50,b:50,a:255,e:0},{colorId:245,r:50,g:200,b:50,a:255,e:0},{colorId:246,r:220,g:180,b:50,a:255,e:0},{colorId:247,r:50,g:100,b:220,a:255,e:0},{colorId:248,r:50,g:200,b:200,a:255,e:0},{colorId:249,r:200,g:50,b:200,a:255,e:0},{colorId:250,r:220,g:120,b:50,a:255,e:0},{colorId:251,r:120,g:220,b:120,a:255,e:0},{colorId:252,r:120,g:180,b:220,a:255,e:0},{colorId:253,r:220,g:150,b:200,a:255,e:0},{colorId:254,r:250,g:220,b:150,a:255,e:0}]);var _w=xh,_a=new Map([[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])],[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])],[179,new Uint8Array([24,24,24,24,24,24,24,24])],[196,new Uint8Array([0,0,0,255,0,0,0,0])],[218,new Uint8Array([0,0,0,31,24,24,24,24])],[191,new Uint8Array([0,0,0,248,24,24,24,24])],[192,new Uint8Array([24,24,24,31,0,0,0,0])],[217,new Uint8Array([24,24,24,248,0,0,0,0])],[195,new Uint8Array([24,24,24,31,24,24,24,24])],[180,new Uint8Array([24,24,24,248,24,24,24,24])],[194,new Uint8Array([0,0,0,255,24,24,24,24])],[193,new Uint8Array([24,24,24,255,0,0,0,0])],[197,new Uint8Array([24,24,24,255,24,24,24,24])],[186,new Uint8Array([54,54,54,54,54,54,54,54])],[205,new Uint8Array([0,0,0,255,0,255,0,0])],[201,new Uint8Array([0,0,0,63,54,54,54,54])],[187,new Uint8Array([0,0,0,252,54,54,54,54])],[200,new Uint8Array([54,54,54,63,0,0,0,0])],[188,new Uint8Array([54,54,54,252,0,0,0,0])],[204,new Uint8Array([54,54,54,63,54,54,54,54])],[185,new Uint8Array([54,54,54,252,54,54,54,54])],[203,new Uint8Array([0,0,0,255,54,54,54,54])],[202,new Uint8Array([54,54,54,255,0,0,0,0])],[206,new Uint8Array([54,54,54,255,54,54,54,54])],[219,new Uint8Array([255,255,255,255,255,255,255,255])],[178,new Uint8Array([170,85,170,85,170,85,170,85])],[177,new Uint8Array([136,34,136,34,136,34,136,34])],[176,new Uint8Array([34,136,34,136,34,136,34,136])],[223,new Uint8Array([255,255,255,255,0,0,0,0])],[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])]]);function dk(r){return _a.get(r)}K(dk,"getCharBitmap");function hk(r){return _a.has(r)}K(hk,"hasChar");function fk(){return Array.from(_a.keys()).sort((r,e)=>r-e)}K(fk,"getAllCharCodes");function pk(r){let e=Array.from(_a.entries()).map(([t,n])=>({charCode:t,bitmap:n}));return{loadType:4,fontId:r,width:8,height:8,cellWidth:8,cellHeight:8,characters:e}}K(pk,"createASCII8x8FontLoad");function gk(){return{charWidth:8,charHeight:8,glyphs:new Map(_a)}}K(gk,"getASCII8x8FontConfig");Wr();var $w=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=ne.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let t=ne.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=ne.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=ne.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=ne.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};K($w,"MacroEventEncoder");var mk=$w;function Nw(r,e,t,n,i,s,o,a=[],l=[],u=[],c=[]){let d=Array.from(e.entries()).sort((H,P)=>H[0]-P[0]),h=Array.from(t.entries()).sort((H,P)=>H[0]-P[0]),f=d.length,p=h.length,g=lw(f,p),C=new TextEncoder,y=a.map(H=>C.encode(H)),m=1+y.reduce((H,P)=>H+1+P.length,0),v=new mk,b=l.map(H=>v.encode(H)),S=1+b.reduce((H,P)=>H+P.length,0),I=Math.min(u.length,255),E=1+I*5,U=Math.min(c.length,10),z=1+U*4,B=g+m+S+E+z,R=new Uint8Array(B),O=new DataView(R.buffer),A=0;O.setBigUint64(A,r,!0),A+=8;for(let[,H]of d){let P=ow(H);R[A]=P+256&255,A+=1}let V=Pu(p);for(let H=0;H<V;H++){let P=0;for(let W=0;W<8;W++){let j=H*8+W;if(j<p){let[,X]=h[j];X&&(P|=1<<W)}}R[A]=P,A+=1}R[A]=n&255,A+=1,R[A]=i&255,A+=1,R[A]=s&255,A+=1;let N=0;o&&(N|=1),R[A]=N,A+=1,R[A]=Math.min(a.length,255),A+=1;for(let H of y)R[A]=Math.min(H.length,255),A+=1,R.set(H.slice(0,255),A),A+=H.length;R[A]=Math.min(l.length,255),A+=1;for(let H of b)R.set(H,A),A+=H.length;R[A]=I,A+=1;for(let H=0;H<I;H++){let P=u[H];R[A]=P.displayId&255,A+=1,O.setUint16(A,Math.min(P.pixelWidth,65535),!1),A+=2,O.setUint16(A,Math.min(P.pixelHeight,65535),!1),A+=2}R[A]=U,A+=1;for(let H=0;H<U;H++){let P=c[H];R[A]=P.id&15,A+=1,R[A]=P.x&255,A+=1,R[A]=P.y&255,A+=1,R[A]=P.over?1:0,A+=1}return R}K(Nw,"encodeCompressedInput");var yk=class kt{static toCharCode(e){if(typeof e=="number")return e&65535;let t=e.charCodeAt(0);return uu(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 char(e,t,n,i=15,s=0){return{type:1,posX:e,posY:t,charCode:kt.toCharCode(n),bgColorCode:s,fgColorCode:i}}static text(e,t,n,i=15,s=0){return{type:2,posX:e,posY:t,text:n,bgColorCode:s,fgColorCode:i}}static textMultiline(e,t,n,i=15,s=0){return{type:23,posX:e,posY:t,text:kt.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=>kt.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:kt.toCharCode(o.charCode),bgColorCode:o.bgColorCode,fgColorCode:o.fgColorCode}))}}static fullFrame(e,t=15,n=0){return{type:5,frame:e.map(i=>kt.toCharCode(i)),bgColorCode:n,fgColorCode:t}}static fullFrameMultiColor(e){return{type:6,frame:e.map(t=>({charCode:kt.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:kt.toCharCode(s.charCode??9608),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:kt.toCharCode(i.charCode??9608),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:kt.toCharCode(s.charCode??9608),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:kt.toCharCode(s.charCode??9608),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:kt.toCharCode(a.charCode??9608),bgColorCode:a.bgColor??0,fgColorCode:a.fgColor??15}}}static dotCloud(e,t,n=15,i=0){return{type:11,charCode:kt.toCharCode(t),bgColorCode:i,fgColorCode:n,positions:e}}static dotCloudMultiColor(e){return{type:12,dots:e.map(t=>({...t,charCode:kt.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),g=f%8;h[p]|=1<<g}return{type:17,posX:e,posY:t,sizeX:n,sizeY:i,charCode:kt.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,g=Math.floor(f/4),
|
|
54
|
+
`)}static char(e,t,n,i=15,s=0){return{type:1,posX:e,posY:t,charCode:kt.toCharCode(n),bgColorCode:s,fgColorCode:i}}static text(e,t,n,i=15,s=0){return{type:2,posX:e,posY:t,text:n,bgColorCode:s,fgColorCode:i}}static textMultiline(e,t,n,i=15,s=0){return{type:23,posX:e,posY:t,text:kt.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=>kt.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:kt.toCharCode(o.charCode),bgColorCode:o.bgColorCode,fgColorCode:o.fgColorCode}))}}static fullFrame(e,t=15,n=0){return{type:5,frame:e.map(i=>kt.toCharCode(i)),bgColorCode:n,fgColorCode:t}}static fullFrameMultiColor(e){return{type:6,frame:e.map(t=>({charCode:kt.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:kt.toCharCode(s.charCode??9608),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:kt.toCharCode(i.charCode??9608),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:kt.toCharCode(s.charCode??9608),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:kt.toCharCode(s.charCode??9608),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:kt.toCharCode(a.charCode??9608),bgColorCode:a.bgColor??0,fgColorCode:a.fgColor??15}}}static dotCloud(e,t,n=15,i=0){return{type:11,charCode:kt.toCharCode(t),bgColorCode:i,fgColorCode:n,positions:e}}static dotCloudMultiColor(e){return{type:12,dots:e.map(t=>({...t,charCode:kt.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),g=f%8;h[p]|=1<<g}return{type:17,posX:e,posY:t,sizeX:n,sizeY:i,charCode:kt.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,g=Math.floor(f/4),C=f%4*2;h[g]|=p<<C}return{type:18,posX:e,posY:t,sizeX:n,sizeY:i,override:a,variants:[{charCode:kt.toCharCode(u[0].char),fgColorCode:u[0].fgColor,bgColorCode:u[0].bgColor},{charCode:kt.toCharCode(u[1].char),fgColorCode:u[1].fgColor,bgColorCode:u[1].bgColor},{charCode:kt.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,g=Math.floor(f/2),C=f%2*4;h[g]|=p<<C}return{type:24,posX:e,posY:t,sizeX:n,sizeY:i,override:a,variants:u.map(f=>({charCode:kt.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 clear(e=32,t=15,n=0){return{type:19,charCode:kt.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=>kt.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??9608,bgColor:o.bgColor??0,fgColor:o.fgColor??8,filled:!0}),this.rectangle(e,t,n,i,{charCode:s.charCode??9608,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:kt.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)}};K(yk,"OrderBuilder");vo();k1();cS();var vk=(r=>(r[r.LayerEnabled=1]="LayerEnabled",r[r.SetMode=2]="SetMode",r[r.UpdatePosition=4]="UpdatePosition",r[r.UpdateZOrder=8]="UpdateZOrder",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))(vk||{}),dm;(r=>{function e(d,h){return(d&h)!==0}r.hasFlag=e,K(e,"hasFlag");function t(d,h){return d|h}r.addFlag=t,K(t,"addFlag");function n(d,h){return d&~h}r.removeFlag=n,K(n,"removeFlag");function i(...d){return d.reduce((h,f)=>h|f,0)}r.combine=i,K(i,"combine");function s(d){return(d&240)===0}r.isValid=s,K(s,"isValid");function o(d){return e(d,1)}r.isEnabled=o,K(o,"isEnabled");function a(d){return e(d,2)}r.isSetMode=a,K(a,"isSetMode");function l(d){return e(d,4)}r.hasPositionChanged=l,K(l,"hasPositionChanged");function u(d){return e(d,8)}r.hasZOrderChanged=u,K(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"),h.join(" | ")}r.describe=c,K(c,"describe")})(dm||(dm={}));gS();$1();M1();P1();w1();C1();D1();yS();mS();F1();var Ww=Object.defineProperty,wk=(r,e,t)=>e in r?Ww(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,cr=(r,e)=>Ww(r,"name",{value:e,configurable:!0}),L=(r,e,t)=>(wk(r,typeof e!="symbol"?e+"":e,t),t),Hw=["#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 bk(r,e=Hw){return r<0||r>=e.length?"#ff00ff":e[r]}cr(bk,"paletteIndexToColor");function Ck(r,e=Hw){let t=e.indexOf(r.toLowerCase());return t>=0?t:0}cr(Ck,"colorToPaletteIndex");var Vw=class{constructor(e,t){L(this,"canvas"),L(this,"ctx"),L(this,"container"),L(this,"cols",0),L(this,"rows",0),L(this,"cellWidth",0),L(this,"cellHeight",0),L(this,"offsetX",0),L(this,"offsetY",0),L(this,"strokeColor","rgba(80, 80, 80, 0.4)"),L(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;
|
|
58
58
|
image-rendering: pixelated !important;
|
|
59
59
|
image-rendering: crisp-edges !important;
|
|
60
60
|
z-index: ${n} !important;
|
|
61
|
-
`,this.container.appendChild(this.canvas);let i=this.canvas.getContext("2d");if(!i)throw new Error("[GridOverlay] Impossible de créer le contexte 2D");this.ctx=i,t&&(t.strokeColor&&(this.strokeColor=t.strokeColor),t.lineWidth!==void 0&&(this.lineWidth=t.lineWidth))}setDimensions(e,t,n,i,s=0,o=0){this.cols=e,this.rows=t,this.cellWidth=n,this.cellHeight=i,this.offsetX=s,this.offsetY=o}setCanvasSize(e,t){this.canvas.width=e,this.canvas.height=t,this.ctx.setTransform(1,0,0,1,0,0)}setStyle(e){e.strokeColor&&(this.strokeColor=e.strokeColor),e.lineWidth!==void 0&&(this.lineWidth=e.lineWidth)}setTransform(e,t,n,i,s){let o=i.left-s.left,a=i.top-s.top,l=i.width,u=i.height;(this.canvas.width!==l||this.canvas.height!==u)&&(this.canvas.width=l,this.canvas.height=u);let c=this.canvas.style;c.width=`${l}px`,c.height=`${u}px`,c.left=`${o}px`,c.top=`${a}px`}render(){if(!this.ctx)return;let e=this.cols*this.cellWidth,t=this.rows*this.cellHeight,n=e>0?this.canvas.width/e:1,i=t>0?this.canvas.height/t:1,s=Math.min(n,i),o=this.cellWidth*s,a=this.cellHeight*s,l=this.cols*o,u=this.rows*a,c=this.offsetX*s,d=this.offsetY*s;if(!(l===0||u===0)){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.strokeStyle=this.strokeColor,this.ctx.lineWidth=Math.max(1,this.lineWidth*s),this.ctx.beginPath();for(let h=0;h<=this.cols;h++){let f=c+h*o+.5;this.ctx.moveTo(f,d),this.ctx.lineTo(f,d+u)}for(let h=0;h<=this.rows;h++){let f=d+h*a+.5;this.ctx.moveTo(c,f),this.ctx.lineTo(c+l,f)}this.ctx.stroke()}}update(e,t,n,i,s,o,a=0,l=0){this.setDimensions(e,t,n,i,a,l),this.setCanvasSize(s,o),this.render()}setVisible(e){this.canvas.style.display=e?"block":"none"}destroy(){this.canvas.parentElement&&this.canvas.parentElement.removeChild(this.canvas)}getCanvas(){return this.canvas}};cr(
|
|
61
|
+
`,this.container.appendChild(this.canvas);let i=this.canvas.getContext("2d");if(!i)throw new Error("[GridOverlay] Impossible de créer le contexte 2D");this.ctx=i,t&&(t.strokeColor&&(this.strokeColor=t.strokeColor),t.lineWidth!==void 0&&(this.lineWidth=t.lineWidth))}setDimensions(e,t,n,i,s=0,o=0){this.cols=e,this.rows=t,this.cellWidth=n,this.cellHeight=i,this.offsetX=s,this.offsetY=o}setCanvasSize(e,t){this.canvas.width=e,this.canvas.height=t,this.ctx.setTransform(1,0,0,1,0,0)}setStyle(e){e.strokeColor&&(this.strokeColor=e.strokeColor),e.lineWidth!==void 0&&(this.lineWidth=e.lineWidth)}setTransform(e,t,n,i,s){let o=i.left-s.left,a=i.top-s.top,l=i.width,u=i.height;(this.canvas.width!==l||this.canvas.height!==u)&&(this.canvas.width=l,this.canvas.height=u);let c=this.canvas.style;c.width=`${l}px`,c.height=`${u}px`,c.left=`${o}px`,c.top=`${a}px`}render(){if(!this.ctx)return;let e=this.cols*this.cellWidth,t=this.rows*this.cellHeight,n=e>0?this.canvas.width/e:1,i=t>0?this.canvas.height/t:1,s=Math.min(n,i),o=this.cellWidth*s,a=this.cellHeight*s,l=this.cols*o,u=this.rows*a,c=this.offsetX*s,d=this.offsetY*s;if(!(l===0||u===0)){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.strokeStyle=this.strokeColor,this.ctx.lineWidth=Math.max(1,this.lineWidth*s),this.ctx.beginPath();for(let h=0;h<=this.cols;h++){let f=c+h*o+.5;this.ctx.moveTo(f,d),this.ctx.lineTo(f,d+u)}for(let h=0;h<=this.rows;h++){let f=d+h*a+.5;this.ctx.moveTo(c,f),this.ctx.lineTo(c+l,f)}this.ctx.stroke()}}update(e,t,n,i,s,o,a=0,l=0){this.setDimensions(e,t,n,i,a,l),this.setCanvasSize(s,o),this.render()}setVisible(e){this.canvas.style.display=e?"block":"none"}destroy(){this.canvas.parentElement&&this.canvas.parentElement.removeChild(this.canvas)}getCanvas(){return this.canvas}};cr(Vw,"GridOverlay");var du=Vw;function Gf(r){return Math.sqrt(r)*16}cr(Gf,"getAtlasColumns");function Xf(r){return r*256-1}cr(Xf,"getMaxCharCode");function hu(r,e){let t=Math.floor(r/256),n=r%256,i=Math.sqrt(e),s=t%i,o=Math.floor(t/i),a=n%16,l=Math.floor(n/16);return{col:s*16+a,row:o*16+l}}cr(hu,"getCharGridPosition");var jw=class Ih{constructor(e,t){if(L(this,"canvas"),L(this,"gl"),L(this,"parentElement"),L(this,"containerDiv"),L(this,"cols"),L(this,"rows"),L(this,"charWidth"),L(this,"charHeight"),L(this,"cellWidth",8),L(this,"cellHeight",8),L(this,"glyphOffsetX",0),L(this,"glyphOffsetY",0),L(this,"canvasBgColor"),L(this,"showGrid"),L(this,"supportsUint32Indices",!1),L(this,"useUint16Indices",!1),L(this,"gridOverlay"),L(this,"bitmapFont"),L(this,"atlasTexture",null),L(this,"atlasCanvas"),L(this,"atlasColumns",0),L(this,"fontLoaded",!1),L(this,"paletteTexture",null),L(this,"program",null),L(this,"positionBuffer",null),L(this,"texCoordBuffer",null),L(this,"colorIndexBuffer",null),L(this,"indexBuffer",null),L(this,"aPosition"),L(this,"aTexCoord"),L(this,"aColorIndex"),L(this,"uResolution",null),L(this,"uTexture",null),L(this,"uPalette",null),L(this,"resizeObserver"),L(this,"charCodeToAtlasIndex",new Uint16Array(65536).fill(65535)),L(this,"atlasUVs",new Float32Array(0)),L(this,"cachedAtlasWidth",0),L(this,"cachedAtlasHeight",0),L(this,"paletteFloat",new Float32Array(256*4)),L(this,"maxCells",0),L(this,"renderPositions",new Float32Array(0)),L(this,"renderTexCoords",new Float32Array(0)),L(this,"renderColorIndices",new Float32Array(0)),L(this,"renderIndices",new Uint32Array(0)),L(this,"cachedResolution",[0,0]),L(this,"cachedTextureUnit",-1),L(this,"cachedPaletteUnit",-1),L(this,"cachedTextureUniform",!1),L(this,"cachedPaletteUniform",!1),L(this,"paletteHash",0),L(this,"currentScale",1),L(this,"scalingMode",$t.None),L(this,"ambientEffectEnabled",!1),L(this,"ambientEffectCanvas",null),L(this,"ambientEffectCtx",null),L(this,"ambientEffectBlur",Ge.ambientEffect.blur),L(this,"ambientEffectScale",Ge.ambientEffect.scale),L(this,"ambientEffectOpacity",.7),L(this,"onResizeCallback"),L(this,"staticPositionsInitialized",!1),L(this,"vaoExtension",null),L(this,"vao",null),L(this,"instancedExtension",null),L(this,"useInstancing",!1),L(this,"instanceDataBuffer",null),L(this,"instanceData",new Float32Array(0)),L(this,"templateQuadPositions",new Float32Array(0)),L(this,"templateQuadIndices",new Uint16Array(0)),L(this,"aInstanceOffset",-1),L(this,"aInstanceUVs",-1),L(this,"aInstanceColors",-1),L(this,"uCellSize",null),!e)throw new Error("TerminalGL: Parent element is required");if(!Number.isInteger(t.cols)||t.cols<=0)throw new Error(`TerminalGL: Invalid cols: ${t.cols}. Must be a positive integer.`);if(!Number.isInteger(t.rows)||t.rows<=0)throw new Error(`TerminalGL: Invalid rows: ${t.rows}. Must be a positive integer.`);let n=t.cols*t.rows,i=Ih.checkCompatibility();if(i.errors.length>0)throw new Error(`TerminalGL: WebGL incompatible - ${i.errors.join(", ")}`);let s=t.forceUint16??!1;if(s&&n>i.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${t.cols}×${t.rows} (${n} cells) exceeds Uint16 limit of ${i.maxCellsUint16} cells. Maximum size with Uint16: ${Math.floor(Math.sqrt(i.maxCellsUint16))}×${Math.floor(Math.sqrt(i.maxCellsUint16))} (or smaller rectangles like 127×64)`);if(!i.uint32Indices&&n>i.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${t.cols}×${t.rows} (${n} cells) exceeds device limit of ${i.maxCellsUint16} cells (OES_element_index_uint not supported). Maximum size: ${Math.floor(Math.sqrt(i.maxCellsUint16))}×${Math.floor(Math.sqrt(i.maxCellsUint16))}`);n>i.recommendedMaxCells&&console.warn(`[TerminalGL] ⚠️ Large terminal size ${t.cols}×${t.rows} (${n} cells) exceeds recommended limit of ${i.recommendedMaxCells} cells. Performance may be impacted.`),i.warnings.length>0&&console.warn("[TerminalGL] WebGL Compatibility Warnings:",i.warnings);let o=t.charWidth??8,a=t.charHeight??8;if(!Number.isFinite(o)||o<=0)throw new Error(`TerminalGL: Invalid charWidth: ${o}. Must be a positive number.`);if(!Number.isFinite(a)||a<=0)throw new Error(`TerminalGL: Invalid charHeight: ${a}. Must be a positive number.`);for(this.parentElement=e,this.cols=t.cols,this.rows=t.rows,this.charWidth=o,this.charHeight=a,this.canvasBgColor=t.canvasBgColor!==void 0?t.canvasBgColor:null,this.showGrid=t.showGrid??!1,this.scalingMode=t.scalingMode??$t.None,t.ambientEffect&&(this.ambientEffectEnabled=!0,typeof t.ambientEffect=="object"&&(this.ambientEffectBlur=t.ambientEffect.blur??Ge.ambientEffect.blur,this.ambientEffectScale=t.ambientEffect.scale??Ge.ambientEffect.scale,this.ambientEffectOpacity=t.ambientEffect.opacity??.7));this.parentElement.firstChild;)this.parentElement.removeChild(this.parentElement.firstChild);let l=window.getComputedStyle(this.parentElement).position;l!=="relative"&&l!=="absolute"&&l!=="fixed"&&(this.parentElement.style.position="relative"),this.containerDiv=document.createElement("div"),this.containerDiv.className="terminalgl-container",this.containerDiv.style.cssText=`
|
|
62
62
|
position: absolute !important;
|
|
63
63
|
top: 0 !important;
|
|
64
64
|
left: 0 !important;
|
|
@@ -88,7 +88,7 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
88
88
|
z-index: 1 !important;
|
|
89
89
|
pointer-events: auto !important;
|
|
90
90
|
touch-action: none !important;
|
|
91
|
-
`;let u=this.canvas.getContext("webgl",{alpha:this.canvasBgColor===null,premultipliedAlpha:!1});if(!u)throw new Error("TerminalGL: WebGL not supported");this.gl=u,this.supportsUint32Indices=!!u.getExtension("OES_element_index_uint"),this.useUint16Indices=s||!this.supportsUint32Indices,this.useUint16Indices?console.warn(`[TerminalGL] 📊 Using Uint16 indices (max ${i.maxCellsUint16} cells)`):console.warn(`[TerminalGL] 📊 Using Uint32 indices (max ${i.maxCellsUint32} cells)`),this.vaoExtension=u.getExtension("OES_vertex_array_object"),this.vaoExtension&&console.warn("[TerminalGL] ✅ VAO extension enabled (faster attribute binding)"),this.instancedExtension=u.getExtension("ANGLE_instanced_arrays"),this.instancedExtension?(this.useInstancing=!0,console.warn("[TerminalGL] 🚀 Instanced rendering enabled (massive draw call reduction)")):console.warn("[TerminalGL] ⚠️ Instanced rendering not available (fallback to standard rendering)"),this.containerDiv.appendChild(this.canvas),this.ambientEffectEnabled&&(this.createAmbientEffectCanvas(),console.warn("[TerminalGL] 🌈 Ambient effect enabled at startup")),this.parentElement.appendChild(this.containerDiv),this.initRenderBuffers();try{this.initWebGL()}catch(c){throw console.error("[TerminalGL] ❌ Failed to initialize WebGL:",c),c}this.showGrid&&this.initGridOverlay(),this.setupResizeObserver()}static checkCompatibility(){let e={webgl1:!1,uint32Indices:!1,maxTextureSize:0,maxViewportDims:[0,0],maxCellsUint16:0,maxCellsUint32:0,recommendedMaxCells:0,warnings:[],errors:[]},t=document.createElement("canvas"),n=t.getContext("webgl")||t.getContext("experimental-webgl");if(!n||!(n instanceof WebGLRenderingContext))return e.errors.push("❌ WebGL 1.0 not supported by this browser/device"),e;let i=n;e.webgl1=!0;try{e.maxTextureSize=i.getParameter(i.MAX_TEXTURE_SIZE);let a=i.getParameter(i.MAX_VIEWPORT_DIMS);e.maxViewportDims=[a[0],a[1]]}catch(a){return e.errors.push(`❌ Failed to query WebGL parameters: ${a}`),e}let s=i.getExtension("OES_element_index_uint");e.uint32Indices=!!s;let o=8;if(e.maxCellsUint16=Math.floor(65535/o),e.uint32Indices){let a=Math.floor(e.maxTextureSize*e.maxTextureSize/64);e.maxCellsUint32=Math.min(a,262144)}else e.maxCellsUint32=e.maxCellsUint16,e.warnings.push(`⚠️ OES_element_index_uint not supported - limited to ${e.maxCellsUint16} cells (e.g., 90×90 or 127×64)`);return e.recommendedMaxCells=Math.floor((e.uint32Indices?e.maxCellsUint32:e.maxCellsUint16)*.8),e.maxTextureSize<256?e.errors.push(`❌ MAX_TEXTURE_SIZE too small: ${e.maxTextureSize} (minimum 256 required for font atlas)`):e.maxTextureSize<2048&&e.warnings.push(`⚠️ Small MAX_TEXTURE_SIZE: ${e.maxTextureSize} (may limit font atlas)`),(e.maxViewportDims[0]<1024||e.maxViewportDims[1]<768)&&e.warnings.push(`⚠️ Small MAX_VIEWPORT_DIMS: ${e.maxViewportDims[0]}×${e.maxViewportDims[1]}`),i.getExtension("WEBGL_lose_context")||e.warnings.push("⚠️ WEBGL_lose_context not supported - may cause memory leaks"),e}initInstancedBuffers(){let e=this.gl;this.templateQuadPositions=new Float32Array([0,0,this.cellWidth,0,0,this.cellHeight,this.cellWidth,this.cellHeight]),this.templateQuadIndices=new Uint16Array([0,1,2,2,1,3]),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.bufferData(e.ARRAY_BUFFER,this.templateQuadPositions,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.templateQuadIndices,e.STATIC_DRAW),this.instanceData=new Float32Array(this.maxCells*8),console.warn(`[TerminalGL] 🚀 initInstancedBuffers: maxCells=${this.maxCells}, instanceData.length=${this.instanceData.length}`),e.bindBuffer(e.ARRAY_BUFFER,this.instanceDataBuffer),e.bufferData(e.ARRAY_BUFFER,this.instanceData.byteLength,e.DYNAMIC_DRAW)}initRenderBuffers(){let e=this.cols*this.rows*2;this.maxCells=Math.ceil(e*2),this.renderPositions=new Float32Array(this.maxCells*4*2),this.renderTexCoords=new Float32Array(this.maxCells*4*2),this.renderColorIndices=new Float32Array(this.maxCells*4),this.useUint16Indices?this.renderIndices=new Uint16Array(this.maxCells*6):this.renderIndices=new Uint32Array(this.maxCells*6),this.staticPositionsInitialized=!1}precomputeStaticPositions(){let e=this.cellWidth,t=this.cellHeight,n=this.glyphOffsetX,i=this.glyphOffsetY,s=this.charWidth,o=this.charHeight,a=0,l=0,u=0;for(let d=0;d<this.rows;d++){let h=Math.round(d*t),f=Math.round(h+t);for(let p=0;p<this.cols;p++){let g=Math.round(p*e),
|
|
91
|
+
`;let u=this.canvas.getContext("webgl",{alpha:this.canvasBgColor===null,premultipliedAlpha:!1});if(!u)throw new Error("TerminalGL: WebGL not supported");this.gl=u,this.supportsUint32Indices=!!u.getExtension("OES_element_index_uint"),this.useUint16Indices=s||!this.supportsUint32Indices,this.useUint16Indices?console.warn(`[TerminalGL] 📊 Using Uint16 indices (max ${i.maxCellsUint16} cells)`):console.warn(`[TerminalGL] 📊 Using Uint32 indices (max ${i.maxCellsUint32} cells)`),this.vaoExtension=u.getExtension("OES_vertex_array_object"),this.vaoExtension&&console.warn("[TerminalGL] ✅ VAO extension enabled (faster attribute binding)"),this.instancedExtension=u.getExtension("ANGLE_instanced_arrays"),this.instancedExtension?(this.useInstancing=!0,console.warn("[TerminalGL] 🚀 Instanced rendering enabled (massive draw call reduction)")):console.warn("[TerminalGL] ⚠️ Instanced rendering not available (fallback to standard rendering)"),this.containerDiv.appendChild(this.canvas),this.ambientEffectEnabled&&(this.createAmbientEffectCanvas(),console.warn("[TerminalGL] 🌈 Ambient effect enabled at startup")),this.parentElement.appendChild(this.containerDiv),this.initRenderBuffers();try{this.initWebGL()}catch(c){throw console.error("[TerminalGL] ❌ Failed to initialize WebGL:",c),c}this.showGrid&&this.initGridOverlay(),this.setupResizeObserver()}static checkCompatibility(){let e={webgl1:!1,uint32Indices:!1,maxTextureSize:0,maxViewportDims:[0,0],maxCellsUint16:0,maxCellsUint32:0,recommendedMaxCells:0,warnings:[],errors:[]},t=document.createElement("canvas"),n=t.getContext("webgl")||t.getContext("experimental-webgl");if(!n||!(n instanceof WebGLRenderingContext))return e.errors.push("❌ WebGL 1.0 not supported by this browser/device"),e;let i=n;e.webgl1=!0;try{e.maxTextureSize=i.getParameter(i.MAX_TEXTURE_SIZE);let a=i.getParameter(i.MAX_VIEWPORT_DIMS);e.maxViewportDims=[a[0],a[1]]}catch(a){return e.errors.push(`❌ Failed to query WebGL parameters: ${a}`),e}let s=i.getExtension("OES_element_index_uint");e.uint32Indices=!!s;let o=8;if(e.maxCellsUint16=Math.floor(65535/o),e.uint32Indices){let a=Math.floor(e.maxTextureSize*e.maxTextureSize/64);e.maxCellsUint32=Math.min(a,262144)}else e.maxCellsUint32=e.maxCellsUint16,e.warnings.push(`⚠️ OES_element_index_uint not supported - limited to ${e.maxCellsUint16} cells (e.g., 90×90 or 127×64)`);return e.recommendedMaxCells=Math.floor((e.uint32Indices?e.maxCellsUint32:e.maxCellsUint16)*.8),e.maxTextureSize<256?e.errors.push(`❌ MAX_TEXTURE_SIZE too small: ${e.maxTextureSize} (minimum 256 required for font atlas)`):e.maxTextureSize<2048&&e.warnings.push(`⚠️ Small MAX_TEXTURE_SIZE: ${e.maxTextureSize} (may limit font atlas)`),(e.maxViewportDims[0]<1024||e.maxViewportDims[1]<768)&&e.warnings.push(`⚠️ Small MAX_VIEWPORT_DIMS: ${e.maxViewportDims[0]}×${e.maxViewportDims[1]}`),i.getExtension("WEBGL_lose_context")||e.warnings.push("⚠️ WEBGL_lose_context not supported - may cause memory leaks"),e}initInstancedBuffers(){let e=this.gl;this.templateQuadPositions=new Float32Array([0,0,this.cellWidth,0,0,this.cellHeight,this.cellWidth,this.cellHeight]),this.templateQuadIndices=new Uint16Array([0,1,2,2,1,3]),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.bufferData(e.ARRAY_BUFFER,this.templateQuadPositions,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.templateQuadIndices,e.STATIC_DRAW),this.instanceData=new Float32Array(this.maxCells*8),console.warn(`[TerminalGL] 🚀 initInstancedBuffers: maxCells=${this.maxCells}, instanceData.length=${this.instanceData.length}`),e.bindBuffer(e.ARRAY_BUFFER,this.instanceDataBuffer),e.bufferData(e.ARRAY_BUFFER,this.instanceData.byteLength,e.DYNAMIC_DRAW)}initRenderBuffers(){let e=this.cols*this.rows*2;this.maxCells=Math.ceil(e*2),this.renderPositions=new Float32Array(this.maxCells*4*2),this.renderTexCoords=new Float32Array(this.maxCells*4*2),this.renderColorIndices=new Float32Array(this.maxCells*4),this.useUint16Indices?this.renderIndices=new Uint16Array(this.maxCells*6):this.renderIndices=new Uint32Array(this.maxCells*6),this.staticPositionsInitialized=!1}precomputeStaticPositions(){let e=this.cellWidth,t=this.cellHeight,n=this.glyphOffsetX,i=this.glyphOffsetY,s=this.charWidth,o=this.charHeight,a=0,l=0,u=0;for(let d=0;d<this.rows;d++){let h=Math.round(d*t),f=Math.round(h+t);for(let p=0;p<this.cols;p++){let g=Math.round(p*e),C=Math.round(g+e);this.renderPositions[a++]=g,this.renderPositions[a++]=h,this.renderPositions[a++]=C,this.renderPositions[a++]=h,this.renderPositions[a++]=g,this.renderPositions[a++]=f,this.renderPositions[a++]=C,this.renderPositions[a++]=f,this.renderIndices[l++]=u,this.renderIndices[l++]=u+1,this.renderIndices[l++]=u+2,this.renderIndices[l++]=u+2,this.renderIndices[l++]=u+1,this.renderIndices[l++]=u+3,u+=4;let y=Math.round(g+n),m=Math.round(h+i),v=Math.round(y+s),b=Math.round(m+o);this.renderPositions[a++]=y,this.renderPositions[a++]=m,this.renderPositions[a++]=v,this.renderPositions[a++]=m,this.renderPositions[a++]=y,this.renderPositions[a++]=b,this.renderPositions[a++]=v,this.renderPositions[a++]=b,this.renderIndices[l++]=u,this.renderIndices[l++]=u+1,this.renderIndices[l++]=u+2,this.renderIndices[l++]=u+2,this.renderIndices[l++]=u+1,this.renderIndices[l++]=u+3,u+=4}}let c=this.gl;c.bindBuffer(c.ARRAY_BUFFER,this.positionBuffer),c.bufferSubData(c.ARRAY_BUFFER,0,this.renderPositions),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,this.indexBuffer),c.bufferSubData(c.ELEMENT_ARRAY_BUFFER,0,this.renderIndices),this.staticPositionsInitialized=!0}initWebGL(){let e=this.gl,t;this.useInstancing?t=`
|
|
92
92
|
// Per-vertex attributes (template quad)
|
|
93
93
|
attribute vec2 aPosition; // Local quad position (0,0 to cellW,cellH)
|
|
94
94
|
|
|
@@ -169,7 +169,7 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
169
169
|
gl_FragColor = vec4(texColor.rgb * vColor.rgb, texColor.a);
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
|
-
`,i=this.compileShader(e.VERTEX_SHADER,t),s=this.compileShader(e.FRAGMENT_SHADER,n);if(!i||!s)throw new Error("Shader compilation error");let o=e.createProgram();if(!o)throw new Error("Unable to create WebGL program");if(e.attachShader(o,i),e.attachShader(o,s),e.linkProgram(o),!e.getProgramParameter(o,e.LINK_STATUS)){let a=e.getProgramInfoLog(o);throw new Error("Program linking error: "+a)}this.program=o,this.cachedTextureUniform=!1,this.cachedPaletteUniform=!1,this.aPosition=e.getAttribLocation(o,"aPosition"),this.useInstancing?(this.aInstanceOffset=e.getAttribLocation(o,"aInstanceOffset"),this.aInstanceUVs=e.getAttribLocation(o,"aInstanceUVs"),this.aInstanceColors=e.getAttribLocation(o,"aInstanceColors"),this.uCellSize=e.getUniformLocation(o,"uCellSize"),this.instanceDataBuffer=e.createBuffer(),this.aTexCoord=this.aInstanceOffset,this.aColorIndex=this.aInstanceUVs):(this.aTexCoord=e.getAttribLocation(o,"aTexCoord"),this.aColorIndex=e.getAttribLocation(o,"aColorIndex")),this.uResolution=e.getUniformLocation(o,"uResolution"),this.uTexture=e.getUniformLocation(o,"uTexture"),this.uPalette=e.getUniformLocation(o,"uPalette"),this.positionBuffer=e.createBuffer(),this.texCoordBuffer=e.createBuffer(),this.colorIndexBuffer=e.createBuffer(),this.indexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderPositions.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderTexCoords.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderColorIndices.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,e.DYNAMIC_DRAW),this.vaoExtension&&(this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.enableVertexAttribArray(this.aPosition),e.vertexAttribPointer(this.aPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.enableVertexAttribArray(this.aTexCoord),e.vertexAttribPointer(this.aTexCoord,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.enableVertexAttribArray(this.aColorIndex),e.vertexAttribPointer(this.aColorIndex,1,e.FLOAT,!1,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null))),e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),e.viewport(0,0,this.canvas.width,this.canvas.height)}compileShader(e,t){let n=this.gl,i=n.createShader(e);return i?(n.shaderSource(i,t),n.compileShader(i),n.getShaderParameter(i,n.COMPILE_STATUS)?i:(console.error("Shader compilation error:",n.getShaderInfoLog(i)),n.deleteShader(i),null)):null}initGridOverlay(){this.gridOverlay=new du(this.containerDiv,{strokeColor:"rgba(144, 24, 24, 1)",lineWidth:1,zIndex:10}),this.updateGridOverlay()}updateGridOverlay(){if(!this.gridOverlay)return;let e=this.cols*this.cellWidth,t=this.rows*this.cellHeight,n=this.canvas.getBoundingClientRect(),i=this.containerDiv.getBoundingClientRect();this.gridOverlay.setDimensions(this.cols,this.rows,this.cellWidth,this.cellHeight,0,0),this.gridOverlay.setTransform(this.currentScale,e,t,n,i),this.gridOverlay.render()}setBitmapFont(e,t,n,i,s){this.bitmapFont=e,this.fontLoaded=!0,this.charWidth=Math.round(t),this.charHeight=Math.round(n),this.cellWidth=Math.round(i),this.cellHeight=Math.round(s),this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&(console.warn("[TerminalGL] 🚀 Initializing instanced buffers..."),this.initInstancedBuffers());try{this.generateAtlas()}catch(o){throw console.error("[TerminalGL] ❌ Failed to generate atlas:",o),o}this.buildCharCodeMap(),this.precomputeAtlasUVs(),this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.useInstancing||this.precomputeStaticPositions(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}async setImageFont(e,t,n,i,s,o){this.fontLoaded=!0,this.charWidth=Math.round(t),this.charHeight=Math.round(n),this.cellWidth=Math.round(i),this.cellHeight=Math.round(s),this.atlasColumns=Vf(o);let a=jf(o);this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&(console.warn("[TerminalGL] 🚀 Initializing instanced buffers for ImageFont..."),this.initInstancedBuffers()),await this.loadImageFontAtlas(e),this.charCodeToAtlasIndex.fill(65535);for(let l=0;l<=a;l++)this.charCodeToAtlasIndex[l]=l;this.precomputeImageFontUVs(o),this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.useInstancing||this.precomputeStaticPositions(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}async loadImageFontAtlas(e){return new Promise((t,n)=>{let i=new Uint8Array(e),s=new Blob([i],{type:"image/png"}),o=URL.createObjectURL(s),a=new Image;a.onload=()=>{URL.revokeObjectURL(o),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=a.width,this.atlasCanvas.height=a.height;let l=this.atlasCanvas.getContext("2d");if(!l){n(new Error("Failed to create 2D context for atlas"));return}l.drawImage(a,0,0),this.cachedAtlasWidth=a.width,this.cachedAtlasHeight=a.height,this.createAtlasTexture(),t()},a.onerror=()=>{URL.revokeObjectURL(o),n(new Error("Failed to load PNG image for ImageFont atlas"))},a.src=o})}precomputeImageFontUVs(e){let t=e*256;this.atlasUVs=new Float32Array(t*4);let n=this.cachedAtlasWidth,i=this.cachedAtlasHeight,s=.5/n,o=.5/i;for(let a=0;a<t;a++){let{col:l,row:u}=hu(a,e),c=(l*this.charWidth+s)/n,d=(u*this.charHeight+o)/i,h=((l+1)*this.charWidth-s)/n,f=((u+1)*this.charHeight-o)/i,p=a*4;this.atlasUVs[p]=c,this.atlasUVs[p+1]=d,this.atlasUVs[p+2]=h,this.atlasUVs[p+3]=f}}generateAtlas(){if(!this.bitmapFont)return;let e=Array.from(this.bitmapFont.keys()).sort((l,u)=>l-u),t=e.length;this.atlasColumns=Math.ceil(Math.sqrt(t));let n=Math.ceil(t/this.atlasColumns),i=this.atlasColumns*this.charWidth,s=n*this.charHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=i,this.atlasCanvas.height=s;let o=this.atlasCanvas.getContext("2d");if(!o)throw new Error("Unable to create 2D context for atlas");o.clearRect(0,0,i,s),o.fillStyle="#ffffff";let a=0;for(let l of e){let u=this.bitmapFont.get(l);if(!u)continue;let c=a%this.atlasColumns,d=Math.floor(a/this.atlasColumns),h=c*this.charWidth,f=d*this.charHeight;for(let p=0;p<Math.min(u.length,this.charHeight);p++){let g=u[p];for(let x=0;x<this.charWidth;x++){let y=1<<7-x;g&y&&o.fillRect(h+x,f+p,1,1)}}a++}this.createAtlasTexture()}buildCharCodeMap(){if(!this.bitmapFont)return;this.charCodeToAtlasIndex.fill(65535);let e=Array.from(this.bitmapFont.keys()).sort((t,n)=>t-n);for(let t=0;t<e.length;t++)this.charCodeToAtlasIndex[e[t]]=t}precomputeAtlasUVs(){if(!this.bitmapFont)return;let e=this.bitmapFont.size;this.atlasUVs=new Float32Array(e*4),this.cachedAtlasWidth=this.atlasColumns*this.charWidth,this.cachedAtlasHeight=Math.ceil(e/this.atlasColumns)*this.charHeight;let t=this.cachedAtlasWidth,n=this.cachedAtlasHeight,i=.5/t,s=.5/n;for(let o=0;o<e;o++){let a=o%this.atlasColumns,l=Math.floor(o/this.atlasColumns),u=(a*this.charWidth+i)/t,c=(l*this.charHeight+s)/n,d=((a+1)*this.charWidth-i)/t,h=((l+1)*this.charHeight-s)/n,f=o*4;this.atlasUVs[f]=u,this.atlasUVs[f+1]=c,this.atlasUVs[f+2]=d,this.atlasUVs[f+3]=h}}createAtlasTexture(){if(this.atlasCanvas)try{let e=this.gl,t=e.createTexture();if(!t)throw new Error("Unable to create texture");e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.atlasCanvas),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),this.atlasTexture=t}catch(e){throw console.error("[TerminalGL] ❌ Failed to create atlas texture:",e),e}}clear(){let e=this.gl;e&&e.clear(e.COLOR_BUFFER_BIT)}parseColor(e){if(e.startsWith("#")){let t=e.slice(1),n=0,i=0,s=0;return t.length===3?(n=parseInt(t[0]+t[0],16),i=parseInt(t[1]+t[1],16),s=parseInt(t[2]+t[2],16)):t.length===6&&(n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),s=parseInt(t.slice(4,6),16)),[n/255,i/255,s/255,1]}if(e.startsWith("rgb")){let t=e.match(/rgba?\(([^)]+)\)/);if(t){let n=t[1].split(",").map(i=>parseFloat(i.trim()));return[n[0]/255,n[1]/255,n[2]/255,n[3]!==void 0?n[3]:1]}}return[1,1,1,1]}setupResizeObserver(){if(!(typeof ResizeObserver>"u"))try{this.resizeObserver=new ResizeObserver(()=>{try{this.updateCanvasSize()}catch(e){console.error("[TerminalGL] ❌ Error in resize callback:",e)}}),this.resizeObserver.observe(this.parentElement),this.updateCanvasSize()}catch(e){console.error("[TerminalGL] ❌ Failed to setup ResizeObserver:",e)}}updateCanvasSize(){let e=this.parentElement.clientWidth,t=this.parentElement.clientHeight;if(e===0||t===0)return;let n=this.cols*this.cellWidth,i=this.rows*this.cellHeight;if(n===0||i===0)return;let s=e/n,o=t/i,a=Math.min(s,o),l;switch(this.scalingMode){case $t.Integer:l=Math.max(1,Math.floor(a));break;case $t.Half:l=Math.max(1,Math.floor(a*2)/2);break;case $t.Quarter:l=Math.max(1,Math.floor(a*4)/4);break;case $t.Eighth:l=Math.max(1,Math.floor(a*8)/8);break;case $t.Responsive:l=1;break;case $t.None:default:l=Math.max(.1,a);break}if(this.canvas.style.transform=`scale(${l})`,this.ambientEffectEnabled&&this.ambientEffectCanvas){let u=l*this.ambientEffectScale;this.ambientEffectCanvas.style.transform=`scale(${u})`}this.currentScale=l,this.onResizeCallback&&this.onResizeCallback(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}updateAmbientEffect(){!this.ambientEffectCanvas||!this.ambientEffectCtx||this.ambientEffectCtx.drawImage(this.canvas,0,0)}setPalette(e){let t=0;for(let n=0;n<Math.min(e.length,256);n++){let i=e[n];t=(t<<5)-t+i.r,t=(t<<5)-t+i.g,t=(t<<5)-t+i.b,t=(t<<5)-t+i.a,t=t|0}if(t!==this.paletteHash){this.paletteHash=t;for(let n=0;n<e.length&&n<256;n++){let i=e[n],s=n*4;this.paletteFloat[s]=i.r/255,this.paletteFloat[s+1]=i.g/255,this.paletteFloat[s+2]=i.b/255,this.paletteFloat[s+3]=i.a/255}this.updatePaletteTexture()}}updatePaletteTexture(){try{let e=this.gl;this.paletteTexture||(this.paletteTexture=e.createTexture()),e.bindTexture(e.TEXTURE_2D,this.paletteTexture);let t=new Uint8Array(256*4);for(let n=0;n<256;n++){let i=n*4;t[i]=this.paletteFloat[i]*255,t[i+1]=this.paletteFloat[i+1]*255,t[i+2]=this.paletteFloat[i+2]*255,t[i+3]=this.paletteFloat[i+3]*255}e.texImage2D(e.TEXTURE_2D,0,e.RGBA,256,1,0,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null)}catch(e){throw console.error("[TerminalGL] ❌ Failed to update palette texture:",e),e}}renderDisplayData(e){try{if(!this.isReady()){console.warn("[TerminalGL] ⚠️ Not ready: font not loaded yet");return}(e.width!==this.cols||e.height!==this.rows)&&this.resize(e.width,e.height),this.renderDirect(e),this.ambientEffectEnabled&&this.ambientEffectCanvas&&this.ambientEffectCtx&&this.updateAmbientEffect()}catch(t){console.error("[TerminalGL] ❌ Error rendering display data:",t)}}renderDirect(e){let t=this.gl;if(!this.staticPositionsInitialized&&!this.useInstancing&&this.precomputeStaticPositions(),this.canvasBgColor!==null){let n=this.parseColor(this.canvasBgColor);t.clearColor(n[0],n[1],n[2],n[3])}else t.clearColor(0,0,0,0);t.clear(t.COLOR_BUFFER_BIT),this.useInstancing?this.renderInstanced(e):this.renderDirectBuffers(e)}renderInstanced(e){let t=this.gl,n=this.instancedExtension;if(!this.instanceData||this.instanceData.length===0){console.warn("[TerminalGL] ⚠️ Instance data not initialized, falling back to standard rendering"),this.renderDirectBuffers(e);return}let i=0,s=this.instanceData.length/8,o=e.width*e.height*2;if(o>s){console.error(`[TerminalGL] ❌ Instance buffer too small! Need ${o}, have ${s}. Display size: ${e.width}×${e.height}, buffer was sized for smaller terminal.`),this.renderDirectBuffers(e);return}for(let l=0;l<e.height;l++)for(let u=0;u<e.width;u++){let c=e.cells[l*e.width+u],d=c.bgColorIndex,h=c.fgColorIndex,f=this.canvasBgColor!==null&&d===255,p=c.char===" "||h===255;if(!f){if(i>=s){console.error(`[TerminalGL] ❌ Instance buffer overflow! instanceIdx=${i}, max=${s}`);break}let g=i*8;this.instanceData[g]=u,this.instanceData[g+1]=l,this.instanceData[g+2]=0,this.instanceData[g+3]=0,this.instanceData[g+4]=0,this.instanceData[g+5]=0,this.instanceData[g+6]=d,this.instanceData[g+7]=0,i++}if(!p){let g=c.char.charCodeAt(0),x=this.charCodeToAtlasIndex[g];if(x!==65535){if(i>=s){console.error(`[TerminalGL] ❌ Instance buffer overflow! instanceIdx=${i}, max=${s}`);break}let y=x*4,m=i*8;this.instanceData[m]=u,this.instanceData[m+1]=l,this.instanceData[m+2]=this.atlasUVs[y],this.instanceData[m+3]=this.atlasUVs[y+1],this.instanceData[m+4]=this.atlasUVs[y+2],this.instanceData[m+5]=this.atlasUVs[y+3],this.instanceData[m+6]=0,this.instanceData[m+7]=h,i++}}}if(i===0){console.warn("[TerminalGL] ⚠️ No instances to draw (all cells skipped)");return}t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.instanceData.subarray(0,i*8)),t.useProgram(this.program),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.enableVertexAttribArray(this.aPosition),t.vertexAttribPointer(this.aPosition,2,t.FLOAT,!1,0,0),n.vertexAttribDivisorANGLE(this.aPosition,0),t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer);let a=8*Float32Array.BYTES_PER_ELEMENT;t.enableVertexAttribArray(this.aInstanceOffset),t.vertexAttribPointer(this.aInstanceOffset,2,t.FLOAT,!1,a,0),n.vertexAttribDivisorANGLE(this.aInstanceOffset,1),t.enableVertexAttribArray(this.aInstanceUVs),t.vertexAttribPointer(this.aInstanceUVs,4,t.FLOAT,!1,a,2*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisorANGLE(this.aInstanceUVs,1),t.enableVertexAttribArray(this.aInstanceColors),t.vertexAttribPointer(this.aInstanceColors,2,t.FLOAT,!1,a,6*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisorANGLE(this.aInstanceColors,1),t.uniform2f(this.uResolution,this.canvas.width,this.canvas.height),t.uniform2f(this.uCellSize,this.cellWidth,this.cellHeight),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.atlasTexture),t.uniform1i(this.uTexture,0),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.paletteTexture),t.uniform1i(this.uPalette,1),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),n.drawElementsInstancedANGLE(t.TRIANGLES,6,t.UNSIGNED_SHORT,0,i),n.vertexAttribDivisorANGLE(this.aPosition,0),n.vertexAttribDivisorANGLE(this.aInstanceOffset,0),n.vertexAttribDivisorANGLE(this.aInstanceUVs,0),n.vertexAttribDivisorANGLE(this.aInstanceColors,0)}renderDirectBuffers(e){let t=this.gl,n=e.width*e.height,i=n*2;if(i>this.maxCells){console.error(`[TerminalGL] ❌ Buffer overflow detected! Trying to render ${i} quads but buffer capacity is ${this.maxCells}. This should not happen - resize() should have reallocated.`);return}let s=0,o=0,a=e.cells,l=n;for(let f=0;f<l;f++){let p=a[f],g=p.bgColorIndex,x=this.canvasBgColor!==null&&g===255?255:g,y=0;for(let b=0;b<4;b++)this.renderTexCoords[s++]=y,this.renderTexCoords[s++]=y,this.renderColorIndices[o++]=x;let m=p.fgColorIndex,v=p.char;if(v===" "||m===255)for(let b=0;b<4;b++)this.renderTexCoords[s++]=0,this.renderTexCoords[s++]=0,this.renderColorIndices[o++]=255;else{let b=v.charCodeAt(0),I=this.charCodeToAtlasIndex[b];if(I!==65535){let S=I*4,M=this.atlasUVs[S],U=this.atlasUVs[S+1],z=this.atlasUVs[S+2],O=this.atlasUVs[S+3];this.renderTexCoords[s++]=M,this.renderTexCoords[s++]=U,this.renderColorIndices[o++]=m,this.renderTexCoords[s++]=z,this.renderTexCoords[s++]=U,this.renderColorIndices[o++]=m,this.renderTexCoords[s++]=M,this.renderTexCoords[s++]=O,this.renderColorIndices[o++]=m,this.renderTexCoords[s++]=z,this.renderTexCoords[s++]=O,this.renderColorIndices[o++]=m}else for(let S=0;S<4;S++)this.renderTexCoords[s++]=0,this.renderTexCoords[s++]=0,this.renderColorIndices[o++]=255}}(s!==l*2*4*2||o!==l*2*4)&&console.error("[TerminalGL] ❌ Buffer index mismatch!",{texIdx:s,colorIdx:o,expected:l*2*4}),t.useProgram(this.program),this.vao&&this.vaoExtension?(this.vaoExtension.bindVertexArrayOES(this.vao),t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,s)),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,o))):(t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.enableVertexAttribArray(this.aPosition),t.vertexAttribPointer(this.aPosition,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,s)),t.enableVertexAttribArray(this.aTexCoord),t.vertexAttribPointer(this.aTexCoord,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,o)),t.enableVertexAttribArray(this.aColorIndex),t.vertexAttribPointer(this.aColorIndex,1,t.FLOAT,!1,0,0));let u=this.canvas.width,c=this.canvas.height;(this.cachedResolution[0]!==u||this.cachedResolution[1]!==c)&&(t.uniform2f(this.uResolution,u,c),this.cachedResolution[0]=u,this.cachedResolution[1]=c),this.cachedTextureUnit!==0&&(t.activeTexture(t.TEXTURE0),this.cachedTextureUnit=0),t.bindTexture(t.TEXTURE_2D,this.atlasTexture),this.cachedTextureUniform||(t.uniform1i(this.uTexture,0),this.cachedTextureUniform=!0),this.cachedPaletteUnit!==1&&(t.activeTexture(t.TEXTURE1),this.cachedPaletteUnit=1),t.bindTexture(t.TEXTURE_2D,this.paletteTexture),this.cachedPaletteUniform||(t.uniform1i(this.uPalette,1),this.cachedPaletteUniform=!0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);let d=e.width*e.height*2*6,h=this.useUint16Indices?t.UNSIGNED_SHORT:t.UNSIGNED_INT;t.drawElements(t.TRIANGLES,d,h,0)}resize(e,t){if(!Number.isInteger(e)||e<=0){console.error(`[TerminalGL] ❌ Invalid cols: ${e}. Must be positive integer.`);return}if(!Number.isInteger(t)||t<=0){console.error(`[TerminalGL] ❌ Invalid rows: ${t}. Must be positive integer.`);return}if(e===this.cols&&t===this.rows)return;let n=e*t,i=this.useInstancing?262144:this.useUint16Indices?8191:262144;if(n>i){let c=Math.floor(Math.sqrt(i));console.error(`[TerminalGL] ❌ Cannot resize to ${e}×${t} (${n} cells). Device limit: ${i} cells (max ~${c}×${c}). ${!this.useInstancing&&this.useUint16Indices?"Device lacks OES_element_index_uint extension.":""}`);return}let s=bh.checkCompatibility();n>s.recommendedMaxCells&&console.warn(`[TerminalGL] ⚠️ Resizing to ${e}×${t} (${n} cells) exceeds recommended limit (${s.recommendedMaxCells} cells). Performance may degrade.`),this.cols=e,this.rows=t,this.staticPositionsInitialized=!1;let o=this.cols*this.rows*2,a=Math.ceil(o*1.5),l=o>this.maxCells,u=this.maxCells>a*4;if(console.warn(`[TerminalGL] 📐 resize check: cols=${e}, rows=${t}, newMaxCells=${o}, this.maxCells=${this.maxCells}, needGrow=${l}, needShrink=${u}`),l||u){let c=this.maxCells;if(this.maxCells=a,console.warn(`[TerminalGL] 📐 resize realloc: ${c} → ${this.maxCells} (needGrow=${l}, needShrink=${u})`),this.renderPositions=new Float32Array(this.maxCells*4*2),this.renderTexCoords=new Float32Array(this.maxCells*4*2),this.renderColorIndices=new Float32Array(this.maxCells*4),this.useUint16Indices?this.renderIndices=new Uint16Array(this.maxCells*6):this.renderIndices=new Uint32Array(this.maxCells*6),this.useInstancing&&this.instanceDataBuffer){this.instanceData=new Float32Array(this.maxCells*8);let g=this.gl;g.bindBuffer(g.ARRAY_BUFFER,this.instanceDataBuffer),g.bufferData(g.ARRAY_BUFFER,this.instanceData.byteLength,g.DYNAMIC_DRAW)}let d=this.gl;this.useInstancing||(d.bindBuffer(d.ARRAY_BUFFER,this.positionBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderPositions.byteLength,d.DYNAMIC_DRAW)),d.bindBuffer(d.ARRAY_BUFFER,this.texCoordBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderTexCoords.byteLength,d.DYNAMIC_DRAW),d.bindBuffer(d.ARRAY_BUFFER,this.colorIndexBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderColorIndices.byteLength,d.DYNAMIC_DRAW),this.useInstancing||(d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,this.indexBuffer),d.bufferData(d.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,d.DYNAMIC_DRAW)),this.vaoExtension&&this.vao&&(this.vaoExtension.deleteVertexArrayOES(this.vao),this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),d.bindBuffer(d.ARRAY_BUFFER,this.positionBuffer),d.enableVertexAttribArray(this.aPosition),d.vertexAttribPointer(this.aPosition,2,d.FLOAT,!1,0,0),d.bindBuffer(d.ARRAY_BUFFER,this.texCoordBuffer),d.enableVertexAttribArray(this.aTexCoord),d.vertexAttribPointer(this.aTexCoord,2,d.FLOAT,!1,0,0),d.bindBuffer(d.ARRAY_BUFFER,this.colorIndexBuffer),d.enableVertexAttribArray(this.aColorIndex),d.vertexAttribPointer(this.aColorIndex,1,d.FLOAT,!1,0,0),d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null)));let h=l?"📈 Growing":"📉 Shrinking",f=c*160/1048576,p=this.maxCells*160/1048576;console.warn(`[TerminalGL] ${h} buffers: ${f.toFixed(2)}MB → ${p.toFixed(2)}MB (${c} → ${this.maxCells} quads)`)}this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.canvas.style.width=`${this.canvas.width}px`,this.canvas.style.height=`${this.canvas.height}px`,this.ambientEffectEnabled&&this.ambientEffectCanvas&&(this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.width=`${this.canvas.width}px`,this.ambientEffectCanvas.style.height=`${this.canvas.height}px`),this.showGrid&&this.gridOverlay&&this.updateGridOverlay(),this.updateCanvasSize()}getCanvas(){return this.canvas}getGridSize(){return{cols:this.cols,rows:this.rows}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCurrentScale(){return this.currentScale}getBaseDimensions(){return{width:this.cols*this.cellWidth,height:this.rows*this.cellHeight}}setOnResizeCallback(e){this.onResizeCallback=e}clearOnResizeCallback(){this.onResizeCallback=void 0}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}setScalingMode(e){this.scalingMode!==e&&(this.scalingMode=e,this.updateCanvasSize())}getScalingMode(){return this.scalingMode}setCellSize(e,t){let n=Math.max(1,Math.min(255,Math.round(e))),i=Math.max(1,Math.min(255,Math.round(t)));this.cellWidth===n&&this.cellHeight===i||(this.cellWidth=n,this.cellHeight=i,this.charWidth=n,this.charHeight=i,this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.fontLoaded&&this.generateAtlas(),this.useInstancing&&this.initInstancedBuffers(),this.updateCanvasSize())}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getMaxCells(){return this.useInstancing?262144:this.useUint16Indices?8191:262144}setGrid(e){e.enabled?(this.gridOverlay?this.gridOverlay.setStyle({strokeColor:e.color,lineWidth:e.lineWidth}):this.gridOverlay=new du(this.containerDiv,{strokeColor:e.color??"rgba(144, 24, 24, 1)",lineWidth:e.lineWidth??1,zIndex:10}),this.showGrid=!0,this.gridOverlay.setVisible(!0),this.updateGridOverlay()):(this.showGrid=!1,this.gridOverlay&&this.gridOverlay.setVisible(!1))}isGridEnabled(){return this.showGrid}setAmbientEffect(e){typeof e=="boolean"?this.ambientEffectEnabled=e:(this.ambientEffectEnabled=!0,e.blur!==void 0&&(this.ambientEffectBlur=e.blur),e.scale!==void 0&&(this.ambientEffectScale=e.scale)),this.ambientEffectEnabled&&!this.ambientEffectCanvas&&this.createAmbientEffectCanvas(),this.ambientEffectCanvas&&(this.ambientEffectEnabled?(this.ambientEffectCanvas.style.display="block",this.ambientEffectCanvas.style.filter=`blur(${this.ambientEffectBlur}px)`,this.ambientEffectCanvas.style.transform=`scale(${this.ambientEffectScale})`,this.updateAmbientEffect()):this.ambientEffectCanvas.style.display="none")}createAmbientEffectCanvas(){this.ambientEffectCanvas||(this.ambientEffectCanvas=document.createElement("canvas"),this.ambientEffectCanvas.className="terminalgl-ambient-effect-canvas",this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.cssText=`
|
|
172
|
+
`,i=this.compileShader(e.VERTEX_SHADER,t),s=this.compileShader(e.FRAGMENT_SHADER,n);if(!i||!s)throw new Error("Shader compilation error");let o=e.createProgram();if(!o)throw new Error("Unable to create WebGL program");if(e.attachShader(o,i),e.attachShader(o,s),e.linkProgram(o),!e.getProgramParameter(o,e.LINK_STATUS)){let a=e.getProgramInfoLog(o);throw new Error("Program linking error: "+a)}this.program=o,this.cachedTextureUniform=!1,this.cachedPaletteUniform=!1,this.aPosition=e.getAttribLocation(o,"aPosition"),this.useInstancing?(this.aInstanceOffset=e.getAttribLocation(o,"aInstanceOffset"),this.aInstanceUVs=e.getAttribLocation(o,"aInstanceUVs"),this.aInstanceColors=e.getAttribLocation(o,"aInstanceColors"),this.uCellSize=e.getUniformLocation(o,"uCellSize"),this.instanceDataBuffer=e.createBuffer(),this.aTexCoord=this.aInstanceOffset,this.aColorIndex=this.aInstanceUVs):(this.aTexCoord=e.getAttribLocation(o,"aTexCoord"),this.aColorIndex=e.getAttribLocation(o,"aColorIndex")),this.uResolution=e.getUniformLocation(o,"uResolution"),this.uTexture=e.getUniformLocation(o,"uTexture"),this.uPalette=e.getUniformLocation(o,"uPalette"),this.positionBuffer=e.createBuffer(),this.texCoordBuffer=e.createBuffer(),this.colorIndexBuffer=e.createBuffer(),this.indexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderPositions.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderTexCoords.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderColorIndices.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,e.DYNAMIC_DRAW),this.vaoExtension&&(this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.enableVertexAttribArray(this.aPosition),e.vertexAttribPointer(this.aPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.enableVertexAttribArray(this.aTexCoord),e.vertexAttribPointer(this.aTexCoord,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.enableVertexAttribArray(this.aColorIndex),e.vertexAttribPointer(this.aColorIndex,1,e.FLOAT,!1,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null))),e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),e.viewport(0,0,this.canvas.width,this.canvas.height)}compileShader(e,t){let n=this.gl,i=n.createShader(e);return i?(n.shaderSource(i,t),n.compileShader(i),n.getShaderParameter(i,n.COMPILE_STATUS)?i:(console.error("Shader compilation error:",n.getShaderInfoLog(i)),n.deleteShader(i),null)):null}initGridOverlay(){this.gridOverlay=new du(this.containerDiv,{strokeColor:"rgba(144, 24, 24, 1)",lineWidth:1,zIndex:10}),this.updateGridOverlay()}updateGridOverlay(){if(!this.gridOverlay)return;let e=this.cols*this.cellWidth,t=this.rows*this.cellHeight,n=this.canvas.getBoundingClientRect(),i=this.containerDiv.getBoundingClientRect();this.gridOverlay.setDimensions(this.cols,this.rows,this.cellWidth,this.cellHeight,0,0),this.gridOverlay.setTransform(this.currentScale,e,t,n,i),this.gridOverlay.render()}setBitmapFont(e,t,n,i,s){this.bitmapFont=e,this.fontLoaded=!0,this.charWidth=Math.round(t),this.charHeight=Math.round(n),this.cellWidth=Math.round(i),this.cellHeight=Math.round(s),this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&(console.warn("[TerminalGL] 🚀 Initializing instanced buffers..."),this.initInstancedBuffers());try{this.generateAtlas()}catch(o){throw console.error("[TerminalGL] ❌ Failed to generate atlas:",o),o}this.buildCharCodeMap(),this.precomputeAtlasUVs(),this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.useInstancing||this.precomputeStaticPositions(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}async setImageFont(e,t,n,i,s,o){this.fontLoaded=!0,this.charWidth=Math.round(t),this.charHeight=Math.round(n),this.cellWidth=Math.round(i),this.cellHeight=Math.round(s),this.atlasColumns=Gf(o);let a=Xf(o);this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&(console.warn("[TerminalGL] 🚀 Initializing instanced buffers for ImageFont..."),this.initInstancedBuffers()),await this.loadImageFontAtlas(e),this.charCodeToAtlasIndex.fill(65535);for(let l=0;l<=a;l++)this.charCodeToAtlasIndex[l]=l;this.precomputeImageFontUVs(o),this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.useInstancing||this.precomputeStaticPositions(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}async loadImageFontAtlas(e){return new Promise((t,n)=>{let i=new Uint8Array(e),s=new Blob([i],{type:"image/png"}),o=URL.createObjectURL(s),a=new Image;a.onload=()=>{URL.revokeObjectURL(o),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=a.width,this.atlasCanvas.height=a.height;let l=this.atlasCanvas.getContext("2d");if(!l){n(new Error("Failed to create 2D context for atlas"));return}l.drawImage(a,0,0),this.cachedAtlasWidth=a.width,this.cachedAtlasHeight=a.height,this.createAtlasTexture(),t()},a.onerror=()=>{URL.revokeObjectURL(o),n(new Error("Failed to load PNG image for ImageFont atlas"))},a.src=o})}precomputeImageFontUVs(e){let t=e*256;this.atlasUVs=new Float32Array(t*4);let n=this.cachedAtlasWidth,i=this.cachedAtlasHeight,s=.5/n,o=.5/i;for(let a=0;a<t;a++){let{col:l,row:u}=hu(a,e),c=(l*this.charWidth+s)/n,d=(u*this.charHeight+o)/i,h=((l+1)*this.charWidth-s)/n,f=((u+1)*this.charHeight-o)/i,p=a*4;this.atlasUVs[p]=c,this.atlasUVs[p+1]=d,this.atlasUVs[p+2]=h,this.atlasUVs[p+3]=f}}generateAtlas(){if(!this.bitmapFont)return;let e=Array.from(this.bitmapFont.keys()).sort((l,u)=>l-u),t=e.length;this.atlasColumns=Math.ceil(Math.sqrt(t));let n=Math.ceil(t/this.atlasColumns),i=this.atlasColumns*this.charWidth,s=n*this.charHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=i,this.atlasCanvas.height=s;let o=this.atlasCanvas.getContext("2d");if(!o)throw new Error("Unable to create 2D context for atlas");o.clearRect(0,0,i,s),o.fillStyle="#ffffff";let a=0;for(let l of e){let u=this.bitmapFont.get(l);if(!u)continue;let c=a%this.atlasColumns,d=Math.floor(a/this.atlasColumns),h=c*this.charWidth,f=d*this.charHeight;for(let p=0;p<Math.min(u.length,this.charHeight);p++){let g=u[p];for(let C=0;C<this.charWidth;C++){let y=1<<7-C;g&y&&o.fillRect(h+C,f+p,1,1)}}a++}this.createAtlasTexture()}buildCharCodeMap(){if(!this.bitmapFont)return;this.charCodeToAtlasIndex.fill(65535);let e=Array.from(this.bitmapFont.keys()).sort((t,n)=>t-n);for(let t=0;t<e.length;t++)this.charCodeToAtlasIndex[e[t]]=t}precomputeAtlasUVs(){if(!this.bitmapFont)return;let e=this.bitmapFont.size;this.atlasUVs=new Float32Array(e*4),this.cachedAtlasWidth=this.atlasColumns*this.charWidth,this.cachedAtlasHeight=Math.ceil(e/this.atlasColumns)*this.charHeight;let t=this.cachedAtlasWidth,n=this.cachedAtlasHeight,i=.5/t,s=.5/n;for(let o=0;o<e;o++){let a=o%this.atlasColumns,l=Math.floor(o/this.atlasColumns),u=(a*this.charWidth+i)/t,c=(l*this.charHeight+s)/n,d=((a+1)*this.charWidth-i)/t,h=((l+1)*this.charHeight-s)/n,f=o*4;this.atlasUVs[f]=u,this.atlasUVs[f+1]=c,this.atlasUVs[f+2]=d,this.atlasUVs[f+3]=h}}createAtlasTexture(){if(this.atlasCanvas)try{let e=this.gl,t=e.createTexture();if(!t)throw new Error("Unable to create texture");e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.atlasCanvas),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),this.atlasTexture=t}catch(e){throw console.error("[TerminalGL] ❌ Failed to create atlas texture:",e),e}}clear(){let e=this.gl;e&&e.clear(e.COLOR_BUFFER_BIT)}parseColor(e){if(e.startsWith("#")){let t=e.slice(1),n=0,i=0,s=0;return t.length===3?(n=parseInt(t[0]+t[0],16),i=parseInt(t[1]+t[1],16),s=parseInt(t[2]+t[2],16)):t.length===6&&(n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),s=parseInt(t.slice(4,6),16)),[n/255,i/255,s/255,1]}if(e.startsWith("rgb")){let t=e.match(/rgba?\(([^)]+)\)/);if(t){let n=t[1].split(",").map(i=>parseFloat(i.trim()));return[n[0]/255,n[1]/255,n[2]/255,n[3]!==void 0?n[3]:1]}}return[1,1,1,1]}setupResizeObserver(){if(!(typeof ResizeObserver>"u"))try{this.resizeObserver=new ResizeObserver(()=>{try{this.updateCanvasSize()}catch(e){console.error("[TerminalGL] ❌ Error in resize callback:",e)}}),this.resizeObserver.observe(this.parentElement),this.updateCanvasSize()}catch(e){console.error("[TerminalGL] ❌ Failed to setup ResizeObserver:",e)}}updateCanvasSize(){let e=this.parentElement.clientWidth,t=this.parentElement.clientHeight;if(e===0||t===0)return;let n=this.cols*this.cellWidth,i=this.rows*this.cellHeight;if(n===0||i===0)return;let s=e/n,o=t/i,a=Math.min(s,o),l;switch(this.scalingMode){case $t.Integer:l=Math.max(1,Math.floor(a));break;case $t.Half:l=Math.max(1,Math.floor(a*2)/2);break;case $t.Quarter:l=Math.max(1,Math.floor(a*4)/4);break;case $t.Eighth:l=Math.max(1,Math.floor(a*8)/8);break;case $t.Responsive:l=1;break;case $t.None:default:l=Math.max(.1,a);break}if(this.canvas.style.transform=`scale(${l})`,this.ambientEffectEnabled&&this.ambientEffectCanvas){let u=l*this.ambientEffectScale;this.ambientEffectCanvas.style.transform=`scale(${u})`}this.currentScale=l,this.onResizeCallback&&this.onResizeCallback(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}updateAmbientEffect(){!this.ambientEffectCanvas||!this.ambientEffectCtx||this.ambientEffectCtx.drawImage(this.canvas,0,0)}setPalette(e){let t=0;for(let n=0;n<Math.min(e.length,256);n++){let i=e[n];t=(t<<5)-t+i.r,t=(t<<5)-t+i.g,t=(t<<5)-t+i.b,t=(t<<5)-t+i.a,t=t|0}if(t!==this.paletteHash){this.paletteHash=t;for(let n=0;n<e.length&&n<256;n++){let i=e[n],s=n*4;this.paletteFloat[s]=i.r/255,this.paletteFloat[s+1]=i.g/255,this.paletteFloat[s+2]=i.b/255,this.paletteFloat[s+3]=i.a/255}this.updatePaletteTexture()}}updatePaletteTexture(){try{let e=this.gl;this.paletteTexture||(this.paletteTexture=e.createTexture()),e.bindTexture(e.TEXTURE_2D,this.paletteTexture);let t=new Uint8Array(256*4);for(let n=0;n<256;n++){let i=n*4;t[i]=this.paletteFloat[i]*255,t[i+1]=this.paletteFloat[i+1]*255,t[i+2]=this.paletteFloat[i+2]*255,t[i+3]=this.paletteFloat[i+3]*255}e.texImage2D(e.TEXTURE_2D,0,e.RGBA,256,1,0,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null)}catch(e){throw console.error("[TerminalGL] ❌ Failed to update palette texture:",e),e}}renderDisplayData(e){try{if(!this.isReady()){console.warn("[TerminalGL] ⚠️ Not ready: font not loaded yet");return}(e.width!==this.cols||e.height!==this.rows)&&this.resize(e.width,e.height),e.passes&&e.passes.length>0?this.renderMultiPass(e,e.passes):this.renderDirect(e),this.ambientEffectEnabled&&this.ambientEffectCanvas&&this.ambientEffectCtx&&this.updateAmbientEffect()}catch(t){console.error("[TerminalGL] ❌ Error rendering display data:",t)}}renderMultiPass(e,t){for(let n=0;n<t.length;n++){let i=t[n],s={id:e.id,width:e.width,height:e.height,palette:e.palette,cells:i.cells};this.renderDirect(s,n===0)}}renderDirect(e,t=!0){let n=this.gl;if(!this.staticPositionsInitialized&&!this.useInstancing&&this.precomputeStaticPositions(),t){if(this.canvasBgColor!==null){let i=this.parseColor(this.canvasBgColor);n.clearColor(i[0],i[1],i[2],i[3])}else n.clearColor(0,0,0,0);n.clear(n.COLOR_BUFFER_BIT)}this.useInstancing?this.renderInstanced(e):this.renderDirectBuffers(e)}renderInstanced(e){let t=this.gl,n=this.instancedExtension;if(!this.instanceData||this.instanceData.length===0){console.warn("[TerminalGL] ⚠️ Instance data not initialized, falling back to standard rendering"),this.renderDirectBuffers(e);return}let i=0,s=this.instanceData.length/8,o=e.width*e.height*2;if(o>s){console.error(`[TerminalGL] ❌ Instance buffer too small! Need ${o}, have ${s}. Display size: ${e.width}×${e.height}, buffer was sized for smaller terminal.`),this.renderDirectBuffers(e);return}for(let l=0;l<e.height;l++)for(let u=0;u<e.width;u++){let c=e.cells[l*e.width+u],d=c.bgColorIndex,h=c.fgColorIndex,f=this.canvasBgColor!==null&&d===255,p=c.char===" "||h===255;if(!f){if(i>=s){console.error(`[TerminalGL] ❌ Instance buffer overflow! instanceIdx=${i}, max=${s}`);break}let g=i*8;this.instanceData[g]=u,this.instanceData[g+1]=l,this.instanceData[g+2]=0,this.instanceData[g+3]=0,this.instanceData[g+4]=0,this.instanceData[g+5]=0,this.instanceData[g+6]=d,this.instanceData[g+7]=0,i++}if(!p){let g=c.char.charCodeAt(0),C=this.charCodeToAtlasIndex[g];if(C!==65535){if(i>=s){console.error(`[TerminalGL] ❌ Instance buffer overflow! instanceIdx=${i}, max=${s}`);break}let y=C*4,m=i*8;this.instanceData[m]=u,this.instanceData[m+1]=l,this.instanceData[m+2]=this.atlasUVs[y],this.instanceData[m+3]=this.atlasUVs[y+1],this.instanceData[m+4]=this.atlasUVs[y+2],this.instanceData[m+5]=this.atlasUVs[y+3],this.instanceData[m+6]=0,this.instanceData[m+7]=h,i++}}}if(i===0){console.warn("[TerminalGL] ⚠️ No instances to draw (all cells skipped)");return}t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.instanceData.subarray(0,i*8)),t.useProgram(this.program),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.enableVertexAttribArray(this.aPosition),t.vertexAttribPointer(this.aPosition,2,t.FLOAT,!1,0,0),n.vertexAttribDivisorANGLE(this.aPosition,0),t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer);let a=8*Float32Array.BYTES_PER_ELEMENT;t.enableVertexAttribArray(this.aInstanceOffset),t.vertexAttribPointer(this.aInstanceOffset,2,t.FLOAT,!1,a,0),n.vertexAttribDivisorANGLE(this.aInstanceOffset,1),t.enableVertexAttribArray(this.aInstanceUVs),t.vertexAttribPointer(this.aInstanceUVs,4,t.FLOAT,!1,a,2*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisorANGLE(this.aInstanceUVs,1),t.enableVertexAttribArray(this.aInstanceColors),t.vertexAttribPointer(this.aInstanceColors,2,t.FLOAT,!1,a,6*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisorANGLE(this.aInstanceColors,1),t.uniform2f(this.uResolution,this.canvas.width,this.canvas.height),t.uniform2f(this.uCellSize,this.cellWidth,this.cellHeight),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.atlasTexture),t.uniform1i(this.uTexture,0),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.paletteTexture),t.uniform1i(this.uPalette,1),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),n.drawElementsInstancedANGLE(t.TRIANGLES,6,t.UNSIGNED_SHORT,0,i),n.vertexAttribDivisorANGLE(this.aPosition,0),n.vertexAttribDivisorANGLE(this.aInstanceOffset,0),n.vertexAttribDivisorANGLE(this.aInstanceUVs,0),n.vertexAttribDivisorANGLE(this.aInstanceColors,0)}renderDirectBuffers(e){let t=this.gl,n=e.width*e.height,i=n*2;if(i>this.maxCells){console.error(`[TerminalGL] ❌ Buffer overflow detected! Trying to render ${i} quads but buffer capacity is ${this.maxCells}. This should not happen - resize() should have reallocated.`);return}let s=0,o=0,a=e.cells,l=n;for(let f=0;f<l;f++){let p=a[f],g=p.bgColorIndex,C=this.canvasBgColor!==null&&g===255?255:g,y=0;for(let b=0;b<4;b++)this.renderTexCoords[s++]=y,this.renderTexCoords[s++]=y,this.renderColorIndices[o++]=C;let m=p.fgColorIndex,v=p.char;if(v===" "||m===255)for(let b=0;b<4;b++)this.renderTexCoords[s++]=0,this.renderTexCoords[s++]=0,this.renderColorIndices[o++]=255;else{let b=v.charCodeAt(0),S=this.charCodeToAtlasIndex[b];if(S!==65535){let I=S*4,E=this.atlasUVs[I],U=this.atlasUVs[I+1],z=this.atlasUVs[I+2],B=this.atlasUVs[I+3];this.renderTexCoords[s++]=E,this.renderTexCoords[s++]=U,this.renderColorIndices[o++]=m,this.renderTexCoords[s++]=z,this.renderTexCoords[s++]=U,this.renderColorIndices[o++]=m,this.renderTexCoords[s++]=E,this.renderTexCoords[s++]=B,this.renderColorIndices[o++]=m,this.renderTexCoords[s++]=z,this.renderTexCoords[s++]=B,this.renderColorIndices[o++]=m}else for(let I=0;I<4;I++)this.renderTexCoords[s++]=0,this.renderTexCoords[s++]=0,this.renderColorIndices[o++]=255}}(s!==l*2*4*2||o!==l*2*4)&&console.error("[TerminalGL] ❌ Buffer index mismatch!",{texIdx:s,colorIdx:o,expected:l*2*4}),t.useProgram(this.program),this.vao&&this.vaoExtension?(this.vaoExtension.bindVertexArrayOES(this.vao),t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,s)),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,o))):(t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.enableVertexAttribArray(this.aPosition),t.vertexAttribPointer(this.aPosition,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,s)),t.enableVertexAttribArray(this.aTexCoord),t.vertexAttribPointer(this.aTexCoord,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,o)),t.enableVertexAttribArray(this.aColorIndex),t.vertexAttribPointer(this.aColorIndex,1,t.FLOAT,!1,0,0));let u=this.canvas.width,c=this.canvas.height;(this.cachedResolution[0]!==u||this.cachedResolution[1]!==c)&&(t.uniform2f(this.uResolution,u,c),this.cachedResolution[0]=u,this.cachedResolution[1]=c),this.cachedTextureUnit!==0&&(t.activeTexture(t.TEXTURE0),this.cachedTextureUnit=0),t.bindTexture(t.TEXTURE_2D,this.atlasTexture),this.cachedTextureUniform||(t.uniform1i(this.uTexture,0),this.cachedTextureUniform=!0),this.cachedPaletteUnit!==1&&(t.activeTexture(t.TEXTURE1),this.cachedPaletteUnit=1),t.bindTexture(t.TEXTURE_2D,this.paletteTexture),this.cachedPaletteUniform||(t.uniform1i(this.uPalette,1),this.cachedPaletteUniform=!0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);let d=e.width*e.height*2*6,h=this.useUint16Indices?t.UNSIGNED_SHORT:t.UNSIGNED_INT;t.drawElements(t.TRIANGLES,d,h,0)}resize(e,t){if(!Number.isInteger(e)||e<=0){console.error(`[TerminalGL] ❌ Invalid cols: ${e}. Must be positive integer.`);return}if(!Number.isInteger(t)||t<=0){console.error(`[TerminalGL] ❌ Invalid rows: ${t}. Must be positive integer.`);return}if(e===this.cols&&t===this.rows)return;let n=e*t,i=this.useInstancing?262144:this.useUint16Indices?8191:262144;if(n>i){let c=Math.floor(Math.sqrt(i));console.error(`[TerminalGL] ❌ Cannot resize to ${e}×${t} (${n} cells). Device limit: ${i} cells (max ~${c}×${c}). ${!this.useInstancing&&this.useUint16Indices?"Device lacks OES_element_index_uint extension.":""}`);return}let s=Ih.checkCompatibility();n>s.recommendedMaxCells&&console.warn(`[TerminalGL] ⚠️ Resizing to ${e}×${t} (${n} cells) exceeds recommended limit (${s.recommendedMaxCells} cells). Performance may degrade.`),this.cols=e,this.rows=t,this.staticPositionsInitialized=!1;let o=this.cols*this.rows*2,a=Math.ceil(o*1.5),l=o>this.maxCells,u=this.maxCells>a*4;if(console.warn(`[TerminalGL] 📐 resize check: cols=${e}, rows=${t}, newMaxCells=${o}, this.maxCells=${this.maxCells}, needGrow=${l}, needShrink=${u}`),l||u){let c=this.maxCells;if(this.maxCells=a,console.warn(`[TerminalGL] 📐 resize realloc: ${c} → ${this.maxCells} (needGrow=${l}, needShrink=${u})`),this.renderPositions=new Float32Array(this.maxCells*4*2),this.renderTexCoords=new Float32Array(this.maxCells*4*2),this.renderColorIndices=new Float32Array(this.maxCells*4),this.useUint16Indices?this.renderIndices=new Uint16Array(this.maxCells*6):this.renderIndices=new Uint32Array(this.maxCells*6),this.useInstancing&&this.instanceDataBuffer){this.instanceData=new Float32Array(this.maxCells*8);let g=this.gl;g.bindBuffer(g.ARRAY_BUFFER,this.instanceDataBuffer),g.bufferData(g.ARRAY_BUFFER,this.instanceData.byteLength,g.DYNAMIC_DRAW)}let d=this.gl;this.useInstancing||(d.bindBuffer(d.ARRAY_BUFFER,this.positionBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderPositions.byteLength,d.DYNAMIC_DRAW)),d.bindBuffer(d.ARRAY_BUFFER,this.texCoordBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderTexCoords.byteLength,d.DYNAMIC_DRAW),d.bindBuffer(d.ARRAY_BUFFER,this.colorIndexBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderColorIndices.byteLength,d.DYNAMIC_DRAW),this.useInstancing||(d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,this.indexBuffer),d.bufferData(d.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,d.DYNAMIC_DRAW)),this.vaoExtension&&this.vao&&(this.vaoExtension.deleteVertexArrayOES(this.vao),this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),d.bindBuffer(d.ARRAY_BUFFER,this.positionBuffer),d.enableVertexAttribArray(this.aPosition),d.vertexAttribPointer(this.aPosition,2,d.FLOAT,!1,0,0),d.bindBuffer(d.ARRAY_BUFFER,this.texCoordBuffer),d.enableVertexAttribArray(this.aTexCoord),d.vertexAttribPointer(this.aTexCoord,2,d.FLOAT,!1,0,0),d.bindBuffer(d.ARRAY_BUFFER,this.colorIndexBuffer),d.enableVertexAttribArray(this.aColorIndex),d.vertexAttribPointer(this.aColorIndex,1,d.FLOAT,!1,0,0),d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null)));let h=l?"📈 Growing":"📉 Shrinking",f=c*160/1048576,p=this.maxCells*160/1048576;console.warn(`[TerminalGL] ${h} buffers: ${f.toFixed(2)}MB → ${p.toFixed(2)}MB (${c} → ${this.maxCells} quads)`)}this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.canvas.style.width=`${this.canvas.width}px`,this.canvas.style.height=`${this.canvas.height}px`,this.ambientEffectEnabled&&this.ambientEffectCanvas&&(this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.width=`${this.canvas.width}px`,this.ambientEffectCanvas.style.height=`${this.canvas.height}px`),this.showGrid&&this.gridOverlay&&this.updateGridOverlay(),this.updateCanvasSize()}getCanvas(){return this.canvas}getGridSize(){return{cols:this.cols,rows:this.rows}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCurrentScale(){return this.currentScale}getBaseDimensions(){return{width:this.cols*this.cellWidth,height:this.rows*this.cellHeight}}setOnResizeCallback(e){this.onResizeCallback=e}clearOnResizeCallback(){this.onResizeCallback=void 0}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}setScalingMode(e){this.scalingMode!==e&&(this.scalingMode=e,this.updateCanvasSize())}getScalingMode(){return this.scalingMode}setCellSize(e,t){let n=Math.max(1,Math.min(255,Math.round(e))),i=Math.max(1,Math.min(255,Math.round(t)));this.cellWidth===n&&this.cellHeight===i||(this.cellWidth=n,this.cellHeight=i,this.charWidth=n,this.charHeight=i,this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.fontLoaded&&this.generateAtlas(),this.useInstancing&&this.initInstancedBuffers(),this.updateCanvasSize())}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getMaxCells(){return this.useInstancing?262144:this.useUint16Indices?8191:262144}setGrid(e){e.enabled?(this.gridOverlay?this.gridOverlay.setStyle({strokeColor:e.color,lineWidth:e.lineWidth}):this.gridOverlay=new du(this.containerDiv,{strokeColor:e.color??"rgba(144, 24, 24, 1)",lineWidth:e.lineWidth??1,zIndex:10}),this.showGrid=!0,this.gridOverlay.setVisible(!0),this.updateGridOverlay()):(this.showGrid=!1,this.gridOverlay&&this.gridOverlay.setVisible(!1))}isGridEnabled(){return this.showGrid}setAmbientEffect(e){typeof e=="boolean"?this.ambientEffectEnabled=e:(this.ambientEffectEnabled=!0,e.blur!==void 0&&(this.ambientEffectBlur=e.blur),e.scale!==void 0&&(this.ambientEffectScale=e.scale)),this.ambientEffectEnabled&&!this.ambientEffectCanvas&&this.createAmbientEffectCanvas(),this.ambientEffectCanvas&&(this.ambientEffectEnabled?(this.ambientEffectCanvas.style.display="block",this.ambientEffectCanvas.style.filter=`blur(${this.ambientEffectBlur}px)`,this.ambientEffectCanvas.style.transform=`scale(${this.ambientEffectScale})`,this.updateAmbientEffect()):this.ambientEffectCanvas.style.display="none")}createAmbientEffectCanvas(){this.ambientEffectCanvas||(this.ambientEffectCanvas=document.createElement("canvas"),this.ambientEffectCanvas.className="terminalgl-ambient-effect-canvas",this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.cssText=`
|
|
173
173
|
display: block !important;
|
|
174
174
|
position: absolute !important;
|
|
175
175
|
width: ${this.canvas.width}px !important;
|
|
@@ -180,7 +180,7 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
180
180
|
transform: scale(${this.ambientEffectScale}) !important;
|
|
181
181
|
pointer-events: none !important;
|
|
182
182
|
z-index: 0 !important;
|
|
183
|
-
`,this.ambientEffectCtx=this.ambientEffectCanvas.getContext("2d",{alpha:!0}),this.containerDiv.insertBefore(this.ambientEffectCanvas,this.canvas),console.warn("[TerminalGL] 🌈 ambient effect canvas created dynamically"))}isAmbientEffectEnabled(){return this.ambientEffectEnabled}getAmbientEffectConfig(){return{enabled:this.ambientEffectEnabled,blur:this.ambientEffectBlur,scale:this.ambientEffectScale}}getCols(){return this.cols}getRows(){return this.rows}isReady(){return!!(this.fontLoaded&&this.atlasTexture&&this.program)}destroy(){this.dispose()}dispose(){this.resizeObserver&&this.resizeObserver.disconnect();let e=this.gl;this.program&&e.deleteProgram(this.program),this.positionBuffer&&e.deleteBuffer(this.positionBuffer),this.texCoordBuffer&&e.deleteBuffer(this.texCoordBuffer),this.colorIndexBuffer&&e.deleteBuffer(this.colorIndexBuffer),this.indexBuffer&&e.deleteBuffer(this.indexBuffer),this.instanceDataBuffer&&e.deleteBuffer(this.instanceDataBuffer),this.atlasTexture&&e.deleteTexture(this.atlasTexture),this.paletteTexture&&e.deleteTexture(this.paletteTexture),this.vao&&this.vaoExtension&&this.vaoExtension.deleteVertexArrayOES(this.vao);let t=e.getExtension("WEBGL_lose_context");t&&t.loseContext(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv),this.canvas.width=0,this.canvas.height=0,this.ambientEffectCanvas&&(this.ambientEffectCanvas.width=0,this.ambientEffectCanvas.height=0,this.ambientEffectCanvas=null),this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.renderPositions=new Float32Array(0),this.renderTexCoords=new Float32Array(0),this.renderColorIndices=new Float32Array(0),this.renderIndices=new Uint32Array(0),this.paletteFloat=new Float32Array(0),this.atlasUVs=new Float32Array(0),this.instanceData=new Float32Array(0),this.templateQuadPositions=new Float32Array(0),this.templateQuadIndices=new Uint16Array(0)}};cr(Lw,"TerminalGL");var pk=Lw,_w=class{constructor(e,t,n,i,s){L(this,"atlases"),L(this,"charMap"),L(this,"baseCharWidth"),L(this,"baseCharHeight"),L(this,"baseCellWidth"),L(this,"baseCellHeight"),L(this,"atlasColumns",16),L(this,"font"),L(this,"SCALES",[1,2,4,8]),L(this,"colorCache",new Map),L(this,"MAX_CACHE_SIZE",512),this.font=e,this.baseCharWidth=t,this.baseCharHeight=n,this.baseCellWidth=i??t,this.baseCellHeight=s??n,this.charMap=new Map,this.atlases=new Map,this.generateAtlases()}generateAtlases(){this.atlasColumns=16;let e=0;for(let[t,n]of this.font){let i=e%this.atlasColumns,s=Math.floor(e/this.atlasColumns);this.charMap.set(t,{x:i*this.baseCharWidth,y:s*this.baseCharHeight});for(let o of this.SCALES){let a=this.getOrCreateAtlas(o),l=i*a.charWidth,u=s*a.charHeight;this.renderBitmapToAtlas(a,n,l,u)}e++}}getOrCreateAtlas(e){let t=this.atlases.get(e);if(!t){let n=this.baseCharWidth*e,i=this.baseCharHeight*e,s=Math.ceil(256/this.atlasColumns),o=document.createElement("canvas");o.width=this.atlasColumns*n,o.height=s*i;let a=o.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!a)throw new Error(`Impossible de créer le contexte 2D pour l'atlas ${e}x`);a.imageSmoothingEnabled=!1,t={canvas:o,ctx:a,scale:e,charWidth:n,charHeight:i},this.atlases.set(e,t)}return t}renderBitmapToAtlas(e,t,n,i){let s=e.scale,o=e.ctx;o.fillStyle="#ffffff";for(let a=0;a<Math.min(t.length,this.baseCharHeight);a++){let l=t[a];for(let u=0;u<this.baseCharWidth;u++){let c=1<<7-u;l&c&&o.fillRect(n+u*s,i+a*s,s,s)}}}drawChar(e,t,n,i,s,o,a){let l=this.charMap.get(t);if(!l)return;let u=`${t}:${a}`,c=this.colorCache.get(u);if(c)c.lastUsed=performance.now();else{let y=this.createColoredGlyph(t,a,l);if(!y)return;c={canvas:y,lastUsed:performance.now()},this.colorCache.set(u,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}let d=s/this.baseCellWidth,h=o/this.baseCellHeight,f=(this.baseCellWidth-this.baseCharWidth)/2*d,p=(this.baseCellHeight-this.baseCharHeight)/2*h,g=this.baseCharWidth*d,x=this.baseCharHeight*h;e.drawImage(c.canvas,n+f,i+p,g,x)}createColoredGlyph(e,t,n){let i=this.atlases.get(1);if(!i)return null;let s=i.ctx.getImageData(n.x,n.y,this.baseCharWidth,this.baseCharHeight),o=s.data,a=this.hexToRgb(t);for(let c=0;c<o.length;c+=4)o[c+3]>0&&(o[c]=a.r,o[c+1]=a.g,o[c+2]=a.b);let l=document.createElement("canvas");l.width=this.baseCharWidth,l.height=this.baseCharHeight;let u=l.getContext("2d",{alpha:!0});return u?(u.imageSmoothingEnabled=!1,u.putImageData(s,0,0),l):null}hexToRgb(e){if(e.startsWith("#")){let i=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;e=e.replace(i,(o,a,l,u)=>a+a+l+l+u+u);let s=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return s?{r:parseInt(s[1],16),g:parseInt(s[2],16),b:parseInt(s[3],16)}:{r:255,g:255,b:255}}let t=/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/.exec(e);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)};let n={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,255,0],blue:[0,0,255],yellow:[255,255,0],cyan:[0,255,255],magenta:[255,0,255]}[e.toLowerCase()];return n?{r:n[0],g:n[1],b:n[2]}:{r:255,g:255,b:255}}evictLRU(){let e=null,t=1/0;for(let[n,i]of this.colorCache)i.lastUsed<t&&(t=i.lastUsed,e=n);if(e){let n=this.colorCache.get(e);n&&(n.canvas.width=0,n.canvas.height=0),this.colorCache.delete(e)}}getAtlasCanvas(e=1){var t;return(t=this.atlases.get(e))==null?void 0:t.canvas}getAllAtlases(){return this.atlases}getCharDimensions(){return{width:this.baseCharWidth,height:this.baseCharHeight}}getCharCount(){return this.charMap.size}hasChar(e){return this.charMap.has(e)}getAtlasDimensions(e=1){let t=this.atlases.get(e);if(t)return{width:t.canvas.width,height:t.canvas.height}}toDataURL(e=1,t="image/png"){var n;return(n=this.atlases.get(e))==null?void 0:n.canvas.toDataURL(t)}getCacheStats(){return{size:this.colorCache.size,maxSize:this.MAX_CACHE_SIZE}}clearCache(){for(let e of this.colorCache.values())e.canvas.width=0,e.canvas.height=0;this.colorCache.clear()}destroy(){this.charMap.clear();for(let e of this.atlases.values())e.canvas.width=0,e.canvas.height=0;this.atlases.clear(),this.clearCache()}};cr(_w,"BitmapFontAtlas");var gk=_w,$w=class{constructor(e){L(this,"atlasCanvas",null),L(this,"atlasCtx",null),L(this,"atlasImage",null),L(this,"glyphWidth"),L(this,"glyphHeight"),L(this,"cellWidth"),L(this,"cellHeight"),L(this,"atlasBlocks"),L(this,"atlasColumns"),L(this,"maxCharCode"),L(this,"isLoaded",!1),L(this,"colorCache",new Map),L(this,"MAX_CACHE_SIZE",1024),this.glyphWidth=e.glyphWidth,this.glyphHeight=e.glyphHeight,this.cellWidth=e.cellWidth??e.glyphWidth,this.cellHeight=e.cellHeight??e.glyphHeight,this.atlasBlocks=e.atlasBlocks,this.atlasColumns=Vf(e.atlasBlocks),this.maxCharCode=jf(e.atlasBlocks)}async loadFromPNG(e){return new Promise((t,n)=>{let i=new Uint8Array(e),s=new Blob([i],{type:"image/png"}),o=URL.createObjectURL(s),a=new Image;a.onload=()=>{URL.revokeObjectURL(o);let l=this.atlasColumns*this.glyphWidth,u=this.atlasColumns*this.glyphHeight;if((a.width!==l||a.height!==u)&&console.warn(`ImageFontAtlas: Image size ${a.width}×${a.height} doesn't match expected ${l}×${u} for ${this.atlasBlocks} block(s) with ${this.glyphWidth}×${this.glyphHeight} glyphs`),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=a.width,this.atlasCanvas.height=a.height,this.atlasCtx=this.atlasCanvas.getContext("2d",{alpha:!0,willReadFrequently:!0}),!this.atlasCtx){n(new Error("Failed to create 2D context for atlas"));return}this.atlasCtx.imageSmoothingEnabled=!1,this.atlasCtx.drawImage(a,0,0),this.atlasImage=a,this.isLoaded=!0,t()},a.onerror=()=>{URL.revokeObjectURL(o),n(new Error("Failed to load PNG image for atlas"))},a.src=o})}isReady(){return this.isLoaded}getGlyphPosition(e){if(e<0||e>this.maxCharCode)return null;let{col:t,row:n}=hu(e,this.atlasBlocks);return{x:t*this.glyphWidth,y:n*this.glyphHeight}}getCharUV(e){if(e<0||e>this.maxCharCode)return null;let{col:t,row:n}=hu(e,this.atlasBlocks),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}}drawChar(e,t,n,i,s,o,a){if(!this.isLoaded||!this.atlasCanvas)return;let l=this.getGlyphPosition(t);if(!l)return;let u=`${t}:${a}`,c=this.colorCache.get(u);if(c)c.lastUsed=performance.now();else{let d=this.createColoredGlyph(t,a,l);if(!d)return;c={canvas:d,lastUsed:performance.now()},this.colorCache.set(u,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}if(e.imageSmoothingEnabled=!1,s===this.cellWidth&&o===this.cellHeight){let d=Math.floor((this.cellWidth-this.glyphWidth)/2),h=Math.floor((this.cellHeight-this.glyphHeight)/2);e.drawImage(c.canvas,Math.floor(n)+d,Math.floor(i)+h)}else{let d=s/this.cellWidth,h=o/this.cellHeight,f=Math.floor((this.cellWidth-this.glyphWidth)/2*d),p=Math.floor((this.cellHeight-this.glyphHeight)/2*h),g=Math.ceil(this.glyphWidth*d),x=Math.ceil(this.glyphHeight*h);e.drawImage(c.canvas,Math.floor(n)+f,Math.floor(i)+p,g,x)}}createColoredGlyph(e,t,n){if(!this.atlasCtx)return null;let i=this.atlasCtx.getImageData(n.x,n.y,this.glyphWidth,this.glyphHeight),s=i.data,o=this.parseColor(t);for(let u=0;u<s.length;u+=4)s[u+3]>0&&(s[u]=o.r,s[u+1]=o.g,s[u+2]=o.b);let a=document.createElement("canvas");a.width=this.glyphWidth,a.height=this.glyphHeight;let l=a.getContext("2d",{alpha:!0});return l?(l.putImageData(i,0,0),a):null}parseColor(e){if(e.startsWith("#")){let n=e.slice(1);return n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16)}}let t=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(e);return t?{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}:{r:255,g:255,b:255}}evictLRU(){let e=null,t=1/0;for(let[n,i]of this.colorCache)i.lastUsed<t&&(t=i.lastUsed,e=n);if(e){let n=this.colorCache.get(e);n&&(n.canvas.width=0,n.canvas.height=0),this.colorCache.delete(e)}}getAtlasCanvas(){return this.atlasCanvas}getAtlasImage(){return this.atlasImage}getConfig(){return{glyphWidth:this.glyphWidth,glyphHeight:this.glyphHeight,cellWidth:this.cellWidth,cellHeight:this.cellHeight,atlasBlocks:this.atlasBlocks}}getGlyphDimensions(){return{width:this.glyphWidth,height:this.glyphHeight}}getCellDimensions(){return{width:this.cellWidth,height:this.cellHeight}}getAtlasDimensions(){return{width:this.atlasColumns*this.glyphWidth,height:this.atlasColumns*this.glyphHeight}}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}isValidCharCode(e){return e>=0&&e<=this.maxCharCode}clearCache(){for(let e of this.colorCache.values())e.canvas.width=0,e.canvas.height=0;this.colorCache.clear()}getCacheStats(){return{size:this.colorCache.size,maxSize:this.MAX_CACHE_SIZE}}destroy(){this.clearCache(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=null),this.atlasCtx=null,this.atlasImage=null,this.isLoaded=!1}};cr($w,"ImageFontAtlas");var mk=$w,Nw=class{constructor(e,t={}){if(L(this,"containerDiv"),L(this,"canvas"),L(this,"ctx"),L(this,"parentElement"),L(this,"cells"),L(this,"cols",0),L(this,"rows",0),L(this,"fontSize"),L(this,"fontFamily"),L(this,"defaultFgColor"),L(this,"defaultBgColor"),L(this,"canvasBgColor"),L(this,"cellWidth"),L(this,"cellHeight"),L(this,"offsetX",0),L(this,"offsetY",0),L(this,"fontType","web"),L(this,"bitmapFont"),L(this,"bitmapAtlas"),L(this,"imageAtlas"),L(this,"bitmapCharWidth",8),L(this,"bitmapCharHeight",8),L(this,"showDebugGrid"),L(this,"debugGridColor"),L(this,"gridOverlay"),L(this,"fixedGridMode"),L(this,"fixedCols"),L(this,"fixedRows"),L(this,"cellAspectRatio"),L(this,"resizeObserver"),L(this,"imageDataBuffer"),L(this,"useImageDataRendering",!1),L(this,"paletteCache"),L(this,"scalingMode",$t.None),L(this,"currentScale",1),L(this,"customCellSize",!1),!e)throw new Error("Render: L'élément parent est requis");this.parentElement=e,this.fixedGridMode=!!(t.fixedCols&&t.fixedRows),this.fixedCols=t.fixedCols,this.fixedRows=t.fixedRows,this.cellAspectRatio=t.cellAspectRatio??1,this.cellWidth=t.cellWidth??8,this.cellHeight=t.cellHeight??8,this.fontSize=t.fontSize??12,this.fontFamily=t.fontFamily??"monospace",this.defaultFgColor=t.defaultFgColor??"#ffffff",this.defaultBgColor=t.defaultBgColor??"#000000",this.canvasBgColor=t.canvasBgColor!==void 0?t.canvasBgColor:null,this.showDebugGrid=t.showDebugGrid??!1,this.debugGridColor=t.debugGridColor??"rgba(144, 24, 24, 1)",this.scalingMode=t.scalingMode??$t.None,window.getComputedStyle(this.parentElement).position==="static"&&(this.parentElement.style.position="relative"),this.containerDiv=document.createElement("div"),this.containerDiv.className="terminal2d-container",this.containerDiv.style.cssText=`
|
|
183
|
+
`,this.ambientEffectCtx=this.ambientEffectCanvas.getContext("2d",{alpha:!0}),this.containerDiv.insertBefore(this.ambientEffectCanvas,this.canvas),console.warn("[TerminalGL] 🌈 ambient effect canvas created dynamically"))}isAmbientEffectEnabled(){return this.ambientEffectEnabled}getAmbientEffectConfig(){return{enabled:this.ambientEffectEnabled,blur:this.ambientEffectBlur,scale:this.ambientEffectScale}}getCols(){return this.cols}getRows(){return this.rows}isReady(){return!!(this.fontLoaded&&this.atlasTexture&&this.program)}destroy(){this.dispose()}dispose(){this.resizeObserver&&this.resizeObserver.disconnect();let e=this.gl;this.program&&e.deleteProgram(this.program),this.positionBuffer&&e.deleteBuffer(this.positionBuffer),this.texCoordBuffer&&e.deleteBuffer(this.texCoordBuffer),this.colorIndexBuffer&&e.deleteBuffer(this.colorIndexBuffer),this.indexBuffer&&e.deleteBuffer(this.indexBuffer),this.instanceDataBuffer&&e.deleteBuffer(this.instanceDataBuffer),this.atlasTexture&&e.deleteTexture(this.atlasTexture),this.paletteTexture&&e.deleteTexture(this.paletteTexture),this.vao&&this.vaoExtension&&this.vaoExtension.deleteVertexArrayOES(this.vao);let t=e.getExtension("WEBGL_lose_context");t&&t.loseContext(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv),this.canvas.width=0,this.canvas.height=0,this.ambientEffectCanvas&&(this.ambientEffectCanvas.width=0,this.ambientEffectCanvas.height=0,this.ambientEffectCanvas=null),this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.renderPositions=new Float32Array(0),this.renderTexCoords=new Float32Array(0),this.renderColorIndices=new Float32Array(0),this.renderIndices=new Uint32Array(0),this.paletteFloat=new Float32Array(0),this.atlasUVs=new Float32Array(0),this.instanceData=new Float32Array(0),this.templateQuadPositions=new Float32Array(0),this.templateQuadIndices=new Uint16Array(0)}};cr(jw,"TerminalGL");var xk=jw,Yw=class{constructor(e,t,n,i,s){L(this,"atlases"),L(this,"charMap"),L(this,"baseCharWidth"),L(this,"baseCharHeight"),L(this,"baseCellWidth"),L(this,"baseCellHeight"),L(this,"atlasColumns",16),L(this,"font"),L(this,"SCALES",[1,2,4,8]),L(this,"colorCache",new Map),L(this,"MAX_CACHE_SIZE",512),this.font=e,this.baseCharWidth=t,this.baseCharHeight=n,this.baseCellWidth=i??t,this.baseCellHeight=s??n,this.charMap=new Map,this.atlases=new Map,this.generateAtlases()}generateAtlases(){this.atlasColumns=16;let e=0;for(let[t,n]of this.font){let i=e%this.atlasColumns,s=Math.floor(e/this.atlasColumns);this.charMap.set(t,{x:i*this.baseCharWidth,y:s*this.baseCharHeight});for(let o of this.SCALES){let a=this.getOrCreateAtlas(o),l=i*a.charWidth,u=s*a.charHeight;this.renderBitmapToAtlas(a,n,l,u)}e++}}getOrCreateAtlas(e){let t=this.atlases.get(e);if(!t){let n=this.baseCharWidth*e,i=this.baseCharHeight*e,s=Math.ceil(256/this.atlasColumns),o=document.createElement("canvas");o.width=this.atlasColumns*n,o.height=s*i;let a=o.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!a)throw new Error(`Impossible de créer le contexte 2D pour l'atlas ${e}x`);a.imageSmoothingEnabled=!1,t={canvas:o,ctx:a,scale:e,charWidth:n,charHeight:i},this.atlases.set(e,t)}return t}renderBitmapToAtlas(e,t,n,i){let s=e.scale,o=e.ctx;o.fillStyle="#ffffff";for(let a=0;a<Math.min(t.length,this.baseCharHeight);a++){let l=t[a];for(let u=0;u<this.baseCharWidth;u++){let c=1<<7-u;l&c&&o.fillRect(n+u*s,i+a*s,s,s)}}}drawChar(e,t,n,i,s,o,a){let l=this.charMap.get(t);if(!l)return;let u=`${t}:${a}`,c=this.colorCache.get(u);if(c)c.lastUsed=performance.now();else{let y=this.createColoredGlyph(t,a,l);if(!y)return;c={canvas:y,lastUsed:performance.now()},this.colorCache.set(u,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}let d=s/this.baseCellWidth,h=o/this.baseCellHeight,f=(this.baseCellWidth-this.baseCharWidth)/2*d,p=(this.baseCellHeight-this.baseCharHeight)/2*h,g=this.baseCharWidth*d,C=this.baseCharHeight*h;e.drawImage(c.canvas,n+f,i+p,g,C)}createColoredGlyph(e,t,n){let i=this.atlases.get(1);if(!i)return null;let s=i.ctx.getImageData(n.x,n.y,this.baseCharWidth,this.baseCharHeight),o=s.data,a=this.hexToRgb(t);for(let c=0;c<o.length;c+=4)o[c+3]>0&&(o[c]=a.r,o[c+1]=a.g,o[c+2]=a.b);let l=document.createElement("canvas");l.width=this.baseCharWidth,l.height=this.baseCharHeight;let u=l.getContext("2d",{alpha:!0});return u?(u.imageSmoothingEnabled=!1,u.putImageData(s,0,0),l):null}hexToRgb(e){if(e.startsWith("#")){let i=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;e=e.replace(i,(o,a,l,u)=>a+a+l+l+u+u);let s=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return s?{r:parseInt(s[1],16),g:parseInt(s[2],16),b:parseInt(s[3],16)}:{r:255,g:255,b:255}}let t=/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/.exec(e);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)};let n={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,255,0],blue:[0,0,255],yellow:[255,255,0],cyan:[0,255,255],magenta:[255,0,255]}[e.toLowerCase()];return n?{r:n[0],g:n[1],b:n[2]}:{r:255,g:255,b:255}}evictLRU(){let e=null,t=1/0;for(let[n,i]of this.colorCache)i.lastUsed<t&&(t=i.lastUsed,e=n);if(e){let n=this.colorCache.get(e);n&&(n.canvas.width=0,n.canvas.height=0),this.colorCache.delete(e)}}getAtlasCanvas(e=1){var t;return(t=this.atlases.get(e))==null?void 0:t.canvas}getAllAtlases(){return this.atlases}getCharDimensions(){return{width:this.baseCharWidth,height:this.baseCharHeight}}getCharCount(){return this.charMap.size}hasChar(e){return this.charMap.has(e)}getAtlasDimensions(e=1){let t=this.atlases.get(e);if(t)return{width:t.canvas.width,height:t.canvas.height}}toDataURL(e=1,t="image/png"){var n;return(n=this.atlases.get(e))==null?void 0:n.canvas.toDataURL(t)}getCacheStats(){return{size:this.colorCache.size,maxSize:this.MAX_CACHE_SIZE}}clearCache(){for(let e of this.colorCache.values())e.canvas.width=0,e.canvas.height=0;this.colorCache.clear()}destroy(){this.charMap.clear();for(let e of this.atlases.values())e.canvas.width=0,e.canvas.height=0;this.atlases.clear(),this.clearCache()}};cr(Yw,"BitmapFontAtlas");var Ik=Yw,Gw=class{constructor(e){L(this,"atlasCanvas",null),L(this,"atlasCtx",null),L(this,"atlasImage",null),L(this,"glyphWidth"),L(this,"glyphHeight"),L(this,"cellWidth"),L(this,"cellHeight"),L(this,"atlasBlocks"),L(this,"atlasColumns"),L(this,"maxCharCode"),L(this,"isLoaded",!1),L(this,"colorCache",new Map),L(this,"MAX_CACHE_SIZE",1024),this.glyphWidth=e.glyphWidth,this.glyphHeight=e.glyphHeight,this.cellWidth=e.cellWidth??e.glyphWidth,this.cellHeight=e.cellHeight??e.glyphHeight,this.atlasBlocks=e.atlasBlocks,this.atlasColumns=Gf(e.atlasBlocks),this.maxCharCode=Xf(e.atlasBlocks)}async loadFromPNG(e){return new Promise((t,n)=>{let i=new Uint8Array(e),s=new Blob([i],{type:"image/png"}),o=URL.createObjectURL(s),a=new Image;a.onload=()=>{URL.revokeObjectURL(o);let l=this.atlasColumns*this.glyphWidth,u=this.atlasColumns*this.glyphHeight;if((a.width!==l||a.height!==u)&&console.warn(`ImageFontAtlas: Image size ${a.width}×${a.height} doesn't match expected ${l}×${u} for ${this.atlasBlocks} block(s) with ${this.glyphWidth}×${this.glyphHeight} glyphs`),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=a.width,this.atlasCanvas.height=a.height,this.atlasCtx=this.atlasCanvas.getContext("2d",{alpha:!0,willReadFrequently:!0}),!this.atlasCtx){n(new Error("Failed to create 2D context for atlas"));return}this.atlasCtx.imageSmoothingEnabled=!1,this.atlasCtx.drawImage(a,0,0),this.atlasImage=a,this.isLoaded=!0,t()},a.onerror=()=>{URL.revokeObjectURL(o),n(new Error("Failed to load PNG image for atlas"))},a.src=o})}isReady(){return this.isLoaded}getGlyphPosition(e){if(e<0||e>this.maxCharCode)return null;let{col:t,row:n}=hu(e,this.atlasBlocks);return{x:t*this.glyphWidth,y:n*this.glyphHeight}}getCharUV(e){if(e<0||e>this.maxCharCode)return null;let{col:t,row:n}=hu(e,this.atlasBlocks),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}}drawChar(e,t,n,i,s,o,a){if(!this.isLoaded||!this.atlasCanvas)return;let l=this.getGlyphPosition(t);if(!l)return;let u=`${t}:${a}`,c=this.colorCache.get(u);if(c)c.lastUsed=performance.now();else{let d=this.createColoredGlyph(t,a,l);if(!d)return;c={canvas:d,lastUsed:performance.now()},this.colorCache.set(u,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}if(e.imageSmoothingEnabled=!1,s===this.cellWidth&&o===this.cellHeight){let d=Math.floor((this.cellWidth-this.glyphWidth)/2),h=Math.floor((this.cellHeight-this.glyphHeight)/2);e.drawImage(c.canvas,Math.floor(n)+d,Math.floor(i)+h)}else{let d=s/this.cellWidth,h=o/this.cellHeight,f=Math.floor((this.cellWidth-this.glyphWidth)/2*d),p=Math.floor((this.cellHeight-this.glyphHeight)/2*h),g=Math.ceil(this.glyphWidth*d),C=Math.ceil(this.glyphHeight*h);e.drawImage(c.canvas,Math.floor(n)+f,Math.floor(i)+p,g,C)}}createColoredGlyph(e,t,n){if(!this.atlasCtx)return null;let i=this.atlasCtx.getImageData(n.x,n.y,this.glyphWidth,this.glyphHeight),s=i.data,o=this.parseColor(t);for(let u=0;u<s.length;u+=4)s[u+3]>0&&(s[u]=o.r,s[u+1]=o.g,s[u+2]=o.b);let a=document.createElement("canvas");a.width=this.glyphWidth,a.height=this.glyphHeight;let l=a.getContext("2d",{alpha:!0});return l?(l.putImageData(i,0,0),a):null}parseColor(e){if(e.startsWith("#")){let n=e.slice(1);return n.length===3&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]),{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16)}}let t=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(e);return t?{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}:{r:255,g:255,b:255}}evictLRU(){let e=null,t=1/0;for(let[n,i]of this.colorCache)i.lastUsed<t&&(t=i.lastUsed,e=n);if(e){let n=this.colorCache.get(e);n&&(n.canvas.width=0,n.canvas.height=0),this.colorCache.delete(e)}}getAtlasCanvas(){return this.atlasCanvas}getAtlasImage(){return this.atlasImage}getConfig(){return{glyphWidth:this.glyphWidth,glyphHeight:this.glyphHeight,cellWidth:this.cellWidth,cellHeight:this.cellHeight,atlasBlocks:this.atlasBlocks}}getGlyphDimensions(){return{width:this.glyphWidth,height:this.glyphHeight}}getCellDimensions(){return{width:this.cellWidth,height:this.cellHeight}}getAtlasDimensions(){return{width:this.atlasColumns*this.glyphWidth,height:this.atlasColumns*this.glyphHeight}}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}isValidCharCode(e){return e>=0&&e<=this.maxCharCode}clearCache(){for(let e of this.colorCache.values())e.canvas.width=0,e.canvas.height=0;this.colorCache.clear()}getCacheStats(){return{size:this.colorCache.size,maxSize:this.MAX_CACHE_SIZE}}destroy(){this.clearCache(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=null),this.atlasCtx=null,this.atlasImage=null,this.isLoaded=!1}};cr(Gw,"ImageFontAtlas");var Sk=Gw,Xw=class{constructor(e,t={}){if(L(this,"containerDiv"),L(this,"canvas"),L(this,"ctx"),L(this,"parentElement"),L(this,"cells"),L(this,"cols",0),L(this,"rows",0),L(this,"fontSize"),L(this,"fontFamily"),L(this,"defaultFgColor"),L(this,"defaultBgColor"),L(this,"canvasBgColor"),L(this,"cellWidth"),L(this,"cellHeight"),L(this,"offsetX",0),L(this,"offsetY",0),L(this,"fontType","web"),L(this,"bitmapFont"),L(this,"bitmapAtlas"),L(this,"imageAtlas"),L(this,"bitmapCharWidth",8),L(this,"bitmapCharHeight",8),L(this,"showDebugGrid"),L(this,"debugGridColor"),L(this,"gridOverlay"),L(this,"fixedGridMode"),L(this,"fixedCols"),L(this,"fixedRows"),L(this,"cellAspectRatio"),L(this,"resizeObserver"),L(this,"imageDataBuffer"),L(this,"useImageDataRendering",!1),L(this,"paletteCache"),L(this,"scalingMode",$t.None),L(this,"currentScale",1),L(this,"customCellSize",!1),!e)throw new Error("Render: L'élément parent est requis");this.parentElement=e,this.fixedGridMode=!!(t.fixedCols&&t.fixedRows),this.fixedCols=t.fixedCols,this.fixedRows=t.fixedRows,this.cellAspectRatio=t.cellAspectRatio??1,this.cellWidth=t.cellWidth??8,this.cellHeight=t.cellHeight??8,this.fontSize=t.fontSize??12,this.fontFamily=t.fontFamily??"monospace",this.defaultFgColor=t.defaultFgColor??"#ffffff",this.defaultBgColor=t.defaultBgColor??"#000000",this.canvasBgColor=t.canvasBgColor!==void 0?t.canvasBgColor:null,this.showDebugGrid=t.showDebugGrid??!1,this.debugGridColor=t.debugGridColor??"rgba(144, 24, 24, 1)",this.scalingMode=t.scalingMode??$t.None,window.getComputedStyle(this.parentElement).position==="static"&&(this.parentElement.style.position="relative"),this.containerDiv=document.createElement("div"),this.containerDiv.className="terminal2d-container",this.containerDiv.style.cssText=`
|
|
184
184
|
position: absolute !important;
|
|
185
185
|
top: 0 !important;
|
|
186
186
|
left: 0 !important;
|
|
@@ -209,7 +209,7 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
209
209
|
backface-visibility: hidden !important;
|
|
210
210
|
pointer-events: auto !important;
|
|
211
211
|
touch-action: none !important;
|
|
212
|
-
`,this.fontType==="web"&&(this.fontSize=Math.round(this.cellHeight/14*12)),this.offsetX=0,this.offsetY=0}createEmptyGrid(){let e=[];for(let t=0;t<this.rows;t++){let n=[];for(let i=0;i<this.cols;i++)n.push({char:" ",fgColor:this.defaultFgColor,bgColor:this.defaultBgColor});e.push(n)}return e}enableAutoResize(){this.resizeObserver=new ResizeObserver(()=>{let e=this.cols,t=this.rows;if(this.calculateGridSize(),this.cols!==e||this.rows!==t){let n=this.cells;this.cells=this.createEmptyGrid();let i=Math.min(e,this.cols),s=Math.min(t,this.rows);for(let o=0;o<s;o++)for(let a=0;a<i;a++)this.cells[o][a]=n[o][a]}this.render()}),this.resizeObserver.observe(this.parentElement)}setCell(e,t,n,i,s){if(t<0||t>=this.rows||e<0||e>=this.cols)return;let o=n&&typeof n=="string"?n.charAt(0):" ";this.cells[t][e]={char:o,fgColor:i??this.defaultFgColor,bgColor:s??this.defaultBgColor}}getCell(e,t){return t<0||t>=this.rows||e<0||e>=this.cols?null:this.cells[t][e]}write(e,t,n,i,s){for(let o=0;o<n.length;o++)this.setCell(e+o,t,n[o],i,s)}fillRect(e,t,n,i,s=" ",o,a){for(let l=t;l<t+i;l++)for(let u=e;u<e+n;u++)this.setCell(u,l,s,o,a)}clear(){this.cells=this.createEmptyGrid()}setFromArray(e){let t=e.width*e.height;if(e.cells.length!==t)throw new Error(`Invalid array length: expected ${t} (${e.width}×${e.height}), got ${e.cells.length}`);let n=0;for(let i=0;i<e.height;i++)for(let s=0;s<e.width;s++){let o=e.cells[n];i<this.rows&&s<this.cols&&this.setCell(s,i,o.char,o.fgColor,o.bgColor),n++}}render(){if(this.fontType==="bitmap"&&this.bitmapFont&&this.useImageDataRendering){this.renderWithImageData();return}this.renderClassic()}renderWithImageData(){if(!this.bitmapFont)return;let e=this.cols*this.bitmapCharWidth,t=this.rows*this.bitmapCharHeight;(!this.imageDataBuffer||this.imageDataBuffer.width!==e||this.imageDataBuffer.height!==t)&&(this.imageDataBuffer=this.ctx.createImageData(e,t));let n=this.imageDataBuffer.data;for(let a=0;a<this.rows;a++)for(let l=0;l<this.cols;l++){let u=this.cells[a][l],c=this.parseColorToRGB(u.bgColor),d=this.parseColorToRGB(u.fgColor),h=u.char.charCodeAt(0),f=this.bitmapFont.get(h);for(let p=0;p<this.bitmapCharHeight;p++)for(let g=0;g<this.bitmapCharWidth;g++){let x=l*this.bitmapCharWidth+g,y=((a*this.bitmapCharHeight+p)*e+x)*4,m=!1;if(f&&p<f.length){let v=f[p],b=1<<7-g;m=(v&b)!==0}m?(n[y]=d.r,n[y+1]=d.g,n[y+2]=d.b,n[y+3]=d.a):(n[y]=c.r,n[y+1]=c.g,n[y+2]=c.b,n[y+3]=c.a)}}this.canvasBgColor!==null?(this.ctx.fillStyle=this.canvasBgColor,this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.imageSmoothingEnabled=!1,this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges";let i=document.createElement("canvas");i.width=e,i.height=t,i.getContext("2d").putImageData(this.imageDataBuffer,0,0);let s=this.cols*this.cellWidth,o=this.rows*this.cellHeight;this.ctx.drawImage(i,0,0,e,t,this.offsetX,this.offsetY,s,o),this.showDebugGrid&&this.drawDebugGrid()}parseColorToRGB(e){let t=/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/.exec(e);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};if(e.startsWith("#")){let i=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;e=e.replace(i,(o,a,l,u)=>a+a+l+l+u+u);let s=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(s)return{r:parseInt(s[1],16),g:parseInt(s[2],16),b:parseInt(s[3],16),a:255}}let n={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,255,0],blue:[0,0,255],yellow:[255,255,0],cyan:[0,255,255],magenta:[255,0,255],transparent:[0,0,0]}[e.toLowerCase()];return n?{r:n[0],g:n[1],b:n[2],a:e==="transparent"?0:255}:{r:255,g:255,b:255,a:255}}renderClassic(){this.canvasBgColor!==null?(this.ctx.fillStyle=this.canvasBgColor,this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.fontType==="bitmap"||this.fontType==="image"?(this.ctx.imageSmoothingEnabled=!1,this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges"):(this.ctx.imageSmoothingEnabled=!0,this.ctx.imageSmoothingQuality="high",this.canvas.style.imageRendering="auto",this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.textBaseline="top",this.ctx.textRendering="optimizeLegibility");for(let e=0;e<this.rows;e++)for(let t=0;t<this.cols;t++){let n=this.cells[e][t],i=Math.floor(this.offsetX+t*this.cellWidth),s=Math.floor(this.offsetY+e*this.cellHeight),o=Math.floor(this.offsetX+(t+1)*this.cellWidth),a=Math.floor(this.offsetY+(e+1)*this.cellHeight),l=o-i,u=a-s;if((this.canvasBgColor!==null||n.bgColor!==this.defaultBgColor)&&(this.ctx.fillStyle=n.bgColor,this.ctx.fillRect(i,s,l,u)),n.char!==" ")if(this.fontType==="image"&&this.imageAtlas){let c=n.char.charCodeAt(0);this.imageAtlas.drawChar(this.ctx,c,i,s,l,u,n.fgColor)}else if(this.fontType==="bitmap"&&this.bitmapFont)this.drawBitmapChar(n.char,i,s,l,u,n.fgColor);else{this.ctx.fillStyle=n.fgColor;let c=i+(l-this.ctx.measureText(n.char).width)/2,d=s+(u-this.fontSize)/2;this.ctx.fillText(n.char,c,d)}}this.showDebugGrid&&this.drawDebugGrid()}drawBitmapChar(e,t,n,i,s,o){let a=e.charCodeAt(0);if(this.bitmapAtlas){this.bitmapAtlas.drawChar(this.ctx,a,t,n,i,s,o);return}if(!this.bitmapFont)return;let l=this.bitmapFont.get(a);if(!l)return;let u=i/this.bitmapCharWidth,c=s/this.bitmapCharHeight;this.ctx.fillStyle=o;for(let d=0;d<Math.min(l.length,this.bitmapCharHeight);d++){let h=l[d],f=n+d*c,p=n+(d+1)*c;for(let g=0;g<this.bitmapCharWidth;g++){let x=1<<7-g;if(h&x){let y=t+g*u,m=t+(g+1)*u;this.ctx.fillRect(y,f,m-y,p-f)}}}}drawDebugGrid(){if(!this.gridOverlay)return;let e=this.parentElement.clientWidth||800,t=this.parentElement.clientHeight||600;this.gridOverlay.update(this.cols,this.rows,this.cellWidth,this.cellHeight,e,t,this.offsetX,this.offsetY)}getCanvas(){return this.canvas}getContext(){return this.ctx}getDimensions(){return{cols:this.cols,rows:this.rows}}getCellDimensions(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCurrentScale(){return this.currentScale}getScalingMode(){return this.scalingMode}getOffsets(){return{offsetX:this.offsetX,offsetY:this.offsetY}}setDebugGrid(e){this.showDebugGrid=e,e&&!this.gridOverlay?(this.gridOverlay=new du(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,zIndex:10}),this.drawDebugGrid()):!e&&this.gridOverlay?(this.gridOverlay.destroy(),this.gridOverlay=void 0):e&&this.gridOverlay&&this.gridOverlay.setVisible(!0)}setCanvasBackgroundColor(e){this.canvasBgColor=e}getCanvasBackgroundColor(){return this.canvasBgColor}setFixedGrid(e,t,n){this.fixedGridMode=!0,this.fixedCols=e,this.fixedRows=t,n!==void 0&&(this.cellAspectRatio=n);let i=this.cols,s=this.rows,o=this.cells;if(this.calculateGridSize(),this.cols!==i||this.rows!==s){this.cells=this.createEmptyGrid();let a=Math.min(i,this.cols),l=Math.min(s,this.rows);for(let u=0;u<l;u++)for(let c=0;c<a;c++)this.cells[u][c]=o[u][c]}this.render()}setAdaptiveGrid(e,t){this.fixedGridMode=!1,this.fixedCols=void 0,this.fixedRows=void 0,e!==void 0&&(this.cellWidth=e),t!==void 0&&(this.cellHeight=t);let n=this.cols,i=this.rows,s=this.cells;if(this.calculateGridSize(),this.cols!==n||this.rows!==i){this.cells=this.createEmptyGrid();let o=Math.min(n,this.cols),a=Math.min(i,this.rows);for(let l=0;l<a;l++)for(let u=0;u<o;u++)this.cells[l][u]=s[l][u]}this.render()}isFixedGridMode(){return this.fixedGridMode}setDebugGridColor(e){this.debugGridColor=e}isDebugGridEnabled(){return this.showDebugGrid}setImageDataRendering(e){this.useImageDataRendering=e,e&&this.fontType==="bitmap"?console.warn("[Render] ImageData rendering enabled (optimized for benchmarks)"):e&&(console.warn("[Render] ImageData rendering requires bitmap font, keeping classic mode"),this.useImageDataRendering=!1)}isImageDataRenderingEnabled(){return this.useImageDataRendering}setWebFont(e,t){this.fontType="web",this.fontFamily=e,t!==void 0&&(this.fontSize=t),this.bitmapFont=void 0,this.bitmapAtlas=void 0,this.useImageDataRendering=!1,this.calculateGridSize(),this.cells=this.createEmptyGrid()}setBitmapFont(e,t,n,i,s){this.fontType="bitmap",this.bitmapFont=e,this.bitmapCharWidth=t,this.bitmapCharHeight=n,this.bitmapAtlas=new gk(e,t,n,i,s),this.cellWidth=i,this.cellHeight=s,this.calculateGridSize(),this.cells=this.createEmptyGrid()}async setImageFont(e,t,n,i,s,o){this.fontType="image",this.imageAtlas=new mk({glyphWidth:t,glyphHeight:n,cellWidth:i,cellHeight:s,atlasBlocks:o}),await this.imageAtlas.loadFromPNG(e),this.cellWidth=i,this.cellHeight=s,this.bitmapCharWidth=t,this.bitmapCharHeight=n,this.calculateGridSize(),this.cells=this.createEmptyGrid()}getFontType(){return this.fontType}getBitmapFont(){return this.bitmapFont}getBitmapCharDimensions(){return this.fontType!=="bitmap"?null:{width:this.bitmapCharWidth,height:this.bitmapCharHeight}}setPalette(e){this.paletteCache=e}renderDisplayData(e){if(!e||!e.cells||e.cells.length===0){console.warn("[Terminal2D] Empty display data");return}if(e.width===0||e.height===0){console.warn("[Terminal2D] Invalid display dimensions:",e.width,e.height);return}(e.width!==this.cols||e.height!==this.rows)&&this.setFixedGrid(e.width,e.height,this.cellAspectRatio);let t=this.paletteCache??e.palette;if(!t||t.length===0){console.error("[Terminal2D] No palette available (neither cached nor in display)");return}let n=cr(i=>{if(i==null||isNaN(i))return console.warn("[Terminal2D] Invalid palette index (undefined/null/NaN):",i),this.defaultFgColor;if(i===255)return"rgba(0, 0, 0, 0)";if(i<0||i>=t.length)return console.warn(`[Terminal2D] Invalid palette index: ${i}`),this.defaultFgColor;let s=t[i];return!s||typeof s.r!="number"?(console.warn(`[Terminal2D] Corrupted palette entry at index ${i}:`,s),this.defaultFgColor):`rgba(${s.r}, ${s.g}, ${s.b}, ${s.a/255})`},"convertColor");for(let i=0;i<e.height&&i<this.rows;i++)for(let s=0;s<e.width&&s<this.cols;s++){let o=i*e.width+s;if(o>=e.cells.length)break;let a=e.cells[o];if(!a)continue;let l=n(a.fgColorIndex),u=n(a.bgColorIndex);this.setCell(s,i,a.char??" ",l,u)}this.render()}isReady(){return!0}getCols(){return this.cols}getRows(){return this.rows}resize(e,t){this.setFixedGrid(e,t)}setScalingMode(e){if(this.scalingMode===e)return;let t=this.cols,n=this.rows;if(this.scalingMode=e,this.calculateGridSize(),this.cols!==t||this.rows!==n){let i=this.cells;if(this.cells=this.createEmptyGrid(),i&&i.length>0){let s=Math.min(t,this.cols),o=Math.min(n,this.rows);for(let a=0;a<o;a++)for(let l=0;l<s;l++)i[a]&&i[a][l]&&(this.cells[a][l]=i[a][l])}}this.render()}setCellSize(e,t){let n=Math.max(1,Math.min(255,Math.round(e))),i=Math.max(1,Math.min(255,Math.round(t)));if(this.cellWidth===n&&this.cellHeight===i)return;let s=this.cols,o=this.rows;if(this.cellWidth=n,this.cellHeight=i,this.customCellSize=!0,this.calculateGridSize(),this.cols!==s||this.rows!==o){let a=this.cells;if(this.cells=this.createEmptyGrid(),a&&a.length>0){let l=Math.min(s,this.cols),u=Math.min(o,this.rows);for(let c=0;c<u;c++)for(let d=0;d<l;d++)a[c]&&a[c][d]&&(this.cells[c][d]=a[c][d])}}this.render()}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}getMaxCells(){return 65536}destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0),this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}};cr(Nw,"Terminal2D");var yk=Nw,Ww=class{constructor(e,t={}){L(this,"container"),L(this,"overlayDiv",null),L(this,"button",null),L(this,"options"),L(this,"started",!1),L(this,"onStartCallback"),this.container=e,this.options={buttonText:t.buttonText??"Click to Start",onStart:t.onStart??(()=>{}),backgroundColor:t.backgroundColor??"rgba(0, 0, 0, 0.8)",buttonColor:t.buttonColor??"#4a90d9",buttonHoverColor:t.buttonHoverColor??"#357abd",buttonTextColor:t.buttonTextColor??"#ffffff",zIndex:t.zIndex??1e3},this.onStartCallback=t.onStart,this.createOverlay()}createOverlay(){let e=window.getComputedStyle(this.container).position;e!=="relative"&&e!=="absolute"&&e!=="fixed"&&(this.container.style.position="relative"),this.overlayDiv=document.createElement("div"),this.overlayDiv.className="utsp-autoplay-overlay",this.overlayDiv.style.cssText=`
|
|
212
|
+
`,this.fontType==="web"&&(this.fontSize=Math.round(this.cellHeight/14*12)),this.offsetX=0,this.offsetY=0}createEmptyGrid(){let e=[];for(let t=0;t<this.rows;t++){let n=[];for(let i=0;i<this.cols;i++)n.push({char:" ",fgColor:this.defaultFgColor,bgColor:this.defaultBgColor});e.push(n)}return e}enableAutoResize(){this.resizeObserver=new ResizeObserver(()=>{let e=this.cols,t=this.rows;if(this.calculateGridSize(),this.cols!==e||this.rows!==t){let n=this.cells;this.cells=this.createEmptyGrid();let i=Math.min(e,this.cols),s=Math.min(t,this.rows);for(let o=0;o<s;o++)for(let a=0;a<i;a++)this.cells[o][a]=n[o][a]}this.render()}),this.resizeObserver.observe(this.parentElement)}setCell(e,t,n,i,s){if(t<0||t>=this.rows||e<0||e>=this.cols)return;let o=n&&typeof n=="string"?n.charAt(0):" ";this.cells[t][e]={char:o,fgColor:i??this.defaultFgColor,bgColor:s??this.defaultBgColor}}getCell(e,t){return t<0||t>=this.rows||e<0||e>=this.cols?null:this.cells[t][e]}write(e,t,n,i,s){for(let o=0;o<n.length;o++)this.setCell(e+o,t,n[o],i,s)}fillRect(e,t,n,i,s=" ",o,a){for(let l=t;l<t+i;l++)for(let u=e;u<e+n;u++)this.setCell(u,l,s,o,a)}clear(){this.cells=this.createEmptyGrid()}setFromArray(e){let t=e.width*e.height;if(e.cells.length!==t)throw new Error(`Invalid array length: expected ${t} (${e.width}×${e.height}), got ${e.cells.length}`);let n=0;for(let i=0;i<e.height;i++)for(let s=0;s<e.width;s++){let o=e.cells[n];i<this.rows&&s<this.cols&&this.setCell(s,i,o.char,o.fgColor,o.bgColor),n++}}render(){if(this.fontType==="bitmap"&&this.bitmapFont&&this.useImageDataRendering){this.renderWithImageData();return}this.renderClassic()}renderWithImageData(){if(!this.bitmapFont)return;let e=this.cols*this.bitmapCharWidth,t=this.rows*this.bitmapCharHeight;(!this.imageDataBuffer||this.imageDataBuffer.width!==e||this.imageDataBuffer.height!==t)&&(this.imageDataBuffer=this.ctx.createImageData(e,t));let n=this.imageDataBuffer.data;for(let a=0;a<this.rows;a++)for(let l=0;l<this.cols;l++){let u=this.cells[a][l],c=this.parseColorToRGB(u.bgColor),d=this.parseColorToRGB(u.fgColor),h=u.char.charCodeAt(0),f=this.bitmapFont.get(h);for(let p=0;p<this.bitmapCharHeight;p++)for(let g=0;g<this.bitmapCharWidth;g++){let C=l*this.bitmapCharWidth+g,y=((a*this.bitmapCharHeight+p)*e+C)*4,m=!1;if(f&&p<f.length){let v=f[p],b=1<<7-g;m=(v&b)!==0}m?(n[y]=d.r,n[y+1]=d.g,n[y+2]=d.b,n[y+3]=d.a):(n[y]=c.r,n[y+1]=c.g,n[y+2]=c.b,n[y+3]=c.a)}}this.canvasBgColor!==null?(this.ctx.fillStyle=this.canvasBgColor,this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.imageSmoothingEnabled=!1,this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges";let i=document.createElement("canvas");i.width=e,i.height=t,i.getContext("2d").putImageData(this.imageDataBuffer,0,0);let s=this.cols*this.cellWidth,o=this.rows*this.cellHeight;this.ctx.drawImage(i,0,0,e,t,this.offsetX,this.offsetY,s,o),this.showDebugGrid&&this.drawDebugGrid()}parseColorToRGB(e){let t=/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/.exec(e);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};if(e.startsWith("#")){let i=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;e=e.replace(i,(o,a,l,u)=>a+a+l+l+u+u);let s=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(s)return{r:parseInt(s[1],16),g:parseInt(s[2],16),b:parseInt(s[3],16),a:255}}let n={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,255,0],blue:[0,0,255],yellow:[255,255,0],cyan:[0,255,255],magenta:[255,0,255],transparent:[0,0,0]}[e.toLowerCase()];return n?{r:n[0],g:n[1],b:n[2],a:e==="transparent"?0:255}:{r:255,g:255,b:255,a:255}}renderClassic(){this.canvasBgColor!==null?(this.ctx.fillStyle=this.canvasBgColor,this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.fontType==="bitmap"||this.fontType==="image"?(this.ctx.imageSmoothingEnabled=!1,this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges"):(this.ctx.imageSmoothingEnabled=!0,this.ctx.imageSmoothingQuality="high",this.canvas.style.imageRendering="auto",this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.textBaseline="top",this.ctx.textRendering="optimizeLegibility");for(let e=0;e<this.rows;e++)for(let t=0;t<this.cols;t++){let n=this.cells[e][t],i=Math.floor(this.offsetX+t*this.cellWidth),s=Math.floor(this.offsetY+e*this.cellHeight),o=Math.floor(this.offsetX+(t+1)*this.cellWidth),a=Math.floor(this.offsetY+(e+1)*this.cellHeight),l=o-i,u=a-s;if((this.canvasBgColor!==null||n.bgColor!==this.defaultBgColor)&&(this.ctx.fillStyle=n.bgColor,this.ctx.fillRect(i,s,l,u)),n.char!==" ")if(this.fontType==="image"&&this.imageAtlas){let c=n.char.charCodeAt(0);this.imageAtlas.drawChar(this.ctx,c,i,s,l,u,n.fgColor)}else if(this.fontType==="bitmap"&&this.bitmapFont)this.drawBitmapChar(n.char,i,s,l,u,n.fgColor);else{this.ctx.fillStyle=n.fgColor;let c=i+(l-this.ctx.measureText(n.char).width)/2,d=s+(u-this.fontSize)/2;this.ctx.fillText(n.char,c,d)}}this.showDebugGrid&&this.drawDebugGrid()}drawBitmapChar(e,t,n,i,s,o){let a=e.charCodeAt(0);if(this.bitmapAtlas){this.bitmapAtlas.drawChar(this.ctx,a,t,n,i,s,o);return}if(!this.bitmapFont)return;let l=this.bitmapFont.get(a);if(!l)return;let u=i/this.bitmapCharWidth,c=s/this.bitmapCharHeight;this.ctx.fillStyle=o;for(let d=0;d<Math.min(l.length,this.bitmapCharHeight);d++){let h=l[d],f=n+d*c,p=n+(d+1)*c;for(let g=0;g<this.bitmapCharWidth;g++){let C=1<<7-g;if(h&C){let y=t+g*u,m=t+(g+1)*u;this.ctx.fillRect(y,f,m-y,p-f)}}}}drawDebugGrid(){if(!this.gridOverlay)return;let e=this.parentElement.clientWidth||800,t=this.parentElement.clientHeight||600;this.gridOverlay.update(this.cols,this.rows,this.cellWidth,this.cellHeight,e,t,this.offsetX,this.offsetY)}getCanvas(){return this.canvas}getContext(){return this.ctx}getDimensions(){return{cols:this.cols,rows:this.rows}}getCellDimensions(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCurrentScale(){return this.currentScale}getScalingMode(){return this.scalingMode}getOffsets(){return{offsetX:this.offsetX,offsetY:this.offsetY}}setDebugGrid(e){this.showDebugGrid=e,e&&!this.gridOverlay?(this.gridOverlay=new du(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,zIndex:10}),this.drawDebugGrid()):!e&&this.gridOverlay?(this.gridOverlay.destroy(),this.gridOverlay=void 0):e&&this.gridOverlay&&this.gridOverlay.setVisible(!0)}setCanvasBackgroundColor(e){this.canvasBgColor=e}getCanvasBackgroundColor(){return this.canvasBgColor}setFixedGrid(e,t,n){this.fixedGridMode=!0,this.fixedCols=e,this.fixedRows=t,n!==void 0&&(this.cellAspectRatio=n);let i=this.cols,s=this.rows,o=this.cells;if(this.calculateGridSize(),this.cols!==i||this.rows!==s){this.cells=this.createEmptyGrid();let a=Math.min(i,this.cols),l=Math.min(s,this.rows);for(let u=0;u<l;u++)for(let c=0;c<a;c++)this.cells[u][c]=o[u][c]}this.render()}setAdaptiveGrid(e,t){this.fixedGridMode=!1,this.fixedCols=void 0,this.fixedRows=void 0,e!==void 0&&(this.cellWidth=e),t!==void 0&&(this.cellHeight=t);let n=this.cols,i=this.rows,s=this.cells;if(this.calculateGridSize(),this.cols!==n||this.rows!==i){this.cells=this.createEmptyGrid();let o=Math.min(n,this.cols),a=Math.min(i,this.rows);for(let l=0;l<a;l++)for(let u=0;u<o;u++)this.cells[l][u]=s[l][u]}this.render()}isFixedGridMode(){return this.fixedGridMode}setDebugGridColor(e){this.debugGridColor=e}isDebugGridEnabled(){return this.showDebugGrid}setImageDataRendering(e){this.useImageDataRendering=e,e&&this.fontType==="bitmap"?console.warn("[Render] ImageData rendering enabled (optimized for benchmarks)"):e&&(console.warn("[Render] ImageData rendering requires bitmap font, keeping classic mode"),this.useImageDataRendering=!1)}isImageDataRenderingEnabled(){return this.useImageDataRendering}setWebFont(e,t){this.fontType="web",this.fontFamily=e,t!==void 0&&(this.fontSize=t),this.bitmapFont=void 0,this.bitmapAtlas=void 0,this.useImageDataRendering=!1,this.calculateGridSize(),this.cells=this.createEmptyGrid()}setBitmapFont(e,t,n,i,s){this.fontType="bitmap",this.bitmapFont=e,this.bitmapCharWidth=t,this.bitmapCharHeight=n,this.bitmapAtlas=new Ik(e,t,n,i,s),this.cellWidth=i,this.cellHeight=s,this.calculateGridSize(),this.cells=this.createEmptyGrid()}async setImageFont(e,t,n,i,s,o){this.fontType="image",this.imageAtlas=new Sk({glyphWidth:t,glyphHeight:n,cellWidth:i,cellHeight:s,atlasBlocks:o}),await this.imageAtlas.loadFromPNG(e),this.cellWidth=i,this.cellHeight=s,this.bitmapCharWidth=t,this.bitmapCharHeight=n,this.calculateGridSize(),this.cells=this.createEmptyGrid()}getFontType(){return this.fontType}getBitmapFont(){return this.bitmapFont}getBitmapCharDimensions(){return this.fontType!=="bitmap"?null:{width:this.bitmapCharWidth,height:this.bitmapCharHeight}}setPalette(e){this.paletteCache=e}renderDisplayData(e){if(!e||!e.cells||e.cells.length===0){console.warn("[Terminal2D] Empty display data");return}if(e.width===0||e.height===0){console.warn("[Terminal2D] Invalid display dimensions:",e.width,e.height);return}(e.width!==this.cols||e.height!==this.rows)&&this.setFixedGrid(e.width,e.height,this.cellAspectRatio);let t=this.paletteCache??e.palette;if(!t||t.length===0){console.error("[Terminal2D] No palette available (neither cached nor in display)");return}let n=cr(i=>{if(i==null||isNaN(i))return console.warn("[Terminal2D] Invalid palette index (undefined/null/NaN):",i),this.defaultFgColor;if(i===255)return"rgba(0, 0, 0, 0)";if(i<0||i>=t.length)return console.warn(`[Terminal2D] Invalid palette index: ${i}`),this.defaultFgColor;let s=t[i];return!s||typeof s.r!="number"?(console.warn(`[Terminal2D] Corrupted palette entry at index ${i}:`,s),this.defaultFgColor):`rgba(${s.r}, ${s.g}, ${s.b}, ${s.a/255})`},"convertColor");for(let i=0;i<e.height&&i<this.rows;i++)for(let s=0;s<e.width&&s<this.cols;s++){let o=i*e.width+s;if(o>=e.cells.length)break;let a=e.cells[o];if(!a)continue;let l=n(a.fgColorIndex),u=n(a.bgColorIndex);this.setCell(s,i,a.char??" ",l,u)}this.render()}isReady(){return!0}getCols(){return this.cols}getRows(){return this.rows}resize(e,t){this.setFixedGrid(e,t)}setScalingMode(e){if(this.scalingMode===e)return;let t=this.cols,n=this.rows;if(this.scalingMode=e,this.calculateGridSize(),this.cols!==t||this.rows!==n){let i=this.cells;if(this.cells=this.createEmptyGrid(),i&&i.length>0){let s=Math.min(t,this.cols),o=Math.min(n,this.rows);for(let a=0;a<o;a++)for(let l=0;l<s;l++)i[a]&&i[a][l]&&(this.cells[a][l]=i[a][l])}}this.render()}setCellSize(e,t){let n=Math.max(1,Math.min(255,Math.round(e))),i=Math.max(1,Math.min(255,Math.round(t)));if(this.cellWidth===n&&this.cellHeight===i)return;let s=this.cols,o=this.rows;if(this.cellWidth=n,this.cellHeight=i,this.customCellSize=!0,this.calculateGridSize(),this.cols!==s||this.rows!==o){let a=this.cells;if(this.cells=this.createEmptyGrid(),a&&a.length>0){let l=Math.min(s,this.cols),u=Math.min(o,this.rows);for(let c=0;c<u;c++)for(let d=0;d<l;d++)a[c]&&a[c][d]&&(this.cells[c][d]=a[c][d])}}this.render()}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}getMaxCells(){return 65536}destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0),this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}};cr(Xw,"Terminal2D");var kk=Xw,Zw=class{constructor(e,t={}){L(this,"container"),L(this,"overlayDiv",null),L(this,"button",null),L(this,"options"),L(this,"started",!1),L(this,"onStartCallback"),this.container=e,this.options={buttonText:t.buttonText??"Click to Start",onStart:t.onStart??(()=>{}),backgroundColor:t.backgroundColor??"rgba(0, 0, 0, 0.8)",buttonColor:t.buttonColor??"#4a90d9",buttonHoverColor:t.buttonHoverColor??"#357abd",buttonTextColor:t.buttonTextColor??"#ffffff",zIndex:t.zIndex??1e3},this.onStartCallback=t.onStart,this.createOverlay()}createOverlay(){let e=window.getComputedStyle(this.container).position;e!=="relative"&&e!=="absolute"&&e!=="fixed"&&(this.container.style.position="relative"),this.overlayDiv=document.createElement("div"),this.overlayDiv.className="utsp-autoplay-overlay",this.overlayDiv.style.cssText=`
|
|
213
213
|
position: absolute !important;
|
|
214
214
|
top: 0 !important;
|
|
215
215
|
left: 0 !important;
|
|
@@ -233,7 +233,7 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
233
233
|
cursor: pointer !important;
|
|
234
234
|
transition: background-color 0.2s ease, transform 0.1s ease !important;
|
|
235
235
|
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
|
|
236
|
-
`,this.button.addEventListener("mouseenter",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonHoverColor} !important`,this.button.style.transform="scale(1.05)")}),this.button.addEventListener("mouseleave",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonColor} !important`,this.button.style.transform="scale(1)")}),this.button.addEventListener("click",t=>{t.stopPropagation(),this.start()}),this.overlayDiv.addEventListener("click",()=>{this.start()}),this.overlayDiv.appendChild(this.button),this.container.appendChild(this.overlayDiv)}start(){this.started||(this.started=!0,this.overlayDiv&&(this.overlayDiv.style.transition="opacity 0.3s ease",this.overlayDiv.style.opacity="0",setTimeout(()=>{this.removeOverlay()},300)),this.onStartCallback&&this.onStartCallback())}isStarted(){return this.started}isVisible(){return this.overlayDiv!==null&&!this.started}removeOverlay(){this.overlayDiv&&this.overlayDiv.parentElement&&this.overlayDiv.parentElement.removeChild(this.overlayDiv),this.overlayDiv=null,this.button=null}setButtonText(e){this.options.buttonText=e,this.button&&(this.button.textContent=e)}setOnStart(e){this.onStartCallback=e}destroy(){this.removeOverlay(),this.started=!1}};cr(
|
|
236
|
+
`,this.button.addEventListener("mouseenter",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonHoverColor} !important`,this.button.style.transform="scale(1.05)")}),this.button.addEventListener("mouseleave",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonColor} !important`,this.button.style.transform="scale(1)")}),this.button.addEventListener("click",t=>{t.stopPropagation(),this.start()}),this.overlayDiv.addEventListener("click",()=>{this.start()}),this.overlayDiv.appendChild(this.button),this.container.appendChild(this.overlayDiv)}start(){this.started||(this.started=!0,this.overlayDiv&&(this.overlayDiv.style.transition="opacity 0.3s ease",this.overlayDiv.style.opacity="0",setTimeout(()=>{this.removeOverlay()},300)),this.onStartCallback&&this.onStartCallback())}isStarted(){return this.started}isVisible(){return this.overlayDiv!==null&&!this.started}removeOverlay(){this.overlayDiv&&this.overlayDiv.parentElement&&this.overlayDiv.parentElement.removeChild(this.overlayDiv),this.overlayDiv=null,this.button=null}setButtonText(e){this.options.buttonText=e,this.button&&(this.button.textContent=e)}setOnStart(e){this.onStartCallback=e}destroy(){this.removeOverlay(),this.started=!1}};cr(Zw,"AutoplayOverlay");var Ek=Zw,Kw=class{constructor(e,t){L(this,"canvas"),L(this,"ctx"),L(this,"containerDiv"),L(this,"parentElement"),L(this,"resizeObserver"),L(this,"width",0),L(this,"height",0),L(this,"currentConfig",null),L(this,"configHash",""),this.parentElement=e,this.containerDiv=document.createElement("div"),this.containerDiv.className="postprocess-container",this.containerDiv.style.cssText=`
|
|
237
237
|
position: absolute !important;
|
|
238
238
|
top: 0 !important;
|
|
239
239
|
left: 0 !important;
|
|
@@ -251,8 +251,8 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
251
251
|
width: 100% !important;
|
|
252
252
|
height: 100% !important;
|
|
253
253
|
pointer-events: none !important;
|
|
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"}};cr(
|
|
255
|
-
`,xk=class{constructor(e={}){L(this,"options"),L(this,"fgCache",[]),L(this,"bgCache",[]),L(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+=am),this.options.includeHome&&(o+=om);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],g=p.fgColorIndex,x=p.bgColorIndex;u?(x!==l&&(o+=this.bgCache[x],l=x),g!==a&&(o+=this.fgCache[g],a=g)):(o+=this.bgCache[x],o+=this.fgCache[g]),o+=p.char||" "}c&&d<n-1&&(o+=Ck)}return this.options.includeReset&&(o+=Gc),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+=Gc),o}clear(){return wk+om}showCursor(){return bk}hideCursor(){return am}reset(){return Gc}moveTo(e,t){return`\x1B[${e+1};${t+1}H`}};cr(xk,"TerminalANSI");function Sk(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}}cr(Sk,"hexToRGB");function Ik(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}`}cr(Ik,"rgbToHex");function kk(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}}cr(kk,"createTestRenderState");var jw=Object.defineProperty,Ek=(r,e,t)=>e in r?jw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wr=(r,e)=>jw(r,"name",{value:e,configurable:!0}),ke=(r,e,t)=>(Ek(r,typeof e!="symbol"?e+"":e,t),t),Mk=(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))(Mk||{}),Yw=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){this.config.debug&&console.warn("[InputSystem]",...e)}};wr(Yw,"BaseInputs");var $a=Yw;function Tk(r){return typeof r=="object"&&r!==null&&"start"in r&&"stop"in r&&"reset"in r&&"isListening"in r&&"destroy"in r}wr(Tk,"isInputs");var Gw=class extends $a{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(Gw,"KeyboardInputs");var Xw=Gw;function Uk(r,e){let t=new Xw(r);return e&&t.setCallbacks(e),t.start(),t}wr(Uk,"useKeyboardInputs");var Ch=class Zw extends $a{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",Ht.zero()),ke(this,"mouseDelta",Ht.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=Ht.zero(),this.mouseDelta=Ht.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=Ht.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=Zw.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 Ht(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(Ch,"MouseInputs"),ke(Ch,"BUTTON_NAMES",["left","middle","right"]);var Kw=Ch;function Ak(r,e){let t=new Kw(r);return e&&t.setCallbacks(e),t.start(),t}wr(Ak,"useMouseInputs");var qw=class extends $a{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 Ht(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 Ht(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 Ht(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(qw,"MobileInputs");var xh=qw;function Rk(r,e,t){console.warn("[MobileInputs] useMobileInputs() is deprecated and causes memory leaks. Use useMemo + useEffect instead.");let n=new xh(r,t);return e&&n.setCallbacks(e),n.start(),n}wr(Rk,"useMobileInputs");var Qw=class extends $a{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,g=Math.floor(f/a),x=Math.floor(p/l);for(let y of this.zones)this.isInsideZone(g,x,y)&&(u.set(y.id,(u.get(y.id)??0)+1),c.set(y.id,{x:Math.max(y.x,Math.min(y.x+y.width-1,g)),y:Math.max(y.y,Math.min(y.y+y.height-1,x))}))}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 g=c.get(h.id);g&&(f.lastX=g.x,f.lastY=g.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(Qw,"TouchZoneInputs");var lm=Qw,bn={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]},Jw=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(bn.tap)}mediumTap(){return this.vibrate(bn.mediumTap)}heavyTap(){return this.vibrate(bn.heavyTap)}success(){return this.vibrate(bn.success)}error(){return this.vibrate(bn.error)}warning(){return this.vibrate(bn.warning)}selection(){return this.vibrate(bn.selection)}impactLight(){return this.vibrate(bn.impactLight)}impactMedium(){return this.vibrate(bn.impactMedium)}impactHeavy(){return this.vibrate(bn.impactHeavy)}notification(){return this.vibrate(bn.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(Jw,"MobileVibration");var Yf=Jw,Xc=null;function Pk(){return Xc||(Xc=new Yf),Xc}wr(Pk,"getMobileVibration");var zk=.01,eb=class extends $a{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)>zk&&((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(eb,"GamepadInputs");var tb=eb;function Dk(r,e){let t=new tb(e);return r&&t.setGamepadCallbacks(r),t.start(),t}wr(Dk,"useGamepadInputs");var rb=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 Xw(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 Kw(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 tb({debug:this.config.debug}),this.gamepad.start(),this.log("Gamepad initialized")),this.config.enableMobile&&(this.config.mobileTargetElement?(this.mobile=new xh(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 lm(this.mobile,d),this.log("Touch zones initialized")}}}getButton(e,t){if(!da({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(!da({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(!da({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(!Av({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=Ri[e];return this.keyboard.isKeyPressed(t)}getKeyboardButtonJustPressed(e){if(!this.keyboard)return!1;let t=Ri[e];return this.keyboard.isKeyJustPressed(t)}getKeyboardButtonJustReleased(e){if(!this.keyboard)return!1;let t=Ri[e];return this.keyboard.isKeyJustReleased(t)}getMouseButton(e){if(!this.mouse)return!1;switch(e){case _t.LeftButton:return this.mouse.isLeftMousePressed();case _t.RightButton:return this.mouse.isRightMousePressed();case _t.MiddleButton:return this.mouse.isMiddleMousePressed();default:return!1}}getMouseButtonJustPressed(e){if(!this.mouse)return!1;switch(e){case _t.LeftButton:return this.mouse.isLeftMouseJustPressed();case _t.RightButton:return this.mouse.isRightMouseJustPressed();case _t.MiddleButton:return this.mouse.isMiddleMouseJustPressed();default:return!1}}getMouseButtonJustReleased(e){if(!this.mouse)return!1;switch(e){case _t.LeftButton:return this.mouse.isLeftMouseJustReleased();case _t.RightButton:return this.mouse.isRightMouseJustReleased();case _t.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 _t.PositionX:return this.mouse.getMousePosition().x;case _t.PositionY:return this.mouse.getMousePosition().y;case _t.DeltaX:return this.mouse.getMouseDelta().x;case _t.DeltaY:return this.mouse.getMouseDelta().y;case _t.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 xh(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 lm(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){this.config.debug&&console.warn(`[InputRouter] ${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=>{i.preventDefault()},{passive:!1})}};wr(rb,"UnifiedInputRouter");var nb=rb,um=100,cm=2,ib=class Sh{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 g of p.sources){if(n.has(g.sourceId))continue;let x=!1,y=!1,m=!1,v=!1;g.type===ce.Keyboard&&g.key!==void 0?(x=t.getButton(ce.Keyboard,g.key),y=((i=t.getButtonJustPressed)==null?void 0:i.call(t,ce.Keyboard,g.key))??!1,m=((s=t.getButtonJustReleased)==null?void 0:s.call(t,ce.Keyboard,g.key))??!1,v=!0):g.type===ce.Mouse&&g.mouseButton!==void 0?(x=t.getButton(ce.Mouse,g.mouseButton),y=((o=t.getButtonJustPressed)==null?void 0:o.call(t,ce.Mouse,g.mouseButton))??!1,m=((a=t.getButtonJustReleased)==null?void 0:a.call(t,ce.Mouse,g.mouseButton))??!1,v=!0):g.type===ce.Gamepad&&g.button!==void 0?(x=t.getButton(ce.Gamepad,g.button),y=((l=t.getButtonJustPressed)==null?void 0:l.call(t,ce.Gamepad,g.button))??!1,m=((u=t.getButtonJustReleased)==null?void 0:u.call(t,ce.Gamepad,g.button))??!1,v=!0):g.type===ce.Touch&&g.touchButton!==void 0?(x=t.getButton(ce.Touch,g.touchButton),y=((c=t.getButtonJustPressed)==null?void 0:c.call(t,ce.Touch,g.touchButton))??!1,m=((d=t.getButtonJustReleased)==null?void 0:d.call(t,ce.Touch,g.touchButton))??!1,v=!0):g.type===ce.TouchZone&&g.touchZoneId!==void 0&&(x=t.getButton(ce.TouchZone,g.touchZoneId),y=((h=t.getButtonJustPressed)==null?void 0:h.call(t,ce.TouchZone,g.touchZoneId))??!1,m=((f=t.getButtonJustReleased)==null?void 0:f.call(t,ce.TouchZone,g.touchZoneId))??!1,v=!0),v&&n.set(g.sourceId,{pressed:x,justPressed:y,justReleased:m})}return n}static collectMousePosition(e,t,n,i,s){var I;let o=e.getAxis(ce.Mouse,_t.PositionX),a=e.getAxis(ce.Mouse,_t.PositionY),l=((I=e.isLeftMousePressed)==null?void 0:I.call(e))??!1,{renderWidth:u,renderHeight:c,offsetX:d,offsetY:h,rect:f}=Sh.calculateRenderMetrics(t,s),p=o-f.left-d,g=a-f.top-h,x=u/n,y=c/i,m=Math.floor(p/x),v=Math.floor(g/y),b=p>=0&&p<u&&g>=0&&g<c;return{x:Math.max(0,Math.min(n-1,m)),y:Math.max(0,Math.min(i-1,v)),over:b,isLeftDown:l}}static collectTouchPositions(e,t,n,i,s=10,o){let a=[],{renderWidth:l,renderHeight:u,offsetX:c,offsetY:d,rect:h}=Sh.calculateRenderMetrics(t,o),f=l/n,p=u/i;for(let g=0;g<s;g++){let x=g;if(e.getButton(ce.Touch,x)){let y=um+g*cm,m=um+g*cm+1,v=e.getAxis(ce.Touch,y),b=e.getAxis(ce.Touch,m),I=v-h.left-c,S=b-h.top-d,M=Math.floor(I/f),U=Math.floor(S/p),z=I>=0&&I<l&&S>=0&&S<u;a.push({id:g,x:Math.max(0,Math.min(n-1,M)),y:Math.max(0,Math.min(i-1,U)),over:z})}}return a}static collectTextInputs(e){return typeof e.getTextInputs=="function"?e.getTextInputs():[]}};wr(ib,"InputCollector");var Er=ib;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 Dl=Object.create(null);Object.keys(Yn).forEach(r=>{Dl[Yn[r]]=r});const Ih={type:"error",data:"parser error"},sb=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",ob=typeof ArrayBuffer=="function",ab=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,Gf=({type:r,data:e},t,n)=>sb&&e instanceof Blob?t?n(e):dm(e,n):ob&&(e instanceof ArrayBuffer||ab(e))?t?n(e):dm(new Blob([e]),n):n(Yn[r]+(e||"")),dm=(r,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)};function hm(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Zc;function Ok(r,e){if(sb&&r.data instanceof Blob)return r.data.arrayBuffer().then(hm).then(e);if(ob&&(r.data instanceof ArrayBuffer||ab(r.data)))return e(hm(r.data));Gf(r,!1,t=>{Zc||(Zc=new TextEncoder),e(Zc.encode(t))})}const fm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ko=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<fm.length;r++)Ko[fm.charCodeAt(r)]=r;const Bk=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=Ko[r.charCodeAt(n)],o=Ko[r.charCodeAt(n+1)],a=Ko[r.charCodeAt(n+2)],l=Ko[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},Fk=typeof ArrayBuffer=="function",Xf=(r,e)=>{if(typeof r!="string")return{type:"message",data:lb(r,e)};const t=r.charAt(0);return t==="b"?{type:"message",data:Lk(r.substring(1),e)}:Dl[t]?r.length>1?{type:Dl[t],data:r.substring(1)}:{type:Dl[t]}:Ih},Lk=(r,e)=>{if(Fk){const t=Bk(r);return lb(t,e)}else return{base64:!0,data:r}},lb=(r,e)=>{switch(e){case"blob":return r instanceof Blob?r:new Blob([r]);case"arraybuffer":default:return r instanceof ArrayBuffer?r:r.buffer}},ub="",_k=(r,e)=>{const t=r.length,n=new Array(t);let i=0;r.forEach((s,o)=>{Gf(s,!1,a=>{n[o]=a,++i===t&&e(n.join(ub))})})},$k=(r,e)=>{const t=r.split(ub),n=[];for(let i=0;i<t.length;i++){const s=Xf(t[i],e);if(n.push(s),s.type==="error")break}return n};function Nk(){return new TransformStream({transform(r,e){Ok(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 Kc;function hl(r){return r.reduce((e,t)=>e+t.length,0)}function fl(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 Wk(r,e){Kc||(Kc=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(hl(t)<1)break;const l=fl(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(hl(t)<2)break;const l=fl(t,2);i=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),n=3}else if(n===2){if(hl(t)<8)break;const l=fl(t,8),u=new DataView(l.buffer,l.byteOffset,l.length),c=u.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(Ih);break}i=c*Math.pow(2,32)+u.getUint32(4),n=3}else{if(hl(t)<i)break;const l=fl(t,i);a.enqueue(Xf(s?l:Kc.decode(l),e)),n=0}if(i===0||i>r){a.enqueue(Ih);break}}}})}const cb=4;function Dt(r){if(r)return Hk(r)}function Hk(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 zu=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),dn=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Vk="arraybuffer";function db(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}const jk=dn.setTimeout,Yk=dn.clearTimeout;function Du(r,e){e.useNativeTimers?(r.setTimeoutFn=jk.bind(dn),r.clearTimeoutFn=Yk.bind(dn)):(r.setTimeoutFn=dn.setTimeout.bind(dn),r.clearTimeoutFn=dn.clearTimeout.bind(dn))}const Gk=1.33;function Xk(r){return typeof r=="string"?Zk(r):Math.ceil((r.byteLength||r.size)*Gk)}function Zk(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 hb(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Kk(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function qk(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 Qk extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Zf extends Dt{constructor(e){super(),this.writable=!1,Du(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 Qk(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=Xf(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=Kk(e);return t.length?"?"+t:""}}class Jk extends Zf{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)};$k(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,_k(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]=hb()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let fb=!1;try{fb=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const eE=fb;function tE(){}class rE extends Jk{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,Du(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=db(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=tE,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",pm);else if(typeof addEventListener=="function"){const r="onpagehide"in dn?"pagehide":"unload";addEventListener(r,pm,!1)}}function pm(){for(let r in jn.requests)jn.requests.hasOwnProperty(r)&&jn.requests[r].abort()}const nE=function(){const r=pb({xdomain:!1});return r&&r.responseType!==null}();class iE extends rE{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=nE&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new jn(pb,this.uri(),e)}}function pb(r){const e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||eE))return new XMLHttpRequest}catch{}if(!e)try{return new dn[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const gb=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class sE extends Zf{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=gb?{}:db(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;Gf(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{}i&&zu(()=>{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]=hb()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const qc=dn.WebSocket||dn.MozWebSocket;class oE extends sE{createSocket(e,t,n){return gb?new qc(e,t,n):t?new qc(e,t):new qc(e)}doWrite(e,t){this.ws.send(t)}}class aE extends Zf{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=Wk(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=Nk();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&&zu(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const lE={websocket:oE,webtransport:aE,polling:iE},uE=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,cE=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function kh(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=uE.exec(r||""),s={},o=14;for(;o--;)s[cE[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=dE(s,s.path),s.queryKey=hE(s,s.query),s}function dE(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 hE(r,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}const Eh=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ol=[];Eh&&addEventListener("offline",()=>{Ol.forEach(r=>r())},!1);class zi extends Dt{constructor(e,t){if(super(),this.binaryType=Vk,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=kh(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=kh(t.host).host);Du(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=qk(this.opts.query)),Eh&&(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"})},Ol.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=cb,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&&zi.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",zi.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+=Xk(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,zu(()=>{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(zi.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(),Eh&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Ol.indexOf(this._offlineEventListener);n!==-1&&Ol.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}zi.protocol=cb;class fE extends zi{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;zi.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;zi.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 pE=class extends fE{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=>lE[i]).filter(i=>!!i)),super(e,n)}};function gE(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=kh(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 mE=typeof ArrayBuffer=="function",yE=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,mb=Object.prototype.toString,vE=typeof Blob=="function"||typeof Blob<"u"&&mb.call(Blob)==="[object BlobConstructor]",wE=typeof File=="function"||typeof File<"u"&&mb.call(File)==="[object FileConstructor]";function Kf(r){return mE&&(r instanceof ArrayBuffer||yE(r))||vE&&r instanceof Blob||wE&&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(Kf(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 bE(r){const e=[],t=r.data,n=r;return n.data=Mh(t,e),n.attachments=e.length,{packet:n,buffers:e}}function Mh(r,e){if(!r)return r;if(Kf(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]=Mh(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]=Mh(r[n],e));return t}return r}function CE(r,e){return r.data=Th(r.data,e),delete r.attachments,r}function Th(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]=Th(r[t],e);else if(typeof r=="object")for(const t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=Th(r[t],e));return r}const xE=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],SE=5;var ze;(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"})(ze||(ze={}));class IE{constructor(e){this.replacer=e}encode(e){return(e.type===ze.EVENT||e.type===ze.ACK)&&Bl(e)?this.encodeAsBinary({type:e.type===ze.EVENT?ze.BINARY_EVENT:ze.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===ze.BINARY_EVENT||e.type===ze.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=bE(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}function gm(r){return Object.prototype.toString.call(r)==="[object Object]"}class qf 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===ze.BINARY_EVENT;n||t.type===ze.BINARY_ACK?(t.type=n?ze.EVENT:ze.ACK,this.reconstructor=new kE(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Kf(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(ze[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===ze.BINARY_EVENT||n.type===ze.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(qf.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 ze.CONNECT:return gm(t);case ze.DISCONNECT:return t===void 0;case ze.CONNECT_ERROR:return typeof t=="string"||gm(t);case ze.EVENT:case ze.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&xE.indexOf(t[0])===-1);case ze.ACK:case ze.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class kE{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=CE(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const EE=Object.freeze(Object.defineProperty({__proto__:null,Decoder:qf,Encoder:IE,get PacketType(){return ze},protocol:SE},Symbol.toStringTag,{value:"Module"}));function In(r,e,t){return r.on(e,t),function(){r.off(e,t)}}const ME=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class yb 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=[In(e,"open",this.onopen.bind(this)),In(e,"packet",this.onpacket.bind(this)),In(e,"error",this.onerror.bind(this)),In(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(ME.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:ze.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:ze.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 ze.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 ze.EVENT:case ze.BINARY_EVENT:this.onevent(e);break;case ze.ACK:case ze.BINARY_ACK:this.onack(e);break;case ze.DISCONNECT:this.ondisconnect();break;case ze.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:ze.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:ze.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 vo(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}vo.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};vo.prototype.reset=function(){this.attempts=0};vo.prototype.setMin=function(r){this.ms=r};vo.prototype.setMax=function(r){this.max=r};vo.prototype.setJitter=function(r){this.jitter=r};class Uh 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,Du(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 vo({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||EE;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 pE(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=In(t,"open",function(){n.onopen(),e&&e()}),s=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=In(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(In(e,"ping",this.onping.bind(this)),In(e,"data",this.ondata.bind(this)),In(e,"error",this.onerror.bind(this)),In(e,"close",this.onclose.bind(this)),In(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){zu(()=>{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 yb(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 Lo={};function Fl(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};const t=gE(r,e.path||"/socket.io"),n=t.source,i=t.id,s=t.path,o=Lo[i]&&s in Lo[i].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let l;return a?l=new Uh(n,e):(Lo[i]||(Lo[i]=new Uh(n,e)),l=Lo[i]),t.query&&!e.query&&(e.query=t.queryKey),l.socket(t.path,e)}Object.assign(Fl,{Manager:Uh,Socket:yb,io:Fl,connect:Fl});var vb=Object.defineProperty,TE=(r,e,t)=>e in r?vb(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wb=(r,e)=>vb(r,"name",{value:e,configurable:!0}),gi=(r,e,t)=>(TE(r,typeof e!="symbol"?e+"":e,t),t),bb=class{constructor(e){if(gi(this,"socket",null),gi(this,"options"),gi(this,"_state",on.Disconnected),gi(this,"pingTimestamp",0),gi(this,"latency",0),gi(this,"pingInterval",null),gi(this,"bridgeHandlers",new Map),gi(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??{},debug:e.debug??!1},this.log("Client initialized",{url:this.options.url,autoReconnect:this.options.autoReconnect})}get state(){return this._state}isConnected(){var e;return this._state===on.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=on.Connecting,this.bridgeSetup=!1,new Promise((e,t)=>{this.socket=Fl(this.options.url,{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=on.Connected,this.startPingMonitor(),this.bridgeHandlers.size>0&&this.setupBridgeListener(),e()}),this.socket.on("connect_error",n=>{this.log(`Connection error: ${n.message}`),this._state=on.Error,t(n)}),this.socket.on("disconnect",n=>{this.log(`Disconnected: ${n}`),this._state=on.Disconnected,this.stopPingMonitor()}),this.socket.on("reconnect_attempt",n=>{this.log(`Reconnection attempt ${n}...`),this._state=on.Reconnecting}),this.socket.on("reconnect",n=>{this.log(`Reconnected after ${n} attempts`),this._state=on.Connected,this.startPingMonitor()}),this.socket.on("reconnect_failed",()=>{this.log("Reconnection failed"),this._state=on.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=on.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.volatile.emit(e,t)}catch(n){this.log(`Error sending '${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=wb(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=on.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}`))}};wb(bb,"SocketIOClient");var UE=bb,Cb=Object.defineProperty,AE=(r,e,t)=>e in r?Cb(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xb=(r,e)=>Cb(r,"name",{value:e,configurable:!0}),or=(r,e,t)=>(AE(r,typeof e!="symbol"?e+"":e,t),t),Sb=class{constructor(e,t=!1){or(this,"sounds",new Map),or(this,"nameToId",new Map),or(this,"audioContext"),or(this,"debug"),this.audioContext=e,this.debug=t,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:g,value:x}=await c.read();if(g)break;d.push(x),h+=x.length,i(h,a)}let f=new Uint8Array(h),p=0;for(let g of d)f.set(g,p),p+=g.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){this.debug&&console.warn(`[SoundBank] ${e}`)}};xb(Sb,"SoundBank");var RE=Sb,Ib=class{constructor(e={}){or(this,"audioContext",null),or(this,"masterGainNode",null),or(this,"soundBank",null),or(this,"options"),or(this,"initialized",!1),or(this,"nextInstanceId",1),or(this,"instances",new Map),or(this,"instancesBySound",new Map),or(this,"activeSounds",new Set),or(this,"spatialSounds",new Map),or(this,"spatialConfig",{listenerX:0,listenerY:0,maxDistance:200,referenceDistance:20,rolloffFactor:1,panSpread:1}),or(this,"reverbConvolver",null),or(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 RE(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:g,distanceVolume:x}=this.calculateSpatialAudio(t.position.x,t.position.y),y=i.createStereoPanner();y.pan.value=g,d=u>0?0:l*x,h=l*x,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(y),y.connect(this.masterGainNode),c.pannerNode=y,c.position={x:t.position.x,y:t.position.y},c.targetVolume=h,c.outputNode=y,this.spatialSounds.set(o,{gainNode:a,pannerNode:y,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=${g.toFixed(2)} vol=${x.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 g=p.get(s);return g!==void 0&&!g.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)}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){this.options.debug&&console.warn(`[AudioManager] ${e}`)}};xb(Ib,"AudioManager");var kb=Ib,Eb=Object.defineProperty,PE=(r,e,t)=>e in r?Eb(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ur=(r,e)=>Eb(r,"name",{value:e,configurable:!0}),oe=(r,e,t)=>(PE(r,typeof e!="symbol"?e+"":e,t),t),Qf=(r=>(r.TerminalGL="webgl",r.Terminal2D="terminal2d",r))(Qf||{}),Mb=class{constructor(e=60){if(oe(this,"frameCount",0),oe(this,"fps",0),oe(this,"fpsUpdateTime",0),oe(this,"lastCoreTime",0),oe(this,"lastRenderTime",0),oe(this,"lastTotalTime",0),oe(this,"coreTimeSamples",[]),oe(this,"renderTimeSamples",[]),oe(this,"totalTimeSamples",[]),oe(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}};Ur(Mb,"PerformanceMonitor");var zE=Mb,DE="iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAI/klEQVR4Ae3BUW5jyZYEQQ9C+99yjGNwPhKJS4pkSyrVqzTjOI7jOI7jOI7jOI7jOP45Hbyhg0908EuE4/9VLCJU8UBUsYi4ULGI+MPCQcWFqOINEYuKCxF/0I1/XMUdVcQdEX+5G8enIjYRithEbCI2Ecffo4MLHXyig+P4DcILKhSxqFBUoYhFhaIKRWwqFDEqFHFHxYi4UKGIOyoUsahQxP+QG79EB6ODCx2MCkWo4g0VithEqGLTwehg08Ef1oFu/ICKUTEqVKEIZYEyUIUivlCFIu6IUMUiQh0o4heqUITCCyoU8aIKRRWKGBWbiEWFIjYVI+JFFYp4oEIRqnggqrgQ8YSKCxEvqFDECC+oUMQLKu6IWFRRhSJUoYhNhaIKRVXEEyoU8UCFIhYVi4hNhSJ+WIUiFuGHVCiqUIQqLkSoQhGqUIQqFKEKRbygQhEXKhSxqFCEKhSxqFDEhQpFvKFCEYsKRWzCCyoU8aIKRRWKWFQo4oEKRYyKEVUo4gUVilhUKOKbVCjiDRWKOP4uHfywMCoWEZsKRWwqFhGLikXEhQpFjIoLEYuKETEqLkSMikXEomIR8Q0qFPGCCkVcqFhEKKhCEapQxKgYEYsKRahCEapQhCoUsagYEaNCEXdUKOITFYpQhSJUoQhVKEIVivhCFYp4Q4UiFhWKUIWiDzYVF6KKCxEPRHyi4hMVI2JUKOITFYr4YhWKuFChiE2FIjYVFyIWUUfEiBgVilBQxYWIRYUi7qhQxKZiRIwKRRWKuKNCEarYRGwqFLGpWEQsKjYRiwpFXKhQxKJCEV+gQhGLCkWMoIoRVShiUaGICxWKeKBCEaq4EHGhQhGqUIQqFDEqFLGpUIQqFHGhQhFfpEIRm4oLEZsKRWwqFDE+WES8qUIRmwpFXIgYFYoYFYr4wyoUsalQxIUKRWyijohFxBMqFHEhYhNGxSJiVFyIUMWFiFGxiLhQoYhFxSJiUbGIWFQo4kLFImJRMSIuVCjiQoUi7qhQxAsqFHFHhSKOn9XBLxNGxSJiUbGIGBWbiEXFImJULCIWFRciVHEhYlQsIkaFIlShCFVciBgVmwhVKEIVilCFIi5UKGJUKKpQhCoUMSoWEbqhCmWgilGhDFSxyUAVo0IZqGIToYoL2bDJhlGhDFTxpAxGBosMRsSFCkW8qEIVL6hQBqrQjU3FN8vgQoQqvkkGP6xCEW+quKPiRR9ciCo2FQ9UjIgvVjEiNhUj4kLFiFhUfLOIN0VVVHGh4gU3LlRcyOCODFTxxbLgQhbcEXFHBt+o4j+IuCPiRTc2WfBNOrhQoYi/RAefiFDFN4l4wQeKOhgRL6oYESPqYERsKhRxoWIR8YSogxHxpIpFhSIUdaCIO6KOiEXFIuILRB2MiOMIqthELCoWEaNiE7GoWESMigsRqlCEKhShCkWoQhGqUMSoUFShCFUoQhWKUIUiVHEhYlQsIl5QsYjYVCjiSTcWGahiVCgDVWwyUMWoUAaqGBmMDP4S2fBABosOHsjgjopR8aQbf0AGv0SEOlDEGyoU8aQIVbyhQhmo4gk3Fh0o4kUdKGJEqAv+kIoLESNiEaEOFLGpUMSLIlTxogxGBk+4sciCO6qICxF3ZIEqfliFKjYVo2ITMSI2FYp4U4QqfsiNN1QRFyJUMTr4JhHqQBEXIjYVykAVT6pQxH8UoYof8METoo6oI+IJUQcj4klRByNiEVUo4kKEooovVrGI2FQo4o6ITcUbKo7jnjAqFPGiCkV8gQpFvKBiRDypQhEPVCjijgpFjApF3FExIn7IjRGhir9QhSJU8cUyeCCDF0X8AR8soo6IRcUiYlMxIhYVi4hFxQMVi4g7IjYVm4hFxYhYVIyICxUj4o4KRTyhQhGqUIQqNhGLikWEbmwy2GSBKjYZqGJUKANVjAplsKlQBqoYFaODRYUyuCMDVSwiPhHxiQpFvKiDUbHIQBWjQhmoQh88qeKLRLyh4kJUoYhfqkIRb4iqqOILfPCECkWo4j+oUMQLIt4QdfAHRR0Rv8CNJ0Sogzs6UMSIUAeKGBHqYBOhLnhRFryhYlQsOnhChCoWFaPijogXRagDRSj8IyoWEV+oYkT8JcIvUaGI/2EVI2JRoYhFxYi4UKGIUUU8cOP4MRXK4EkZqGJToahCFU/4QBWbiEXFJkIViioUsajYRKhiVChiVChCFYpQhSJUoQhVKGJUKKpQhCoUoQpFqEIRqrgQ8UMiFFUo4hMfLCLUEaEKRajiQhV1RKhCEReiCkV8oypiEXUwIp4UMSoUMSpGxJuiDhShiEXEk258oQhlMCLUBb9MxIh4Q4UiFhmo4k0VyuAL3Fh0oIgRoQ7ekAWquKODJ0WoA0VsKlSxqRgViwh1cKFCEX+RoApFPKFCEapQxIWKTcSmYkQsKjYRiwpFbCoUVShCFYpQhSIuVChCFRciNhUjYlGhiEXFiPhCQRWKeEKFIv4RFYuI4ziO4ziO4ziO4ziO4ziO4ziO4ziO4ziO4ziO4ziO4ziO4ziO36BiUaGKRcWiQhWqUMWmgzs6+IU6UAeLDtTBCzpQBz/gVqEIVShCEapQhCoUVVEVVVHF8avdIlShCFWoQhGqUISqqIqqqIo4frVUEaOK2FQRo4pQFVVRFVURo0IRo2IT8UtUXIhYVCiqUFRxIUIVFyK+QMUmYlexqFDFomJRoQpVqGLTwR0d/EIdqINFB+pg0YE6+GEdLG4VilCFIhShCkWoQlEVVVEVVRy/2i1CFYpQhSoUoQpFqIqqqIqqiONXu1UoQhWKUIQqFKEKRVVURVVUcfw9Orijgzd18KYOvkEH6uAFHaiDF3SgDl7QgTp4wo3jn3bj+KeFRcUXixgVXyziC1RciFDFN4hQxTeIeOCDRcR/UKGIByLeUKGILxbxhKhCEU+qUFShiE1UoYgnVSiqUMQnPjh+tYoHIv6DD45fLeIb3Tj+aeF4WoUinlTxQMQDFYuIBypecOP4p904/mkfHA9VPKniL/PB8VDEiyJGxQMV3yjigRvHP+3G8U+7cRzHcRzHcRzHcRzHcRzHcRzHcRzHcRzHcfxP+T9Q99xxOxB1qwAAAABJRU5ErkJggg==",_o={glyphWidth:8,glyphHeight:8,cellWidth:8,cellHeight:8,atlasBlocks:1};function Tb(){let r=atob(DE),e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}Ur(Tb,"decodeDefaultAtlas");var Ub=class{constructor(e,t={}){oe(this,"renderer"),oe(this,"options"),oe(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=Tb();await this.renderer.setImageFont(t,_o.glyphWidth,_o.glyphHeight,_o.cellWidth,_o.cellHeight,_o.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=Ur(()=>{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?(this.renderer.renderDisplayData(e),!0):(console.warn("[RENDERER MANAGER] No display provided"),!1):(console.warn("[RENDERER MANAGER] Renderer not ready"),!1)}render(e,t){let n=this.layerFilter?e.getRenderState(t,this.layerFilter):e.getRenderState(t);return!n||n.displays.length===0?(console.warn("[RENDERER MANAGER] No render state or no displays"),!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){this.options.debug&&console.warn(`[RendererManager] ${e}`)}};Ur(Ub,"RendererManager");var mm=Ub,Ab=class{constructor(e){if(oe(this,"core"),oe(this,"rendererManagers",new Map),oe(this,"rendererInitPromises",new Map),oe(this,"rendererManager"),oe(this,"rendererType"),oe(this,"primaryDisplayId",0),oe(this,"displayConfigs"),oe(this,"options"),oe(this,"running",!1),oe(this,"startTime",0),oe(this,"lastTimestamp",0),oe(this,"userId",""),oe(this,"visibilityChangeHandler"),oe(this,"tickRate",30),oe(this,"accumulatedTime",0),oe(this,"FRAME_TIME_MIN",1e3/60),oe(this,"lastRenderTimestamp",0),oe(this,"rafId",0),oe(this,"firstTickDone",!1),oe(this,"performanceMonitor"),oe(this,"renderMode","continuous"),oe(this,"renderRequested",!1),this.options={application:e.application,container:e.container,displayContainers:e.displayContainers,debug:e.debug??!1,width:e.width??80,height:e.height??25,renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,renderMode:e.renderMode??"continuous"},this.log("Initializing BaseClientRuntime"),this.core=new Pw({mode:"client",maxUsers:1}),this.core.onPaletteChanged(t=>{this.onCorePaletteChanged(t)}),this.core.onBitmapFontChanged(t=>{this.onCoreBitmapFontChanged(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 zE(60),this.tickRate=20,this.renderMode=e.renderMode??"continuous",this.log(`Configured: tickRate=${this.tickRate}, renderMode=${this.renderMode}`),this.log("BaseClientRuntime initialized")}createRenderer(e,t){if(t==="terminal2d"){this.log("Creating Terminal 2D renderer");let s=new yk(e,{fixedCols:this.options.width,fixedRows:this.options.height,cellAspectRatio:1});return this.options.useImageDataRendering&&(this.log("Enabling ImageData rendering (pixel-perfect, optimized)"),s.setImageDataRendering(!0)),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 pk(e,{cols:this.options.width,rows:this.options.height,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 mm(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 mm(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}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.core,this)),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.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();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.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(g=>this.mainLoop(g));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.core,o),(h=(d=this.options.application).updateUser)==null||h.call(d,this.core,s,o)),this.processTickOrders(s);let p=s.updateMacros();s.processMacroEvents(p),this.core.endTick().forEach(({static:g,dynamic:x})=>{let y=((g==null?void 0:g.length)??0)+((x==null?void 0:x.length)??0);s.recordBytesReceived(y)}),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){console.warn("[BaseClientRuntime] No render state or displays");return}for(let n of t.displays){let i=this.rendererManagers.get(n.id)??this.ensureRendererManager(n.id);if(!i){console.warn(`[BaseClientRuntime] No renderer manager for display ${n.id}, skipping render`);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(l=>l.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}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=Ur(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?console.warn("[BaseClientRuntime] Cannot update palette: no renderer available"):this.log(`✓ Palette updated on ${i} renderer(s)`)}onCoreBitmapFontChanged(e){this.log(`Bitmap font ${e} changed, updating renderer`);let t=this.core.getBitmapFont(e);if(!t){console.warn(`[BaseClientRuntime] Font ${e} not found in registry`);return}let n=new Map,i=0;for(let a=0;a<256;a++){let l=t.getGlyph(a);l&&(n.set(a,l),i++)}this.log(`Built bitmap font map with ${i} glyphs, dimensions: ${t.getCharWidth()}x${t.getCharHeight()}`);let s=Ur(a=>{a&&"setBitmapFont"in a&&typeof a.setBitmapFont=="function"&&a.setBitmapFont(n,t.getCharWidth(),t.getCharHeight(),t.getCellWidth(),t.getCellHeight())},"applyBitmapFont"),o=0;for(let[a,l]of this.rendererManagers.entries()){let u=l.getRenderer();u&&(s(u),o++,this.onFontChanged(u,a))}o===0?console.warn("[BaseClientRuntime] Cannot update font: no renderer available"):this.log(`✓ Renderer bitmap font updated successfully on ${o} renderer(s)`)}onCoreImageFontChanged(e){this.log(`Image font ${e} changed, updating renderer`);let t=this.core.getImageFont(e);if(!t){console.warn(`[BaseClientRuntime] Image font ${e} not found in registry`);return}this.log(`Loading image font with ${t.getAtlasBlocks()} blocks, glyph: ${t.getGlyphWidth()}x${t.getGlyphHeight()}`);let n=Ur(s=>{s&&"setImageFont"in s&&typeof s.setImageFont=="function"&&s.setImageFont(t.getImageData(),t.getGlyphWidth(),t.getGlyphHeight(),t.getCellWidth(),t.getCellHeight(),t.getAtlasBlocks())},"applyImageFont"),i=0;for(let[s,o]of this.rendererManagers.entries()){let a=o.getRenderer();a&&(n(a),i++,this.onFontChanged(a,s))}i===0?console.warn("[BaseClientRuntime] Cannot update image font: no renderer available"):this.log(`✓ Renderer image font updated successfully on ${i} renderer(s)`)}onFontChanged(e,t){}log(e){this.options.debug&&console.warn(`[BaseClientRuntime] ${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}};Ur(Ab,"BaseClientRuntime");var OE=Ab,Xn=1e3,Rb=class{constructor(e,t,n,i,s,o,a){oe(this,"network"),oe(this,"core"),oe(this,"rendererManagers"),oe(this,"primaryDisplayId"),oe(this,"performanceMonitor"),oe(this,"options"),oe(this,"layerTraffic",new Map),oe(this,"miscTraffic",new Map),oe(this,"displayTraffic",new Map),oe(this,"audioManager",null),oe(this,"postProcessCallback",null),oe(this,"userId",""),oe(this,"lastReceivedTick",-1),oe(this,"connected",!1),oe(this,"totalBytesReceived",0),oe(this,"lastSentViewports",new Map),oe(this,"lastCollectedTouches",[]),oe(this,"touchZonesCallback",null),oe(this,"audioLoadingState",{totalExpected:0,loadedSounds:new Set,errors:new Map}),oe(this,"ensureRendererManager"),this.network=e,this.core=t,this.rendererManagers=n,this.primaryDisplayId=o,this.performanceMonitor=i,this.ensureRendererManager=a,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}}getRendererManager(e){return this.rendererManagers.get(e)}getPrimaryRendererManager(){return this.rendererManagers.get(this.primaryDisplayId)??Array.from(this.rendererManagers.values())[0]}renderDisplays(){var t,n;let e=this.core.getRenderState(this.userId);if(!e||e.displays.length===0){this.options.debug&&this.log("Render skipped: no render state or displays");return}for(let i of e.displays){let s=this.getRendererManager(i.id)??((t=this.ensureRendererManager)==null?void 0:t.call(this,i.id));if(!s){console.warn(`[NetworkSync] No renderer manager for display ${i.id}, skipping render`);continue}let o=(n=s.getLayerFilter)==null?void 0:n.call(s),a=o?this.core.getRenderState(this.userId,o):e;if(!a){this.options.debug&&this.log(`Render state unavailable for display ${i.id} with filter`);continue}let l=a.displays.find(u=>u.id===i.id);if(!l){this.options.debug&&this.log(`Render state missing display ${i.id} after filtering`);continue}if(!s.isReady()){this.options.debug&&this.log(`Renderer for display ${i.id} not ready yet`);continue}s.renderDisplay(l)}}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){return new Promise((t,n)=>{this.network.send("join",{username:this.options.username,token:this.options.token}),this.network.on("join_response",i=>{if(i.success){this.userId=i.userId,this.log(`Joined game as ${this.userId}`);let s=this.core.createUser(this.userId,this.options.username);s.setBytesTickRate(20),this.audioManager&&s.setAudioProcessor(this.audioManager),e!=null&&e.initUser&&e.initUser(this.core,s,{username:this.options.username,token:this.options.token}),t(this.userId)}else n(new Error(i.error||"Failed to join game"))}),setTimeout(()=>n(new Error("Join timeout")),5e3)})}sendInput(e){var b,I,S;let t=this.core.getUser(this.userId);if(!t)return;let n=this.getPrimaryRendererManager(),i=n==null?void 0:n.getCanvas();if(i){let M=t.getDisplays(),U=((b=M.find(N=>N.getId&&N.getId()===this.primaryDisplayId)??M[0])==null?void 0:b.getSize())??{x:this.options.canvasWidth,y:this.options.canvasHeight},z=U.x,O=U.y,R=(S=(I=n==null?void 0:n.getRenderer())==null?void 0:I.getOffsets)==null?void 0:S.call(I),B={offsetX:(R==null?void 0:R.offsetX)??0,offsetY:(R==null?void 0:R.offsetY)??0},A=Er.collectMousePosition(e,i,z,O,B);t.setMousePosition(A.x,A.y,A.over),t.updateMacroMouse(A.x,A.y,A.isLeftDown);let V=Er.collectTouchPositions(e,i,z,O,10,B);V.forEach(N=>{t.setTouchPosition(N.id,N.x,N.y,N.over)}),this.lastCollectedTouches=V}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((M,U)=>M.bindingId-U.bindingId),h=new Map;for(let M of d){let U=s.evaluateAxis(M.bindingId,l);h.set(M.bindingId,U),t.setAxis(M.name,U)}let f=a.sort((M,U)=>M.bindingId-U.bindingId),p=new Map;for(let M of f){let U=s.evaluateButton(M.bindingId,u);p.set(M.bindingId,U),t.setButton(M.name,U)}let g=t.getMouseDisplayInfo(),x=t.getIsMouseOnADisplay(),y=this.collectChangedViewports(),m=this.lastCollectedTouches.map(M=>({id:M.id,x:M.x,y:M.y,over:M.over})),v=Dw(0n,h,p,(g==null?void 0:g.displayId)??0,(g==null?void 0:g.localX)??0,(g==null?void 0:g.localY)??0,x,c,[],y,m);this.network.send("input",v)}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.log("Disconnected from server"))}getUserId(){return this.userId}isConnected(){return this.connected}getTotalBytesReceived(){return this.totalBytesReceived}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=>{try{let t=this.convertToUint8Array(e,"update");if(!t)return;this.recordBytesReceived(t.length);let n=this.core.applyUpdatePacketBuffer(this.userId,t);n?(this.postProcessCallback&&n.postProcessOrders&&n.postProcessOrders.length>0&&this.postProcessCallback(n.postProcessOrders),this.renderDisplays()):this.log("Failed to apply update packet")}catch(t){this.log(`Error applying update packet: ${t}`)}}),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.log("Disconnected from server")})}handleUpdatePacket(e,t){try{let n=this.convertToUint8Array(e,t);if(!n)return;this.recordBytesReceived(n.length);let i=new DataView(n.buffer,n.byteOffset,n.byteLength),s=Number(i.getBigUint64(0,!1));if(t==="update-dynamic"&&s<this.lastReceivedTick)return;s>this.lastReceivedTick&&(this.lastReceivedTick=s);let o=this.core.applyUpdatePacketBuffer(this.userId,n);if(o){let a=performance.now(),l=Ur((y,m)=>{if(m<=0)return;let v=this.miscTraffic.get(y)??{total:0,windowSum:0,samples:[]};v.total+=m,v.windowSum+=m,v.samples.push({time:a,bytes:m}),this.miscTraffic.set(y,v)},"recordMisc"),u=Ur(y=>{try{return JSON.stringify(y).length}catch{return 0}},"safeLen"),c=o.__byteSizes,d=c==null?void 0:c.audioOrders;typeof d=="number"?l("update.audioOrders",d):o.audioOrders&&o.audioOrders.length&&l("update.audioOrders",u(o.audioOrders));let h=c==null?void 0:c.vibrationOrders;typeof h=="number"?l("update.vibrationOrders",h):o.vibrationOrders&&o.vibrationOrders.length&&l("update.vibrationOrders",u(o.vibrationOrders));let f=c==null?void 0:c.macroOrders;typeof f=="number"?l("update.macroOrders",f):o.macroOrders&&o.macroOrders.length&&l("update.macroOrders",u(o.macroOrders));let p=c==null?void 0:c.postProcessOrders;if(typeof p=="number"?l("update.postProcessOrders",p):o.postProcessOrders&&o.postProcessOrders.length&&l("update.postProcessOrders",u(o.postProcessOrders)),o.displays&&o.displays.length)for(let y of o.displays){let m=y.id;if(typeof m!="number")continue;let v=this.displayTraffic.get(m)??{total:0,windowSum:0,samples:[]},b=7;v.total+=b,v.windowSum+=b,v.samples.push({time:a,bytes:b}),this.displayTraffic.set(m,v)}for(let y of o.layers){let m=y.byteSize??0,v=this.layerTraffic.get(y.id)??{total:0,windowSum:0,samples:[]};v.total+=m,v.windowSum+=m,v.samples.push({time:a,bytes:m});let b=a-Xn;for(;v.samples.length&&v.samples[0].time<b;){let I=v.samples.shift();I&&(v.windowSum-=I.bytes)}this.layerTraffic.set(y.id,v)}{let y=a-Xn;this.miscTraffic.forEach((m,v)=>{for(;m.samples.length&&m.samples[0].time<y;){let b=m.samples.shift();b&&(m.windowSum-=b.bytes)}m.windowSum<0&&(m.windowSum=0),this.miscTraffic.set(v,m)})}{let y=a-Xn;this.displayTraffic.forEach((m,v)=>{for(;m.samples.length&&m.samples[0].time<y;){let b=m.samples.shift();b&&(m.windowSum-=b.bytes)}m.windowSum<0&&(m.windowSum=0),this.displayTraffic.set(v,m)})}this.postProcessCallback&&o.postProcessOrders&&o.postProcessOrders.length>0&&this.postProcessCallback(o.postProcessOrders),this.options.debug&&this.debugRenderState();let g=performance.now();this.renderDisplays();let x=performance.now()-g;this.performanceMonitor.recordFrameTiming(0,x),this.options.debug&&console.warn(`[CLIENT] render() completed for ${t} (${x.toFixed(2)}ms)`)}else this.options.debug&&this.log(`Failed to apply ${t} packet (tick ${s})`)}catch(n){this.log(`Error applying ${t} update packet: ${n}`),console.error(n)}}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();console.warn(`[CLIENT] User has ${i.length} layers`),i.forEach((s,o)=>{let a=s.getOrders(),l=s.getStatic();(a.length>0||l)&&console.warn(` Layer ${o}: ${a.length} orders, static=${l}, z=${s.getZOrder()}`)})}let t=((n=this.getPrimaryRendererManager())==null?void 0:n.isReady())??!1;console.warn(`[CLIENT] Renderer ready: ${t}`)}log(e){this.options.debug&&console.warn(`[NetworkSync] ${e}`)}recordBytesReceived(e){this.totalBytesReceived+=e;let t=this.core.getUser(this.userId);t&&t.recordBytesReceived(e)}getLayerTrafficStats(){let e={},t=performance.now()-Xn;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/(Xn/1e3)}}),e}getMiscTrafficStats(){let e={},t=performance.now()-Xn;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/(Xn/1e3)}}),e}getDisplayTrafficStats(){let e={},t=performance.now()-Xn;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/(Xn/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(){this.audioManager&&(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);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){this.network.sendBridge(e,t),this.log(`Bridge sent on channel '${e}'`)}onBridge(e,t){this.network.onBridge(e,t),this.log(`Bridge handler registered for channel '${e}'`)}offBridge(e,t){this.network.offBridge(e,t),this.log(`Bridge handler removed for channel '${e}'`)}removeAllBridgeHandlers(e){this.network.removeAllBridgeHandlers(e),this.log(e?`All bridge handlers removed for '${e}'`:"All bridge handlers removed")}};Ur(Rb,"NetworkSync");var BE=Rb,Pb=class extends OE{constructor(e){var t,n,i,s,o,a,l,u,c,d;if(super({application:e.application,container:e.container,displayContainers:e.displayContainers,debug:e.debug,width:e.width,height:e.height,renderer:e.renderer,useImageDataRendering:e.useImageDataRendering,renderMode:e.renderMode}),oe(this,"input",null),oe(this,"networkSync",null),oe(this,"mode"),oe(this,"localOptions",null),oe(this,"autoplayOverlay",null),oe(this,"autoplay",!0),oe(this,"audioManager",null),oe(this,"mobileVibration",null),oe(this,"postProcessOverlay",null),oe(this,"postProcessOverlays",new Map),oe(this,"postProcessOrderCollector",new Hf),oe(this,"pendingPaletteSlotByDisplay",new Map),oe(this,"localBridgeHandlers",new Map),oe(this,"localBridgeWildcardHandlers",new Set),this.mode=e.mode,e.mode==="local"?(this.localOptions={mode:"local",application:e.application,container:e.container,debug:e.debug??!1,width:e.width??80,height:e.height??25,userId:e.userId??"local",username:e.username??"User",renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,mobileInputConfig:e.mobileInputConfig,touchZones:e.touchZones,captureInput:e.captureInput??!1,inputEnabled:e.inputEnabled??!0,autoplay:e.autoplay??!0,autoplayOptions:e.autoplayOptions,renderMode:e.renderMode??"continuous"},this.userId=e.userId??"local",this.autoplay=e.autoplay??!0):(this.localOptions={mode:"connected",application:e.application,container:e.container,serverUrl:e.serverUrl,username:e.username??"Player",debug:e.debug??!1,width:e.width??80,height:e.height??25,autoReconnect:e.autoReconnect??!0,token:e.token,renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,mobileInputConfig:e.mobileInputConfig,touchZones:e.touchZones,captureInput:e.captureInput??!1,inputEnabled:e.inputEnabled??!0,autoplay:e.autoplay??!0,autoplayOptions:e.autoplayOptions,renderMode:e.renderMode??"continuous"},this.autoplay=e.autoplay??!0),this.log(`Initializing ClientRuntime (${this.mode} mode)`),this.mode==="connected"&&(this.core=new Pw({mode:"client",maxUsers:100}),this.core.onPaletteChanged(h=>{this.onCorePaletteChanged(h),this.retryPendingPaletteSelections()}),this.core.onBitmapFontChanged(h=>{this.onCoreBitmapFontChanged(h)}),this.core.onImageFontChanged(h=>{this.onCoreImageFontChanged(h)})),e.inputEnabled??!0?this.input=new nb({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)??e.width??0,gridHeight:((u=e.touchZones)==null?void 0:u.gridHeight)??e.height??0,rendererOffsets:(c=e.touchZones)==null?void 0:c.rendererOffsets,zones:(d=e.touchZones)==null?void 0:d.zones}}):this.log("Input disabled (inputEnabled: false)"),this.mode==="connected"){let h=this.localOptions,f=new UE({url:h.serverUrl,autoReconnect:h.autoReconnect,auth:{username:h.username,token:h.token},debug:e.debug});this.networkSync=new BE(f,this.core,this.rendererManagers,this.performanceMonitor,{serverUrl:h.serverUrl,username:h.username,token:h.token,debug:e.debug,autoReconnect:h.autoReconnect,canvasWidth:e.width??80,canvasHeight:e.height??25},this.primaryDisplayId,p=>this.ensureRendererManager(p))}this.log("ClientRuntime initialized")}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 Vw(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==="connected"){this.log("setTickRate() has no effect in connected mode");return}super.setTickRate(e)}async onBeforeStart(){this.audioManager=new kb({debug:this.options.debug}),this.mobileVibration=new Yf({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 vk(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),e()}})}),this.log("Autoplay overlay dismissed, continuing startup..."))}async onAfterInit(){var t;this.rebuildPostProcessOverlays(),this.log("PostProcessOverlays created");let e=this.rendererManager.getCanvas();if(e&&this.input&&this.input.setMobileTarget(e),this.mode==="connected"&&this.networkSync){if(this.log("Connecting to server"),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(`[onAfterInit] Touch zones callback called with ${o.length} zones`);let a=s.getCanvas();if(this.log(`[onAfterInit] 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(`[onAfterInit] Grid from zones: ${l}x${u}`);let c=i.enableTouchZonesDevice(a,l,u,o);this.log(`[onAfterInit] enableTouchZonesDevice returned: ${c}`),c&&this.log(`Touch zones configured from server: ${o.length} zones`)}})}if(await this.networkSync.connect(),this.userId=await this.networkSync.joinGame(this.options.application),this.input){let i=((t=this.core.getUser(this.userId))==null?void 0:t.getDisplays())??[];if(i.length>0){let s=i[0].getSize();this.input.updateTouchZoneLayout(s.x,s.y)}}let n=this.core.getUser(this.userId);n&&this.configureUserProcessors(n)}}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.core,this));let e=this.rendererManager.getCanvas();if(e&&this.input&&this.input.setMobileTarget(e),this.mode==="connected"&&this.networkSync){if(this.log("Connecting to server"),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.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==="connected"&&this.networkSync&&this.networkSync.disconnect()}getStats(){var n;let e=super.getStats(),t=(n=this.core.getUser(this.userId))==null?void 0:n.getTotalBytesReceived();return{...e,mode:this.mode,latency:void 0,totalBytesReceived:t}}getAudioLoadingState(){if(this.mode==="connected"&&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:[]}}async onDestroy(){this.autoplayOverlay&&(this.autoplayOverlay.destroy(),this.autoplayOverlay=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null),this.postProcessOverlay&&(this.postProcessOverlay.destroy(),this.postProcessOverlay=null);for(let e of this.postProcessOverlays.values())e.destroy();this.postProcessOverlays.clear(),this.input&&this.input.destroy(),this.networkSync&&this.networkSync.destroy()}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.userId)??"local",this.log(`Creating local user: ${this.userId}`);let t=this.core.createUser(this.userId,(e==null?void 0:e.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.core,t,{username:(e==null?void 0:e.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:this.options.width??80,y:this.options.height??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==="local"){if(this.tickRate===0){let f=performance.now();this.render();let p=performance.now()-f;this.performanceMonitor.recordFrameTiming(0,p),this.rafId=requestAnimationFrame(g=>this.mainLoop(g));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.core,c),(u=(l=this.options.application).updateUser)==null||u.call(l,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 g=s.flushPostProcessCommands(),x=this.postProcessOrderCollector.convertCommands(g);this.applyPostProcessOrders(x)}if(s.hasPendingMacroOrders()){let g=s.flushMacroOrders();s.applyMacroOrders(g)}let p=s.updateMacros();if(s.processMacroEvents(p),s.hasBridgeMessages()){let g=s.getBridgeMessages();this.dispatchLocalBridgeMessages(g)}this.core.endTick().forEach(({static:g,dynamic:x})=>{let y=((g==null?void 0:g.length)??0)+((x==null?void 0:x.length)??0);s.recordBytesReceived(y)}),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.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(I=>I.getId&&I.getId()===this.primaryDisplayId)??f[0])==null?void 0:a.getSize())??{x:this.options.width,y:this.options.height},g=p.x,x=p.y,y=(u=(l=this.rendererManager.getRenderer())==null?void 0:l.getOffsets)==null?void 0:u.call(l),m={offsetX:(y==null?void 0:y.offsetX)??0,offsetY:(y==null?void 0:y.offsetY)??0};this.input.updateTouchZoneLayout(g,x,m);let v=Er.collectMousePosition(this.input,t,g,x,m);e.setMousePosition(v.x,v.y,v.over),e.updateMacroMouse(v.x,v.y,v.isLeftDown),Er.collectTouchPositions(this.input,t,g,x,10,m).forEach(I=>{e.setTouchPosition(I.id,I.x,I.y,I.over)});let b=(c=this.rendererManagers.get(this.primaryDisplayId))==null?void 0:c.getAvailableSize();b&&e.setDisplayViewport(this.primaryDisplayId,b.width,b.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(g=>{let x=i.evaluateAxis(g.bindingId,f);e.setAxis(g.name,x)}),o.forEach(g=>{let x=new Map,y=new Map,m=new Map;for(let[S,M]of p)x.set(S,M.pressed),y.set(S,M.justPressed),m.set(S,M.justReleased);let v=i.evaluateButton(g.bindingId,x),b=i.evaluateButton(g.bindingId,y),I=i.evaluateButton(g.bindingId,m);e.setButton(g.name,v),e.setButton(`${g.name}_justPressed`,b),e.setButton(`${g.name}_justReleased`,I)})}(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,g=p.getGridSize();l=g.cols,u=g.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===$t.Responsive){let p=s.getAvailableSize(),g=256*256;"getMaxCells"in o&&(g=Math.min(g,o.getMaxCells()));let x=Math.floor(p.width/c),y=Math.floor(p.height/d);if(x=Math.min(256,Math.max(1,x)),y=Math.min(256,Math.max(1,y)),x*y>g){let m=Math.sqrt(g/(x*y));x=Math.max(1,Math.floor(x*m)),y=Math.max(1,Math.floor(y*m)),this.log(`⚠️ [Display ${i}] Device limit: max ${g} cells, clamping to ${x}×${y}`)}(a.x!==x||a.y!==y)&&(this.log(`📐 [Display ${i}] Resizing display from ${a.x}×${a.y} to ${x}×${y} (available: ${p.width}×${p.height}px, cell: ${c}×${d}px)`),n.setSize(new Ht(x,y)))}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 Or.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 Or.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 Or.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 Or.SetScalingMode:{this.applyScalingMode(i,n.mode);break}case Or.SetGrid:{this.applyGridConfig(i,n);break}case Or.SwitchPalette:{this.applySwitchPalette(i,n);break}case Or.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=_f(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==="connected"&&this.networkSync)this.networkSync.sendBridge(e,t);else if(this.mode==="local"){let i=this.core.getUser(this.userId);i&&((n=this.options.application)!=null&&n.onBridgeMessage)&&(this.options.application.onBridgeMessage(this.core,i,e,t),this.log(`Bridge message sent to application on channel '${e}'`))}}onBridge(e,t){this.mode==="connected"&&this.networkSync?this.networkSync.onBridge(e,t):this.mode==="local"&&(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==="connected"&&this.networkSync?this.networkSync.offBridge(e,t):this.mode==="local"&&(e==="*"?this.localBridgeWildcardHandlers.delete(t):(n=this.localBridgeHandlers.get(e))==null||n.delete(t))}removeAllBridgeHandlers(e){this.mode==="connected"&&this.networkSync?this.networkSync.removeAllBridgeHandlers(e):this.mode==="local"&&(e===void 0?(this.localBridgeHandlers.clear(),this.localBridgeWildcardHandlers.clear()):e==="*"?this.localBridgeWildcardHandlers.clear():this.localBridgeHandlers.delete(e))}log(e){this.options.debug&&console.warn(`[ClientRuntime/${this.mode}] ${e}`)}};Ur(Pb,"ClientRuntime");var FE=Pb,LE=class{constructor(e={}){var t,n,i;oe(this,"input"),oe(this,"mobileVibration"),this.input=new nb({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 Yf({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 g=a.evaluateAxis(p.bindingId,h);e.setAxis(p.name,g)}),u.forEach(p=>{let g=new Map,x=new Map,y=new Map;for(let[I,S]of f)g.set(I,S.pressed),x.set(I,S.justPressed),y.set(I,S.justReleased);let m=a.evaluateButton(p.bindingId,g),v=a.evaluateButton(p.bindingId,x),b=a.evaluateButton(p.bindingId,y);e.setButton(p.name,m),e.setButton(`${p.name}_justPressed`,v),e.setButton(`${p.name}_justReleased`,b)})}(d=(c=this.input).poll)==null||d.call(c)}processVibrationCommands(e){e.hasMobileVibrationCommands()&&e.applyMobileVibrationCommands(e.flushMobileVibrationCommands()),e.hasGamepadVibrationCommands()&&e.applyGamepadVibrationCommands(e.flushGamepadVibrationCommands())}};Ur(LE,"InputFeature");var _E=class{constructor(e={}){oe(this,"audioManager"),oe(this,"debug"),this.debug=e.debug??!1,this.audioManager=new kb({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}`)}};Ur(_E,"AudioFeature");var $E=class{constructor(e,t={}){oe(this,"overlay"),oe(this,"orderCollector"),oe(this,"debug"),this.debug=t.debug??!1,this.overlay=new Vw(e),this.orderCollector=new Hf}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 Or.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 Or.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 Or.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 Or.SetScalingMode:{this.applyScalingMode(t,i,n.mode);break}case Or.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=_f(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}`)}};Ur($E,"PostProcessFeature");const NE={},ym=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:()=>{(NE?"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},WE=r=>r?ym(r):ym;var zb={exports:{}},Db={},Ob={exports:{}},Bb={};/**
|
|
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"}};cr(Kw,"PostProcessOverlay");var qw=Kw,Kc="\x1B[0m",hm="\x1B[H",Mk="\x1B[2J",fm="\x1B[?25l",Tk="\x1B[?25h",Uk=`
|
|
255
|
+
`,Ak=class{constructor(e={}){L(this,"options"),L(this,"fgCache",[]),L(this,"bgCache",[]),L(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+=fm),this.options.includeHome&&(o+=hm);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],g=p.fgColorIndex,C=p.bgColorIndex;u?(C!==l&&(o+=this.bgCache[C],l=C),g!==a&&(o+=this.fgCache[g],a=g)):(o+=this.bgCache[C],o+=this.fgCache[g]),o+=p.char||" "}c&&d<n-1&&(o+=Uk)}return this.options.includeReset&&(o+=Kc),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+=Kc),o}clear(){return Mk+hm}showCursor(){return Tk}hideCursor(){return fm}reset(){return Kc}moveTo(e,t){return`\x1B[${e+1};${t+1}H`}};cr(Ak,"TerminalANSI");function Rk(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}}cr(Rk,"hexToRGB");function Pk(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}`}cr(Pk,"rgbToHex");function zk(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}}cr(zk,"createTestRenderState");var Qw=Object.defineProperty,Dk=(r,e,t)=>e in r?Qw(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wr=(r,e)=>Qw(r,"name",{value:e,configurable:!0}),ke=(r,e,t)=>(Dk(r,typeof e!="symbol"?e+"":e,t),t),Ok=(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))(Ok||{}),Jw=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){this.config.debug&&console.warn("[InputSystem]",...e)}};wr(Jw,"BaseInputs");var $a=Jw;function Bk(r){return typeof r=="object"&&r!==null&&"start"in r&&"stop"in r&&"reset"in r&&"isListening"in r&&"destroy"in r}wr(Bk,"isInputs");var eb=class extends $a{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(eb,"KeyboardInputs");var tb=eb;function Fk(r,e){let t=new tb(r);return e&&t.setCallbacks(e),t.start(),t}wr(Fk,"useKeyboardInputs");var Sh=class rb extends $a{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",Ht.zero()),ke(this,"mouseDelta",Ht.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=Ht.zero(),this.mouseDelta=Ht.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=Ht.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=rb.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 Ht(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(Sh,"MouseInputs"),ke(Sh,"BUTTON_NAMES",["left","middle","right"]);var nb=Sh;function Lk(r,e){let t=new nb(r);return e&&t.setCallbacks(e),t.start(),t}wr(Lk,"useMouseInputs");var ib=class extends $a{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 Ht(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 Ht(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 Ht(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(ib,"MobileInputs");var kh=ib;function _k(r,e,t){console.warn("[MobileInputs] useMobileInputs() is deprecated and causes memory leaks. Use useMemo + useEffect instead.");let n=new kh(r,t);return e&&n.setCallbacks(e),n.start(),n}wr(_k,"useMobileInputs");var sb=class extends $a{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,g=Math.floor(f/a),C=Math.floor(p/l);for(let y of this.zones)this.isInsideZone(g,C,y)&&(u.set(y.id,(u.get(y.id)??0)+1),c.set(y.id,{x:Math.max(y.x,Math.min(y.x+y.width-1,g)),y:Math.max(y.y,Math.min(y.y+y.height-1,C))}))}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 g=c.get(h.id);g&&(f.lastX=g.x,f.lastY=g.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(sb,"TouchZoneInputs");var pm=sb,bn={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]},ob=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(bn.tap)}mediumTap(){return this.vibrate(bn.mediumTap)}heavyTap(){return this.vibrate(bn.heavyTap)}success(){return this.vibrate(bn.success)}error(){return this.vibrate(bn.error)}warning(){return this.vibrate(bn.warning)}selection(){return this.vibrate(bn.selection)}impactLight(){return this.vibrate(bn.impactLight)}impactMedium(){return this.vibrate(bn.impactMedium)}impactHeavy(){return this.vibrate(bn.impactHeavy)}notification(){return this.vibrate(bn.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(ob,"MobileVibration");var Zf=ob,qc=null;function $k(){return qc||(qc=new Zf),qc}wr($k,"getMobileVibration");var Nk=.01,ab=class extends $a{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)>Nk&&((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(ab,"GamepadInputs");var lb=ab;function Wk(r,e){let t=new lb(e);return r&&t.setGamepadCallbacks(r),t.start(),t}wr(Wk,"useGamepadInputs");var ub=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 tb(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 nb(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 lb({debug:this.config.debug}),this.gamepad.start(),this.log("Gamepad initialized")),this.config.enableMobile&&(this.config.mobileTargetElement?(this.mobile=new kh(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 pm(this.mobile,d),this.log("Touch zones initialized")}}}getButton(e,t){if(!da({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(!da({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(!da({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(!Bv({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=Ri[e];return this.keyboard.isKeyPressed(t)}getKeyboardButtonJustPressed(e){if(!this.keyboard)return!1;let t=Ri[e];return this.keyboard.isKeyJustPressed(t)}getKeyboardButtonJustReleased(e){if(!this.keyboard)return!1;let t=Ri[e];return this.keyboard.isKeyJustReleased(t)}getMouseButton(e){if(!this.mouse)return!1;switch(e){case _t.LeftButton:return this.mouse.isLeftMousePressed();case _t.RightButton:return this.mouse.isRightMousePressed();case _t.MiddleButton:return this.mouse.isMiddleMousePressed();default:return!1}}getMouseButtonJustPressed(e){if(!this.mouse)return!1;switch(e){case _t.LeftButton:return this.mouse.isLeftMouseJustPressed();case _t.RightButton:return this.mouse.isRightMouseJustPressed();case _t.MiddleButton:return this.mouse.isMiddleMouseJustPressed();default:return!1}}getMouseButtonJustReleased(e){if(!this.mouse)return!1;switch(e){case _t.LeftButton:return this.mouse.isLeftMouseJustReleased();case _t.RightButton:return this.mouse.isRightMouseJustReleased();case _t.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 _t.PositionX:return this.mouse.getMousePosition().x;case _t.PositionY:return this.mouse.getMousePosition().y;case _t.DeltaX:return this.mouse.getMouseDelta().x;case _t.DeltaY:return this.mouse.getMouseDelta().y;case _t.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 kh(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 pm(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){this.config.debug&&console.warn(`[InputRouter] ${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=>{i.preventDefault()},{passive:!1})}};wr(ub,"UnifiedInputRouter");var cb=ub,gm=100,mm=2,db=class Eh{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 g of p.sources){if(n.has(g.sourceId))continue;let C=!1,y=!1,m=!1,v=!1;g.type===ce.Keyboard&&g.key!==void 0?(C=t.getButton(ce.Keyboard,g.key),y=((i=t.getButtonJustPressed)==null?void 0:i.call(t,ce.Keyboard,g.key))??!1,m=((s=t.getButtonJustReleased)==null?void 0:s.call(t,ce.Keyboard,g.key))??!1,v=!0):g.type===ce.Mouse&&g.mouseButton!==void 0?(C=t.getButton(ce.Mouse,g.mouseButton),y=((o=t.getButtonJustPressed)==null?void 0:o.call(t,ce.Mouse,g.mouseButton))??!1,m=((a=t.getButtonJustReleased)==null?void 0:a.call(t,ce.Mouse,g.mouseButton))??!1,v=!0):g.type===ce.Gamepad&&g.button!==void 0?(C=t.getButton(ce.Gamepad,g.button),y=((l=t.getButtonJustPressed)==null?void 0:l.call(t,ce.Gamepad,g.button))??!1,m=((u=t.getButtonJustReleased)==null?void 0:u.call(t,ce.Gamepad,g.button))??!1,v=!0):g.type===ce.Touch&&g.touchButton!==void 0?(C=t.getButton(ce.Touch,g.touchButton),y=((c=t.getButtonJustPressed)==null?void 0:c.call(t,ce.Touch,g.touchButton))??!1,m=((d=t.getButtonJustReleased)==null?void 0:d.call(t,ce.Touch,g.touchButton))??!1,v=!0):g.type===ce.TouchZone&&g.touchZoneId!==void 0&&(C=t.getButton(ce.TouchZone,g.touchZoneId),y=((h=t.getButtonJustPressed)==null?void 0:h.call(t,ce.TouchZone,g.touchZoneId))??!1,m=((f=t.getButtonJustReleased)==null?void 0:f.call(t,ce.TouchZone,g.touchZoneId))??!1,v=!0),v&&n.set(g.sourceId,{pressed:C,justPressed:y,justReleased:m})}return n}static collectMousePosition(e,t,n,i,s){var S;let o=e.getAxis(ce.Mouse,_t.PositionX),a=e.getAxis(ce.Mouse,_t.PositionY),l=((S=e.isLeftMousePressed)==null?void 0:S.call(e))??!1,{renderWidth:u,renderHeight:c,offsetX:d,offsetY:h,rect:f}=Eh.calculateRenderMetrics(t,s),p=o-f.left-d,g=a-f.top-h,C=u/n,y=c/i,m=Math.floor(p/C),v=Math.floor(g/y),b=p>=0&&p<u&&g>=0&&g<c;return{x:Math.max(0,Math.min(n-1,m)),y:Math.max(0,Math.min(i-1,v)),over:b,isLeftDown:l}}static collectTouchPositions(e,t,n,i,s=10,o){let a=[],{renderWidth:l,renderHeight:u,offsetX:c,offsetY:d,rect:h}=Eh.calculateRenderMetrics(t,o),f=l/n,p=u/i;for(let g=0;g<s;g++){let C=g;if(e.getButton(ce.Touch,C)){let y=gm+g*mm,m=gm+g*mm+1,v=e.getAxis(ce.Touch,y),b=e.getAxis(ce.Touch,m),S=v-h.left-c,I=b-h.top-d,E=Math.floor(S/f),U=Math.floor(I/p),z=S>=0&&S<l&&I>=0&&I<u;a.push({id:g,x:Math.max(0,Math.min(n-1,E)),y:Math.max(0,Math.min(i-1,U)),over:z})}}return a}static collectTextInputs(e){return typeof e.getTextInputs=="function"?e.getTextInputs():[]}};wr(db,"InputCollector");var Er=db;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 Dl=Object.create(null);Object.keys(Yn).forEach(r=>{Dl[Yn[r]]=r});const Mh={type:"error",data:"parser error"},hb=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",fb=typeof ArrayBuffer=="function",pb=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,Kf=({type:r,data:e},t,n)=>hb&&e instanceof Blob?t?n(e):ym(e,n):fb&&(e instanceof ArrayBuffer||pb(e))?t?n(e):ym(new Blob([e]),n):n(Yn[r]+(e||"")),ym=(r,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)};function vm(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Qc;function Hk(r,e){if(hb&&r.data instanceof Blob)return r.data.arrayBuffer().then(vm).then(e);if(fb&&(r.data instanceof ArrayBuffer||pb(r.data)))return e(vm(r.data));Kf(r,!1,t=>{Qc||(Qc=new TextEncoder),e(Qc.encode(t))})}const wm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ko=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<wm.length;r++)Ko[wm.charCodeAt(r)]=r;const Vk=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=Ko[r.charCodeAt(n)],o=Ko[r.charCodeAt(n+1)],a=Ko[r.charCodeAt(n+2)],l=Ko[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},jk=typeof ArrayBuffer=="function",qf=(r,e)=>{if(typeof r!="string")return{type:"message",data:gb(r,e)};const t=r.charAt(0);return t==="b"?{type:"message",data:Yk(r.substring(1),e)}:Dl[t]?r.length>1?{type:Dl[t],data:r.substring(1)}:{type:Dl[t]}:Mh},Yk=(r,e)=>{if(jk){const t=Vk(r);return gb(t,e)}else return{base64:!0,data:r}},gb=(r,e)=>{switch(e){case"blob":return r instanceof Blob?r:new Blob([r]);case"arraybuffer":default:return r instanceof ArrayBuffer?r:r.buffer}},mb="",Gk=(r,e)=>{const t=r.length,n=new Array(t);let i=0;r.forEach((s,o)=>{Kf(s,!1,a=>{n[o]=a,++i===t&&e(n.join(mb))})})},Xk=(r,e)=>{const t=r.split(mb),n=[];for(let i=0;i<t.length;i++){const s=qf(t[i],e);if(n.push(s),s.type==="error")break}return n};function Zk(){return new TransformStream({transform(r,e){Hk(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 Jc;function hl(r){return r.reduce((e,t)=>e+t.length,0)}function fl(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 Kk(r,e){Jc||(Jc=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(hl(t)<1)break;const l=fl(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(hl(t)<2)break;const l=fl(t,2);i=new DataView(l.buffer,l.byteOffset,l.length).getUint16(0),n=3}else if(n===2){if(hl(t)<8)break;const l=fl(t,8),u=new DataView(l.buffer,l.byteOffset,l.length),c=u.getUint32(0);if(c>Math.pow(2,21)-1){a.enqueue(Mh);break}i=c*Math.pow(2,32)+u.getUint32(4),n=3}else{if(hl(t)<i)break;const l=fl(t,i);a.enqueue(qf(s?l:Jc.decode(l),e)),n=0}if(i===0||i>r){a.enqueue(Mh);break}}}})}const yb=4;function Dt(r){if(r)return qk(r)}function qk(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 zu=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),dn=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Qk="arraybuffer";function vb(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}const Jk=dn.setTimeout,eE=dn.clearTimeout;function Du(r,e){e.useNativeTimers?(r.setTimeoutFn=Jk.bind(dn),r.clearTimeoutFn=eE.bind(dn)):(r.setTimeoutFn=dn.setTimeout.bind(dn),r.clearTimeoutFn=dn.clearTimeout.bind(dn))}const tE=1.33;function rE(r){return typeof r=="string"?nE(r):Math.ceil((r.byteLength||r.size)*tE)}function nE(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 wb(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function iE(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function sE(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 oE extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Qf extends Dt{constructor(e){super(),this.writable=!1,Du(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 oE(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=qf(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=iE(e);return t.length?"?"+t:""}}class aE extends Qf{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)};Xk(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,Gk(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]=wb()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let bb=!1;try{bb=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const lE=bb;function uE(){}class cE extends aE{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,Du(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=vb(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=uE,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",bm);else if(typeof addEventListener=="function"){const r="onpagehide"in dn?"pagehide":"unload";addEventListener(r,bm,!1)}}function bm(){for(let r in jn.requests)jn.requests.hasOwnProperty(r)&&jn.requests[r].abort()}const dE=function(){const r=Cb({xdomain:!1});return r&&r.responseType!==null}();class hE extends cE{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=dE&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new jn(Cb,this.uri(),e)}}function Cb(r){const e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||lE))return new XMLHttpRequest}catch{}if(!e)try{return new dn[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const xb=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class fE extends Qf{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=xb?{}:vb(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;Kf(n,this.supportsBinary,s=>{try{this.doWrite(n,s)}catch{}i&&zu(()=>{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]=wb()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const ed=dn.WebSocket||dn.MozWebSocket;class pE extends fE{createSocket(e,t,n){return xb?new ed(e,t,n):t?new ed(e,t):new ed(e)}doWrite(e,t){this.ws.send(t)}}class gE extends Qf{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=Kk(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=Zk();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&&zu(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const mE={websocket:pE,webtransport:gE,polling:hE},yE=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,vE=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Th(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=yE.exec(r||""),s={},o=14;for(;o--;)s[vE[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=wE(s,s.path),s.queryKey=bE(s,s.query),s}function wE(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 bE(r,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,s){i&&(t[i]=s)}),t}const Uh=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ol=[];Uh&&addEventListener("offline",()=>{Ol.forEach(r=>r())},!1);class zi extends Dt{constructor(e,t){if(super(),this.binaryType=Qk,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=Th(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=Th(t.host).host);Du(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=sE(this.opts.query)),Uh&&(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"})},Ol.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=yb,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&&zi.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",zi.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+=rE(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,zu(()=>{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(zi.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(),Uh&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Ol.indexOf(this._offlineEventListener);n!==-1&&Ol.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}zi.protocol=yb;class CE extends zi{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;zi.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;zi.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 xE=class extends CE{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=>mE[i]).filter(i=>!!i)),super(e,n)}};function IE(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=Th(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 SE=typeof ArrayBuffer=="function",kE=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,Ib=Object.prototype.toString,EE=typeof Blob=="function"||typeof Blob<"u"&&Ib.call(Blob)==="[object BlobConstructor]",ME=typeof File=="function"||typeof File<"u"&&Ib.call(File)==="[object FileConstructor]";function Jf(r){return SE&&(r instanceof ArrayBuffer||kE(r))||EE&&r instanceof Blob||ME&&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(Jf(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 TE(r){const e=[],t=r.data,n=r;return n.data=Ah(t,e),n.attachments=e.length,{packet:n,buffers:e}}function Ah(r,e){if(!r)return r;if(Jf(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]=Ah(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]=Ah(r[n],e));return t}return r}function UE(r,e){return r.data=Rh(r.data,e),delete r.attachments,r}function Rh(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]=Rh(r[t],e);else if(typeof r=="object")for(const t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=Rh(r[t],e));return r}const AE=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],RE=5;var ze;(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"})(ze||(ze={}));class PE{constructor(e){this.replacer=e}encode(e){return(e.type===ze.EVENT||e.type===ze.ACK)&&Bl(e)?this.encodeAsBinary({type:e.type===ze.EVENT?ze.BINARY_EVENT:ze.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===ze.BINARY_EVENT||e.type===ze.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=TE(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}function Cm(r){return Object.prototype.toString.call(r)==="[object Object]"}class ep 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===ze.BINARY_EVENT;n||t.type===ze.BINARY_ACK?(t.type=n?ze.EVENT:ze.ACK,this.reconstructor=new zE(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Jf(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(ze[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===ze.BINARY_EVENT||n.type===ze.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(ep.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 ze.CONNECT:return Cm(t);case ze.DISCONNECT:return t===void 0;case ze.CONNECT_ERROR:return typeof t=="string"||Cm(t);case ze.EVENT:case ze.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&AE.indexOf(t[0])===-1);case ze.ACK:case ze.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class zE{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=UE(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const DE=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ep,Encoder:PE,get PacketType(){return ze},protocol:RE},Symbol.toStringTag,{value:"Module"}));function Sn(r,e,t){return r.on(e,t),function(){r.off(e,t)}}const OE=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Sb 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=[Sn(e,"open",this.onopen.bind(this)),Sn(e,"packet",this.onpacket.bind(this)),Sn(e,"error",this.onerror.bind(this)),Sn(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(OE.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:ze.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:ze.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 ze.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 ze.EVENT:case ze.BINARY_EVENT:this.onevent(e);break;case ze.ACK:case ze.BINARY_ACK:this.onack(e);break;case ze.DISCONNECT:this.ondisconnect();break;case ze.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:ze.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:ze.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 wo(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}wo.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};wo.prototype.reset=function(){this.attempts=0};wo.prototype.setMin=function(r){this.ms=r};wo.prototype.setMax=function(r){this.max=r};wo.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,Du(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 wo({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||DE;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 xE(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=Sn(t,"open",function(){n.onopen(),e&&e()}),s=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=Sn(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(Sn(e,"ping",this.onping.bind(this)),Sn(e,"data",this.ondata.bind(this)),Sn(e,"error",this.onerror.bind(this)),Sn(e,"close",this.onclose.bind(this)),Sn(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){zu(()=>{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 Sb(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 _o={};function Fl(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};const t=IE(r,e.path||"/socket.io"),n=t.source,i=t.id,s=t.path,o=_o[i]&&s in _o[i].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let l;return a?l=new Ph(n,e):(_o[i]||(_o[i]=new Ph(n,e)),l=_o[i]),t.query&&!e.query&&(e.query=t.queryKey),l.socket(t.path,e)}Object.assign(Fl,{Manager:Ph,Socket:Sb,io:Fl,connect:Fl});var kb=Object.defineProperty,BE=(r,e,t)=>e in r?kb(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Eb=(r,e)=>kb(r,"name",{value:e,configurable:!0}),gi=(r,e,t)=>(BE(r,typeof e!="symbol"?e+"":e,t),t),Mb=class{constructor(e){if(gi(this,"socket",null),gi(this,"options"),gi(this,"_state",on.Disconnected),gi(this,"pingTimestamp",0),gi(this,"latency",0),gi(this,"pingInterval",null),gi(this,"bridgeHandlers",new Map),gi(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??{},debug:e.debug??!1},this.log("Client initialized",{url:this.options.url,autoReconnect:this.options.autoReconnect})}get state(){return this._state}isConnected(){var e;return this._state===on.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=on.Connecting,this.bridgeSetup=!1,new Promise((e,t)=>{this.socket=Fl(this.options.url,{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=on.Connected,this.startPingMonitor(),this.bridgeHandlers.size>0&&this.setupBridgeListener(),e()}),this.socket.on("connect_error",n=>{this.log(`Connection error: ${n.message}`),this._state=on.Error,t(n)}),this.socket.on("disconnect",n=>{this.log(`Disconnected: ${n}`),this._state=on.Disconnected,this.stopPingMonitor()}),this.socket.on("reconnect_attempt",n=>{this.log(`Reconnection attempt ${n}...`),this._state=on.Reconnecting}),this.socket.on("reconnect",n=>{this.log(`Reconnected after ${n} attempts`),this._state=on.Connected,this.startPingMonitor()}),this.socket.on("reconnect_failed",()=>{this.log("Reconnection failed"),this._state=on.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=on.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.volatile.emit(e,t)}catch(n){this.log(`Error sending '${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=Eb(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=on.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}`))}};Eb(Mb,"SocketIOClient");var FE=Mb,Tb=Object.defineProperty,LE=(r,e,t)=>e in r?Tb(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ub=(r,e)=>Tb(r,"name",{value:e,configurable:!0}),or=(r,e,t)=>(LE(r,typeof e!="symbol"?e+"":e,t),t),Ab=class{constructor(e,t=!1){or(this,"sounds",new Map),or(this,"nameToId",new Map),or(this,"audioContext"),or(this,"debug"),this.audioContext=e,this.debug=t,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:g,value:C}=await c.read();if(g)break;d.push(C),h+=C.length,i(h,a)}let f=new Uint8Array(h),p=0;for(let g of d)f.set(g,p),p+=g.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){this.debug&&console.warn(`[SoundBank] ${e}`)}};Ub(Ab,"SoundBank");var _E=Ab,Rb=class{constructor(e={}){or(this,"audioContext",null),or(this,"masterGainNode",null),or(this,"soundBank",null),or(this,"options"),or(this,"initialized",!1),or(this,"nextInstanceId",1),or(this,"instances",new Map),or(this,"instancesBySound",new Map),or(this,"activeSounds",new Set),or(this,"spatialSounds",new Map),or(this,"spatialConfig",{listenerX:0,listenerY:0,maxDistance:200,referenceDistance:20,rolloffFactor:1,panSpread:1}),or(this,"reverbConvolver",null),or(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 _E(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:g,distanceVolume:C}=this.calculateSpatialAudio(t.position.x,t.position.y),y=i.createStereoPanner();y.pan.value=g,d=u>0?0:l*C,h=l*C,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(y),y.connect(this.masterGainNode),c.pannerNode=y,c.position={x:t.position.x,y:t.position.y},c.targetVolume=h,c.outputNode=y,this.spatialSounds.set(o,{gainNode:a,pannerNode:y,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=${g.toFixed(2)} vol=${C.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 g=p.get(s);return g!==void 0&&!g.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)}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){this.options.debug&&console.warn(`[AudioManager] ${e}`)}};Ub(Rb,"AudioManager");var Pb=Rb,zb=Object.defineProperty,$E=(r,e,t)=>e in r?zb(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ur=(r,e)=>zb(r,"name",{value:e,configurable:!0}),oe=(r,e,t)=>($E(r,typeof e!="symbol"?e+"":e,t),t),tp=(r=>(r.TerminalGL="webgl",r.Terminal2D="terminal2d",r))(tp||{}),Db=class{constructor(e=60){if(oe(this,"frameCount",0),oe(this,"fps",0),oe(this,"fpsUpdateTime",0),oe(this,"lastCoreTime",0),oe(this,"lastRenderTime",0),oe(this,"lastTotalTime",0),oe(this,"coreTimeSamples",[]),oe(this,"renderTimeSamples",[]),oe(this,"totalTimeSamples",[]),oe(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}};Ur(Db,"PerformanceMonitor");var NE=Db,WE="iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAI/klEQVR4Ae3BUW5jyZYEQQ9C+99yjGNwPhKJS4pkSyrVqzTjOI7jOI7jOI7jOI7jOP45Hbyhg0908EuE4/9VLCJU8UBUsYi4ULGI+MPCQcWFqOINEYuKCxF/0I1/XMUdVcQdEX+5G8enIjYRithEbCI2Ecffo4MLHXyig+P4DcILKhSxqFBUoYhFhaIKRWwqFDEqFHFHxYi4UKGIOyoUsahQxP+QG79EB6ODCx2MCkWo4g0VithEqGLTwehg08Ef1oFu/ICKUTEqVKEIZYEyUIUivlCFIu6IUMUiQh0o4heqUITCCyoU8aIKRRWKGBWbiEWFIjYVI+JFFYp4oEIRqnggqrgQ8YSKCxEvqFDECC+oUMQLKu6IWFRRhSJUoYhNhaIKRVXEEyoU8UCFIhYVi4hNhSJ+WIUiFuGHVCiqUIQqLkSoQhGqUIQqFKEKRbygQhEXKhSxqFCEKhSxqFDEhQpFvKFCEYsKRWzCCyoU8aIKRRWKWFQo4oEKRYyKEVUo4gUVilhUKOKbVCjiDRWKOP4uHfywMCoWEZsKRWwqFhGLikXEhQpFjIoLEYuKETEqLkSMikXEomIR8Q0qFPGCCkVcqFhEKKhCEapQxKgYEYsKRahCEapQhCoUsagYEaNCEXdUKOITFYpQhSJUoQhVKEIVivhCFYp4Q4UiFhWKUIWiDzYVF6KKCxEPRHyi4hMVI2JUKOITFYr4YhWKuFChiE2FIjYVFyIWUUfEiBgVilBQxYWIRYUi7qhQxKZiRIwKRRWKuKNCEarYRGwqFLGpWEQsKjYRiwpFXKhQxKJCEV+gQhGLCkWMoIoRVShiUaGICxWKeKBCEaq4EHGhQhGqUIQqFDEqFLGpUIQqFHGhQhFfpEIRm4oLEZsKRWwqFDE+WES8qUIRmwpFXIgYFYoYFYr4wyoUsalQxIUKRWyijohFxBMqFHEhYhNGxSJiVFyIUMWFiFGxiLhQoYhFxSJiUbGIWFQo4kLFImJRMSIuVCjiQoUi7qhQxAsqFHFHhSKOn9XBLxNGxSJiUbGIGBWbiEXFImJULCIWFRciVHEhYlQsIkaFIlShCFVciBgVmwhVKEIVilCFIi5UKGJUKKpQhCoUMSoWEbqhCmWgilGhDFSxyUAVo0IZqGIToYoL2bDJhlGhDFTxpAxGBosMRsSFCkW8qEIVL6hQBqrQjU3FN8vgQoQqvkkGP6xCEW+quKPiRR9ciCo2FQ9UjIgvVjEiNhUj4kLFiFhUfLOIN0VVVHGh4gU3LlRcyOCODFTxxbLgQhbcEXFHBt+o4j+IuCPiRTc2WfBNOrhQoYi/RAefiFDFN4l4wQeKOhgRL6oYESPqYERsKhRxoWIR8YSogxHxpIpFhSIUdaCIO6KOiEXFIuILRB2MiOMIqthELCoWEaNiE7GoWESMigsRqlCEKhShCkWoQhGqUMSoUFShCFUoQhWKUIUiVHEhYlQsIl5QsYjYVCjiSTcWGahiVCgDVWwyUMWoUAaqGBmMDP4S2fBABosOHsjgjopR8aQbf0AGv0SEOlDEGyoU8aQIVbyhQhmo4gk3Fh0o4kUdKGJEqAv+kIoLESNiEaEOFLGpUMSLIlTxogxGBk+4sciCO6qICxF3ZIEqfliFKjYVo2ITMSI2FYp4U4QqfsiNN1QRFyJUMTr4JhHqQBEXIjYVykAVT6pQxH8UoYof8METoo6oI+IJUQcj4klRByNiEVUo4kKEooovVrGI2FQo4o6ITcUbKo7jnjAqFPGiCkV8gQpFvKBiRDypQhEPVCjijgpFjApF3FExIn7IjRGhir9QhSJU8cUyeCCDF0X8AR8soo6IRcUiYlMxIhYVi4hFxQMVi4g7IjYVm4hFxYhYVIyICxUj4o4KRTyhQhGqUIQqNhGLikWEbmwy2GSBKjYZqGJUKANVjAplsKlQBqoYFaODRYUyuCMDVSwiPhHxiQpFvKiDUbHIQBWjQhmoQh88qeKLRLyh4kJUoYhfqkIRb4iqqOILfPCECkWo4j+oUMQLIt4QdfAHRR0Rv8CNJ0Sogzs6UMSIUAeKGBHqYBOhLnhRFryhYlQsOnhChCoWFaPijogXRagDRSj8IyoWEV+oYkT8JcIvUaGI/2EVI2JRoYhFxYi4UKGIUUU8cOP4MRXK4EkZqGJToahCFU/4QBWbiEXFJkIViioUsajYRKhiVChiVChCFYpQhSJUoQhVKGJUKKpQhCoUoQpFqEIRqrgQ8UMiFFUo4hMfLCLUEaEKRajiQhV1RKhCEReiCkV8oypiEXUwIp4UMSoUMSpGxJuiDhShiEXEk258oQhlMCLUBb9MxIh4Q4UiFhmo4k0VyuAL3Fh0oIgRoQ7ekAWquKODJ0WoA0VsKlSxqRgViwh1cKFCEX+RoApFPKFCEapQxIWKTcSmYkQsKjYRiwpFbCoUVShCFYpQhSIuVChCFRciNhUjYlGhiEXFiPhCQRWKeEKFIv4RFYuI4ziO4ziO4ziO4ziO4ziO4ziO4ziO4ziO4ziO4ziO4ziO4ziO36BiUaGKRcWiQhWqUMWmgzs6+IU6UAeLDtTBCzpQBz/gVqEIVShCEapQhCoUVVEVVVHF8avdIlShCFWoQhGqUISqqIqqqIo4frVUEaOK2FQRo4pQFVVRFVURo0IRo2IT8UtUXIhYVCiqUFRxIUIVFyK+QMUmYlexqFDFomJRoQpVqGLTwR0d/EIdqINFB+pg0YE6+GEdLG4VilCFIhShCkWoQlEVVVEVVRy/2i1CFYpQhSoUoQpFqIqqqIqqiONXu1UoQhWKUIQqFKEKRVVURVVUcfw9Orijgzd18KYOvkEH6uAFHaiDF3SgDl7QgTp4wo3jn3bj+KeFRcUXixgVXyziC1RciFDFN4hQxTeIeOCDRcR/UKGIByLeUKGILxbxhKhCEU+qUFShiE1UoYgnVSiqUMQnPjh+tYoHIv6DD45fLeIb3Tj+aeF4WoUinlTxQMQDFYuIBypecOP4p904/mkfHA9VPKniL/PB8VDEiyJGxQMV3yjigRvHP+3G8U+7cRzHcRzHcRzHcRzHcRzHcRzHcRzHcRzHcfxP+T9Q99xxOxB1qwAAAABJRU5ErkJggg==",$o={glyphWidth:8,glyphHeight:8,cellWidth:8,cellHeight:8,atlasBlocks:1};function Ob(){let r=atob(WE),e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}Ur(Ob,"decodeDefaultAtlas");var Bb=class{constructor(e,t={}){oe(this,"renderer"),oe(this,"options"),oe(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=Ob();await this.renderer.setImageFont(t,$o.glyphWidth,$o.glyphHeight,$o.cellWidth,$o.cellHeight,$o.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=Ur(()=>{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?(this.renderer.renderDisplayData(e),!0):(console.warn("[RENDERER MANAGER] No display provided"),!1):(console.warn("[RENDERER MANAGER] Renderer not ready"),!1)}render(e,t){let n=this.layerFilter?e.getRenderState(t,this.layerFilter):e.getRenderState(t);return!n||n.displays.length===0?(console.warn("[RENDERER MANAGER] No render state or no displays"),!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){this.options.debug&&console.warn(`[RendererManager] ${e}`)}};Ur(Bb,"RendererManager");var xm=Bb,Fb=class{constructor(e){if(oe(this,"core"),oe(this,"rendererManagers",new Map),oe(this,"rendererInitPromises",new Map),oe(this,"rendererManager"),oe(this,"rendererType"),oe(this,"primaryDisplayId",0),oe(this,"displayConfigs"),oe(this,"options"),oe(this,"running",!1),oe(this,"startTime",0),oe(this,"lastTimestamp",0),oe(this,"userId",""),oe(this,"visibilityChangeHandler"),oe(this,"tickRate",30),oe(this,"accumulatedTime",0),oe(this,"FRAME_TIME_MIN",1e3/60),oe(this,"lastRenderTimestamp",0),oe(this,"rafId",0),oe(this,"firstTickDone",!1),oe(this,"performanceMonitor"),oe(this,"renderMode","continuous"),oe(this,"renderRequested",!1),this.options={application:e.application,container:e.container,displayContainers:e.displayContainers,debug:e.debug??!1,width:e.width??80,height:e.height??25,renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,renderMode:e.renderMode??"continuous"},this.log("Initializing BaseClientRuntime"),this.core=new _w({mode:"client",maxUsers:1}),this.core.onPaletteChanged(t=>{this.onCorePaletteChanged(t)}),this.core.onBitmapFontChanged(t=>{this.onCoreBitmapFontChanged(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 NE(60),this.tickRate=20,this.renderMode=e.renderMode??"continuous",this.log(`Configured: tickRate=${this.tickRate}, renderMode=${this.renderMode}`),this.log("BaseClientRuntime initialized")}createRenderer(e,t){if(t==="terminal2d"){this.log("Creating Terminal 2D renderer");let s=new kk(e,{fixedCols:this.options.width,fixedRows:this.options.height,cellAspectRatio:1});return this.options.useImageDataRendering&&(this.log("Enabling ImageData rendering (pixel-perfect, optimized)"),s.setImageDataRendering(!0)),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 xk(e,{cols:this.options.width,rows:this.options.height,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 xm(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 xm(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}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.core,this)),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.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();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.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(g=>this.mainLoop(g));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.core,o),(h=(d=this.options.application).updateUser)==null||h.call(d,this.core,s,o)),this.processTickOrders(s);let p=s.updateMacros();s.processMacroEvents(p),this.core.endTick().forEach(({static:g,dynamic:C})=>{let y=((g==null?void 0:g.length)??0)+((C==null?void 0:C.length)??0);s.recordBytesReceived(y)}),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){console.warn("[BaseClientRuntime] No render state or displays");return}for(let n of t.displays){let i=this.rendererManagers.get(n.id)??this.ensureRendererManager(n.id);if(!i){console.warn(`[BaseClientRuntime] No renderer manager for display ${n.id}, skipping render`);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(l=>l.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}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=Ur(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?console.warn("[BaseClientRuntime] Cannot update palette: no renderer available"):this.log(`✓ Palette updated on ${i} renderer(s)`)}onCoreBitmapFontChanged(e){this.log(`Bitmap font ${e} changed, updating renderer`);let t=this.core.getBitmapFont(e);if(!t){console.warn(`[BaseClientRuntime] Font ${e} not found in registry`);return}let n=new Map,i=0;for(let a=0;a<256;a++){let l=t.getGlyph(a);l&&(n.set(a,l),i++)}this.log(`Built bitmap font map with ${i} glyphs, dimensions: ${t.getCharWidth()}x${t.getCharHeight()}`);let s=Ur(a=>{a&&"setBitmapFont"in a&&typeof a.setBitmapFont=="function"&&a.setBitmapFont(n,t.getCharWidth(),t.getCharHeight(),t.getCellWidth(),t.getCellHeight())},"applyBitmapFont"),o=0;for(let[a,l]of this.rendererManagers.entries()){let u=l.getRenderer();u&&(s(u),o++,this.onFontChanged(u,a))}o===0?console.warn("[BaseClientRuntime] Cannot update font: no renderer available"):this.log(`✓ Renderer bitmap font updated successfully on ${o} renderer(s)`)}onCoreImageFontChanged(e){this.log(`Image font ${e} changed, updating renderer`);let t=this.core.getImageFont(e);if(!t){console.warn(`[BaseClientRuntime] Image font ${e} not found in registry`);return}this.log(`Loading image font with ${t.getAtlasBlocks()} blocks, glyph: ${t.getGlyphWidth()}x${t.getGlyphHeight()}`);let n=Ur(s=>{s&&"setImageFont"in s&&typeof s.setImageFont=="function"&&s.setImageFont(t.getImageData(),t.getGlyphWidth(),t.getGlyphHeight(),t.getCellWidth(),t.getCellHeight(),t.getAtlasBlocks())},"applyImageFont"),i=0;for(let[s,o]of this.rendererManagers.entries()){let a=o.getRenderer();a&&(n(a),i++,this.onFontChanged(a,s))}i===0?console.warn("[BaseClientRuntime] Cannot update image font: no renderer available"):this.log(`✓ Renderer image font updated successfully on ${i} renderer(s)`)}onFontChanged(e,t){}log(e){this.options.debug&&console.warn(`[BaseClientRuntime] ${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}};Ur(Fb,"BaseClientRuntime");var HE=Fb,Xn=1e3,Lb=class{constructor(e,t,n,i,s,o,a){oe(this,"network"),oe(this,"core"),oe(this,"rendererManagers"),oe(this,"primaryDisplayId"),oe(this,"performanceMonitor"),oe(this,"options"),oe(this,"layerTraffic",new Map),oe(this,"miscTraffic",new Map),oe(this,"displayTraffic",new Map),oe(this,"audioManager",null),oe(this,"postProcessCallback",null),oe(this,"userId",""),oe(this,"lastReceivedTick",-1),oe(this,"connected",!1),oe(this,"totalBytesReceived",0),oe(this,"lastSentViewports",new Map),oe(this,"lastCollectedTouches",[]),oe(this,"touchZonesCallback",null),oe(this,"audioLoadingState",{totalExpected:0,loadedSounds:new Set,errors:new Map}),oe(this,"ensureRendererManager"),this.network=e,this.core=t,this.rendererManagers=n,this.primaryDisplayId=o,this.performanceMonitor=i,this.ensureRendererManager=a,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}}getRendererManager(e){return this.rendererManagers.get(e)}getPrimaryRendererManager(){return this.rendererManagers.get(this.primaryDisplayId)??Array.from(this.rendererManagers.values())[0]}renderDisplays(){var t,n;let e=this.core.getRenderState(this.userId);if(!e||e.displays.length===0){this.options.debug&&this.log("Render skipped: no render state or displays");return}for(let i of e.displays){let s=this.getRendererManager(i.id)??((t=this.ensureRendererManager)==null?void 0:t.call(this,i.id));if(!s){console.warn(`[NetworkSync] No renderer manager for display ${i.id}, skipping render`);continue}let o=(n=s.getLayerFilter)==null?void 0:n.call(s),a=o?this.core.getRenderState(this.userId,o):e;if(!a){this.options.debug&&this.log(`Render state unavailable for display ${i.id} with filter`);continue}let l=a.displays.find(u=>u.id===i.id);if(!l){this.options.debug&&this.log(`Render state missing display ${i.id} after filtering`);continue}if(!s.isReady()){this.options.debug&&this.log(`Renderer for display ${i.id} not ready yet`);continue}s.renderDisplay(l)}}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){return new Promise((t,n)=>{this.network.send("join",{username:this.options.username,token:this.options.token}),this.network.on("join_response",i=>{if(i.success){this.userId=i.userId,this.log(`Joined game as ${this.userId}`);let s=this.core.createUser(this.userId,this.options.username);s.setBytesTickRate(20),this.audioManager&&s.setAudioProcessor(this.audioManager),e!=null&&e.initUser&&e.initUser(this.core,s,{username:this.options.username,token:this.options.token}),t(this.userId)}else n(new Error(i.error||"Failed to join game"))}),setTimeout(()=>n(new Error("Join timeout")),5e3)})}sendInput(e){var b,S,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(),U=((b=E.find(N=>N.getId&&N.getId()===this.primaryDisplayId)??E[0])==null?void 0:b.getSize())??{x:this.options.canvasWidth,y:this.options.canvasHeight},z=U.x,B=U.y,R=(I=(S=n==null?void 0:n.getRenderer())==null?void 0:S.getOffsets)==null?void 0:I.call(S),O={offsetX:(R==null?void 0:R.offsetX)??0,offsetY:(R==null?void 0:R.offsetY)??0},A=Er.collectMousePosition(e,i,z,B,O);t.setMousePosition(A.x,A.y,A.over),t.updateMacroMouse(A.x,A.y,A.isLeftDown);let V=Er.collectTouchPositions(e,i,z,B,10,O);V.forEach(N=>{t.setTouchPosition(N.id,N.x,N.y,N.over)}),this.lastCollectedTouches=V}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,U)=>E.bindingId-U.bindingId),h=new Map;for(let E of d){let U=s.evaluateAxis(E.bindingId,l);h.set(E.bindingId,U),t.setAxis(E.name,U)}let f=a.sort((E,U)=>E.bindingId-U.bindingId),p=new Map;for(let E of f){let U=s.evaluateButton(E.bindingId,u);p.set(E.bindingId,U),t.setButton(E.name,U)}let g=t.getMouseDisplayInfo(),C=t.getIsMouseOnADisplay(),y=this.collectChangedViewports(),m=this.lastCollectedTouches.map(E=>({id:E.id,x:E.x,y:E.y,over:E.over})),v=Nw(0n,h,p,(g==null?void 0:g.displayId)??0,(g==null?void 0:g.localX)??0,(g==null?void 0:g.localY)??0,C,c,[],y,m);this.network.send("input",v)}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.log("Disconnected from server"))}getUserId(){return this.userId}isConnected(){return this.connected}getTotalBytesReceived(){return this.totalBytesReceived}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=>{try{let t=this.convertToUint8Array(e,"update");if(!t)return;this.recordBytesReceived(t.length);let n=this.core.applyUpdatePacketBuffer(this.userId,t);n?(this.postProcessCallback&&n.postProcessOrders&&n.postProcessOrders.length>0&&this.postProcessCallback(n.postProcessOrders),this.renderDisplays()):this.log("Failed to apply update packet")}catch(t){this.log(`Error applying update packet: ${t}`)}}),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.log("Disconnected from server")})}handleUpdatePacket(e,t){try{let n=this.convertToUint8Array(e,t);if(!n)return;this.recordBytesReceived(n.length);let i=new DataView(n.buffer,n.byteOffset,n.byteLength),s=Number(i.getBigUint64(0,!1));if(t==="update-dynamic"&&s<this.lastReceivedTick)return;s>this.lastReceivedTick&&(this.lastReceivedTick=s);let o=this.core.applyUpdatePacketBuffer(this.userId,n);if(o){let a=performance.now(),l=Ur((y,m)=>{if(m<=0)return;let v=this.miscTraffic.get(y)??{total:0,windowSum:0,samples:[]};v.total+=m,v.windowSum+=m,v.samples.push({time:a,bytes:m}),this.miscTraffic.set(y,v)},"recordMisc"),u=Ur(y=>{try{return JSON.stringify(y).length}catch{return 0}},"safeLen"),c=o.__byteSizes,d=c==null?void 0:c.audioOrders;typeof d=="number"?l("update.audioOrders",d):o.audioOrders&&o.audioOrders.length&&l("update.audioOrders",u(o.audioOrders));let h=c==null?void 0:c.vibrationOrders;typeof h=="number"?l("update.vibrationOrders",h):o.vibrationOrders&&o.vibrationOrders.length&&l("update.vibrationOrders",u(o.vibrationOrders));let f=c==null?void 0:c.macroOrders;typeof f=="number"?l("update.macroOrders",f):o.macroOrders&&o.macroOrders.length&&l("update.macroOrders",u(o.macroOrders));let p=c==null?void 0:c.postProcessOrders;if(typeof p=="number"?l("update.postProcessOrders",p):o.postProcessOrders&&o.postProcessOrders.length&&l("update.postProcessOrders",u(o.postProcessOrders)),o.displays&&o.displays.length)for(let y of o.displays){let m=y.id;if(typeof m!="number")continue;let v=this.displayTraffic.get(m)??{total:0,windowSum:0,samples:[]},b=7;v.total+=b,v.windowSum+=b,v.samples.push({time:a,bytes:b}),this.displayTraffic.set(m,v)}for(let y of o.layers){let m=y.byteSize??0,v=this.layerTraffic.get(y.id)??{total:0,windowSum:0,samples:[]};v.total+=m,v.windowSum+=m,v.samples.push({time:a,bytes:m});let b=a-Xn;for(;v.samples.length&&v.samples[0].time<b;){let S=v.samples.shift();S&&(v.windowSum-=S.bytes)}this.layerTraffic.set(y.id,v)}{let y=a-Xn;this.miscTraffic.forEach((m,v)=>{for(;m.samples.length&&m.samples[0].time<y;){let b=m.samples.shift();b&&(m.windowSum-=b.bytes)}m.windowSum<0&&(m.windowSum=0),this.miscTraffic.set(v,m)})}{let y=a-Xn;this.displayTraffic.forEach((m,v)=>{for(;m.samples.length&&m.samples[0].time<y;){let b=m.samples.shift();b&&(m.windowSum-=b.bytes)}m.windowSum<0&&(m.windowSum=0),this.displayTraffic.set(v,m)})}this.postProcessCallback&&o.postProcessOrders&&o.postProcessOrders.length>0&&this.postProcessCallback(o.postProcessOrders),this.options.debug&&this.debugRenderState();let g=performance.now();this.renderDisplays();let C=performance.now()-g;this.performanceMonitor.recordFrameTiming(0,C),this.options.debug&&console.warn(`[CLIENT] render() completed for ${t} (${C.toFixed(2)}ms)`)}else this.options.debug&&this.log(`Failed to apply ${t} packet (tick ${s})`)}catch(n){this.log(`Error applying ${t} update packet: ${n}`),console.error(n)}}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();console.warn(`[CLIENT] User has ${i.length} layers`),i.forEach((s,o)=>{let a=s.getOrders(),l=s.getStatic();(a.length>0||l)&&console.warn(` Layer ${o}: ${a.length} orders, static=${l}, z=${s.getZOrder()}`)})}let t=((n=this.getPrimaryRendererManager())==null?void 0:n.isReady())??!1;console.warn(`[CLIENT] Renderer ready: ${t}`)}log(e){this.options.debug&&console.warn(`[NetworkSync] ${e}`)}recordBytesReceived(e){this.totalBytesReceived+=e;let t=this.core.getUser(this.userId);t&&t.recordBytesReceived(e)}getLayerTrafficStats(){let e={},t=performance.now()-Xn;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/(Xn/1e3)}}),e}getMiscTrafficStats(){let e={},t=performance.now()-Xn;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/(Xn/1e3)}}),e}getDisplayTrafficStats(){let e={},t=performance.now()-Xn;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/(Xn/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(){this.audioManager&&(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);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){this.network.sendBridge(e,t),this.log(`Bridge sent on channel '${e}'`)}onBridge(e,t){this.network.onBridge(e,t),this.log(`Bridge handler registered for channel '${e}'`)}offBridge(e,t){this.network.offBridge(e,t),this.log(`Bridge handler removed for channel '${e}'`)}removeAllBridgeHandlers(e){this.network.removeAllBridgeHandlers(e),this.log(e?`All bridge handlers removed for '${e}'`:"All bridge handlers removed")}};Ur(Lb,"NetworkSync");var VE=Lb,_b=class extends HE{constructor(e){var t,n,i,s,o,a,l,u,c,d;if(super({application:e.application,container:e.container,displayContainers:e.displayContainers,debug:e.debug,width:e.width,height:e.height,renderer:e.renderer,useImageDataRendering:e.useImageDataRendering,renderMode:e.renderMode}),oe(this,"input",null),oe(this,"networkSync",null),oe(this,"mode"),oe(this,"localOptions",null),oe(this,"autoplayOverlay",null),oe(this,"autoplay",!0),oe(this,"audioManager",null),oe(this,"mobileVibration",null),oe(this,"postProcessOverlay",null),oe(this,"postProcessOverlays",new Map),oe(this,"postProcessOrderCollector",new Yf),oe(this,"pendingPaletteSlotByDisplay",new Map),oe(this,"localBridgeHandlers",new Map),oe(this,"localBridgeWildcardHandlers",new Set),this.mode=e.mode,e.mode==="local"?(this.localOptions={mode:"local",application:e.application,container:e.container,debug:e.debug??!1,width:e.width??80,height:e.height??25,userId:e.userId??"local",username:e.username??"User",renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,mobileInputConfig:e.mobileInputConfig,touchZones:e.touchZones,captureInput:e.captureInput??!1,inputEnabled:e.inputEnabled??!0,autoplay:e.autoplay??!0,autoplayOptions:e.autoplayOptions,renderMode:e.renderMode??"continuous"},this.userId=e.userId??"local",this.autoplay=e.autoplay??!0):(this.localOptions={mode:"connected",application:e.application,container:e.container,serverUrl:e.serverUrl,username:e.username??"Player",debug:e.debug??!1,width:e.width??80,height:e.height??25,autoReconnect:e.autoReconnect??!0,token:e.token,renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,mobileInputConfig:e.mobileInputConfig,touchZones:e.touchZones,captureInput:e.captureInput??!1,inputEnabled:e.inputEnabled??!0,autoplay:e.autoplay??!0,autoplayOptions:e.autoplayOptions,renderMode:e.renderMode??"continuous"},this.autoplay=e.autoplay??!0),this.log(`Initializing ClientRuntime (${this.mode} mode)`),this.mode==="connected"&&(this.core=new _w({mode:"client",maxUsers:100}),this.core.onPaletteChanged(h=>{this.onCorePaletteChanged(h),this.retryPendingPaletteSelections()}),this.core.onBitmapFontChanged(h=>{this.onCoreBitmapFontChanged(h)}),this.core.onImageFontChanged(h=>{this.onCoreImageFontChanged(h)})),e.inputEnabled??!0?this.input=new cb({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)??e.width??0,gridHeight:((u=e.touchZones)==null?void 0:u.gridHeight)??e.height??0,rendererOffsets:(c=e.touchZones)==null?void 0:c.rendererOffsets,zones:(d=e.touchZones)==null?void 0:d.zones}}):this.log("Input disabled (inputEnabled: false)"),this.mode==="connected"){let h=this.localOptions,f=new FE({url:h.serverUrl,autoReconnect:h.autoReconnect,auth:{username:h.username,token:h.token},debug:e.debug});this.networkSync=new VE(f,this.core,this.rendererManagers,this.performanceMonitor,{serverUrl:h.serverUrl,username:h.username,token:h.token,debug:e.debug,autoReconnect:h.autoReconnect,canvasWidth:e.width??80,canvasHeight:e.height??25},this.primaryDisplayId,p=>this.ensureRendererManager(p))}this.log("ClientRuntime initialized")}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 qw(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==="connected"){this.log("setTickRate() has no effect in connected mode");return}super.setTickRate(e)}async onBeforeStart(){this.audioManager=new Pb({debug:this.options.debug}),this.mobileVibration=new Zf({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 Ek(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),e()}})}),this.log("Autoplay overlay dismissed, continuing startup..."))}async onAfterInit(){var t;this.rebuildPostProcessOverlays(),this.log("PostProcessOverlays created");let e=this.rendererManager.getCanvas();if(e&&this.input&&this.input.setMobileTarget(e),this.mode==="connected"&&this.networkSync){if(this.log("Connecting to server"),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(`[onAfterInit] Touch zones callback called with ${o.length} zones`);let a=s.getCanvas();if(this.log(`[onAfterInit] 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(`[onAfterInit] Grid from zones: ${l}x${u}`);let c=i.enableTouchZonesDevice(a,l,u,o);this.log(`[onAfterInit] enableTouchZonesDevice returned: ${c}`),c&&this.log(`Touch zones configured from server: ${o.length} zones`)}})}if(await this.networkSync.connect(),this.userId=await this.networkSync.joinGame(this.options.application),this.input){let i=((t=this.core.getUser(this.userId))==null?void 0:t.getDisplays())??[];if(i.length>0){let s=i[0].getSize();this.input.updateTouchZoneLayout(s.x,s.y)}}let n=this.core.getUser(this.userId);n&&this.configureUserProcessors(n)}}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.core,this));let e=this.rendererManager.getCanvas();if(e&&this.input&&this.input.setMobileTarget(e),this.mode==="connected"&&this.networkSync){if(this.log("Connecting to server"),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.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==="connected"&&this.networkSync&&this.networkSync.disconnect()}getStats(){var n;let e=super.getStats(),t=(n=this.core.getUser(this.userId))==null?void 0:n.getTotalBytesReceived();return{...e,mode:this.mode,latency:void 0,totalBytesReceived:t}}getAudioLoadingState(){if(this.mode==="connected"&&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:[]}}async onDestroy(){this.autoplayOverlay&&(this.autoplayOverlay.destroy(),this.autoplayOverlay=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null),this.postProcessOverlay&&(this.postProcessOverlay.destroy(),this.postProcessOverlay=null);for(let e of this.postProcessOverlays.values())e.destroy();this.postProcessOverlays.clear(),this.input&&this.input.destroy(),this.networkSync&&this.networkSync.destroy()}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.userId)??"local",this.log(`Creating local user: ${this.userId}`);let t=this.core.createUser(this.userId,(e==null?void 0:e.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.core,t,{username:(e==null?void 0:e.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:this.options.width??80,y:this.options.height??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==="local"){if(this.tickRate===0){let f=performance.now();this.render();let p=performance.now()-f;this.performanceMonitor.recordFrameTiming(0,p),this.rafId=requestAnimationFrame(g=>this.mainLoop(g));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.core,c),(u=(l=this.options.application).updateUser)==null||u.call(l,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 g=s.flushPostProcessCommands(),C=this.postProcessOrderCollector.convertCommands(g);this.applyPostProcessOrders(C)}if(s.hasPendingMacroOrders()){let g=s.flushMacroOrders();s.applyMacroOrders(g)}let p=s.updateMacros();if(s.processMacroEvents(p),s.hasBridgeMessages()){let g=s.getBridgeMessages();this.dispatchLocalBridgeMessages(g)}this.core.endTick().forEach(({static:g,dynamic:C})=>{let y=((g==null?void 0:g.length)??0)+((C==null?void 0:C.length)??0);s.recordBytesReceived(y)}),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.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(S=>S.getId&&S.getId()===this.primaryDisplayId)??f[0])==null?void 0:a.getSize())??{x:this.options.width,y:this.options.height},g=p.x,C=p.y,y=(u=(l=this.rendererManager.getRenderer())==null?void 0:l.getOffsets)==null?void 0:u.call(l),m={offsetX:(y==null?void 0:y.offsetX)??0,offsetY:(y==null?void 0:y.offsetY)??0};this.input.updateTouchZoneLayout(g,C,m);let v=Er.collectMousePosition(this.input,t,g,C,m);e.setMousePosition(v.x,v.y,v.over),e.updateMacroMouse(v.x,v.y,v.isLeftDown),Er.collectTouchPositions(this.input,t,g,C,10,m).forEach(S=>{e.setTouchPosition(S.id,S.x,S.y,S.over)});let b=(c=this.rendererManagers.get(this.primaryDisplayId))==null?void 0:c.getAvailableSize();b&&e.setDisplayViewport(this.primaryDisplayId,b.width,b.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(g=>{let C=i.evaluateAxis(g.bindingId,f);e.setAxis(g.name,C)}),o.forEach(g=>{let C=new Map,y=new Map,m=new Map;for(let[I,E]of p)C.set(I,E.pressed),y.set(I,E.justPressed),m.set(I,E.justReleased);let v=i.evaluateButton(g.bindingId,C),b=i.evaluateButton(g.bindingId,y),S=i.evaluateButton(g.bindingId,m);e.setButton(g.name,v),e.setButton(`${g.name}_justPressed`,b),e.setButton(`${g.name}_justReleased`,S)})}(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,g=p.getGridSize();l=g.cols,u=g.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===$t.Responsive){let p=s.getAvailableSize(),g=256*256;"getMaxCells"in o&&(g=Math.min(g,o.getMaxCells()));let C=Math.floor(p.width/c),y=Math.floor(p.height/d);if(C=Math.min(256,Math.max(1,C)),y=Math.min(256,Math.max(1,y)),C*y>g){let m=Math.sqrt(g/(C*y));C=Math.max(1,Math.floor(C*m)),y=Math.max(1,Math.floor(y*m)),this.log(`⚠️ [Display ${i}] Device limit: max ${g} cells, clamping to ${C}×${y}`)}(a.x!==C||a.y!==y)&&(this.log(`📐 [Display ${i}] Resizing display from ${a.x}×${a.y} to ${C}×${y} (available: ${p.width}×${p.height}px, cell: ${c}×${d}px)`),n.setSize(new Ht(C,y)))}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 Or.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 Or.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 Or.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 Or.SetScalingMode:{this.applyScalingMode(i,n.mode);break}case Or.SetGrid:{this.applyGridConfig(i,n);break}case Or.SwitchPalette:{this.applySwitchPalette(i,n);break}case Or.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=Wf(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==="connected"&&this.networkSync)this.networkSync.sendBridge(e,t);else if(this.mode==="local"){let i=this.core.getUser(this.userId);i&&((n=this.options.application)!=null&&n.onBridgeMessage)&&(this.options.application.onBridgeMessage(this.core,i,e,t),this.log(`Bridge message sent to application on channel '${e}'`))}}onBridge(e,t){this.mode==="connected"&&this.networkSync?this.networkSync.onBridge(e,t):this.mode==="local"&&(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==="connected"&&this.networkSync?this.networkSync.offBridge(e,t):this.mode==="local"&&(e==="*"?this.localBridgeWildcardHandlers.delete(t):(n=this.localBridgeHandlers.get(e))==null||n.delete(t))}removeAllBridgeHandlers(e){this.mode==="connected"&&this.networkSync?this.networkSync.removeAllBridgeHandlers(e):this.mode==="local"&&(e===void 0?(this.localBridgeHandlers.clear(),this.localBridgeWildcardHandlers.clear()):e==="*"?this.localBridgeWildcardHandlers.clear():this.localBridgeHandlers.delete(e))}log(e){this.options.debug&&console.warn(`[ClientRuntime/${this.mode}] ${e}`)}};Ur(_b,"ClientRuntime");var jE=_b,YE=class{constructor(e={}){var t,n,i;oe(this,"input"),oe(this,"mobileVibration"),this.input=new cb({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 Zf({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 g=a.evaluateAxis(p.bindingId,h);e.setAxis(p.name,g)}),u.forEach(p=>{let g=new Map,C=new Map,y=new Map;for(let[S,I]of f)g.set(S,I.pressed),C.set(S,I.justPressed),y.set(S,I.justReleased);let m=a.evaluateButton(p.bindingId,g),v=a.evaluateButton(p.bindingId,C),b=a.evaluateButton(p.bindingId,y);e.setButton(p.name,m),e.setButton(`${p.name}_justPressed`,v),e.setButton(`${p.name}_justReleased`,b)})}(d=(c=this.input).poll)==null||d.call(c)}processVibrationCommands(e){e.hasMobileVibrationCommands()&&e.applyMobileVibrationCommands(e.flushMobileVibrationCommands()),e.hasGamepadVibrationCommands()&&e.applyGamepadVibrationCommands(e.flushGamepadVibrationCommands())}};Ur(YE,"InputFeature");var GE=class{constructor(e={}){oe(this,"audioManager"),oe(this,"debug"),this.debug=e.debug??!1,this.audioManager=new Pb({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}`)}};Ur(GE,"AudioFeature");var XE=class{constructor(e,t={}){oe(this,"overlay"),oe(this,"orderCollector"),oe(this,"debug"),this.debug=t.debug??!1,this.overlay=new qw(e),this.orderCollector=new Yf}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 Or.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 Or.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 Or.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 Or.SetScalingMode:{this.applyScalingMode(t,i,n.mode);break}case Or.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=Wf(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}`)}};Ur(XE,"PostProcessFeature");const ZE={},Im=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},KE=r=>r?Im(r):Im;var $b={exports:{}},Nb={},Wb={exports:{}},Hb={};/**
|
|
256
256
|
* @license React
|
|
257
257
|
* use-sync-external-store-shim.production.js
|
|
258
258
|
*
|
|
@@ -260,7 +260,7 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
260
260
|
*
|
|
261
261
|
* This source code is licensed under the MIT license found in the
|
|
262
262
|
* LICENSE file in the root directory of this source tree.
|
|
263
|
-
*/var
|
|
263
|
+
*/var uo=$;function qE(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var QE=typeof Object.is=="function"?Object.is:qE,JE=uo.useState,eM=uo.useEffect,tM=uo.useLayoutEffect,rM=uo.useDebugValue;function nM(r,e){var t=e(),n=JE({inst:{value:t,getSnapshot:e}}),i=n[0].inst,s=n[1];return tM(function(){i.value=t,i.getSnapshot=e,td(i)&&s({inst:i})},[r,t,e]),eM(function(){return td(i)&&s({inst:i}),r(function(){td(i)&&s({inst:i})})},[r]),rM(t),t}function td(r){var e=r.getSnapshot;r=r.value;try{var t=e();return!QE(r,t)}catch{return!0}}function iM(r,e){return e()}var sM=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?iM:nM;Hb.useSyncExternalStore=uo.useSyncExternalStore!==void 0?uo.useSyncExternalStore:sM;Wb.exports=Hb;var oM=Wb.exports;/**
|
|
264
264
|
* @license React
|
|
265
265
|
* use-sync-external-store-shim/with-selector.production.js
|
|
266
266
|
*
|
|
@@ -268,6 +268,6 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
268
268
|
*
|
|
269
269
|
* This source code is licensed under the MIT license found in the
|
|
270
270
|
* LICENSE file in the root directory of this source tree.
|
|
271
|
-
*/var Ou=$,JE=QE;function eM(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var tM=typeof Object.is=="function"?Object.is:eM,rM=JE.useSyncExternalStore,nM=Ou.useRef,iM=Ou.useEffect,sM=Ou.useMemo,oM=Ou.useDebugValue;Db.useSyncExternalStoreWithSelector=function(r,e,t,n,i){var s=nM(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=sM(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,tM(c,f))return p;var g=n(f);return i!==void 0&&i(p,g)?(c=f,p):(c=f,d=g)}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=rM(r,s[0],s[1]);return iM(function(){o.hasValue=!0,o.value=a},[a]),oM(a),a};zb.exports=Db;var aM=zb.exports;const lM=gy(aM),Fb={},{useDebugValue:uM}=Ey,{useSyncExternalStoreWithSelector:cM}=lM;let vm=!1;const dM=r=>r;function hM(r,e=dM,t){(Fb?"production":void 0)!=="production"&&t&&!vm&&(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"),vm=!0);const n=cM(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return uM(n),n}const wm=r=>{(Fb?"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"?WE(r):r,t=(n,i)=>hM(e,n,i);return Object.assign(t,e),t},fM=r=>r?wm(r):wm,Gs=fM(r=>({connected:!1,lastSnapshot:void 0,setConnected:e=>r({connected:e}),setSnapshot:e=>r({lastSnapshot:e})}));class pM{constructor(){Xi(this,"runtime",null);Xi(this,"layerTraffic",{});Xi(this,"miscTraffic",{});Xi(this,"displayTraffic",{});Xi(this,"visibleLayerIds",null);Xi(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){Gs.getState().setConnected(!1),this.runtime&&this.destroy();const t={mode:"connected",serverUrl:e.serverUrl,container:e.container,displayContainers:e.displayContainers,width:e.width??80,height:e.height??25,renderer:e.renderer??Qf.TerminalGL,inputEnabled:e.inputEnabled??!0,captureInput:e.captureInput??!0,debug:!1,autoplay:!1};try{if(this.runtime=new FE(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}Gs.getState().setConnected(!0),Gs.getState().setSnapshot(l)}catch{}}),await this.runtime.start(),this.runtime.sendBridge("__debug_auth",{})}catch(n){throw Gs.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 gM({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 Xr(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 mM(r){return`${r.toFixed(2)} s`}const yM={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 $o({label:r,tone:e="muted"}){const t=yM[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 bm({children:r}){return k.jsx("div",{style:{border:"1px solid #2a2a2a",borderRadius:6,background:"#161616"},children:r})}function Zn({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 vM({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($o,{label:"Active",tone:"info"})]}),k.jsxs(bm,{children:[k.jsx(Zn,{label:"Origin",value:`(${r.item.origin.x}, ${r.item.origin.y})`,divider:!0}),k.jsx(Zn,{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($o,{label:`#${r.item.id}`,tone:"info"})]}),k.jsx($o,{label:`z ${r.item.z}`,tone:"muted"})]}),k.jsxs(bm,{children:[k.jsx(Zn,{label:"Mode",value:r.item.charCodeMode,divider:!0}),k.jsx(Zn,{label:"Orders",value:r.item.ordersCount,divider:!0}),k.jsx(Zn,{label:"Size",value:`${r.item.width} × ${r.item.height}`,divider:!0}),k.jsx(Zn,{label:"Origin",value:`(${r.item.origin.x}, ${r.item.origin.y})`,divider:!0}),k.jsx(Zn,{label:"Static",value:r.item.isStatic?k.jsx($o,{label:"Static",tone:"success"}):k.jsx($o,{label:"Dynamic",tone:"muted"}),divider:!0}),r.item.bytesTotal!==void 0&&k.jsxs(k.Fragment,{children:[k.jsx(Zn,{label:"Total",value:Xr(r.item.bytesTotal),divider:!0}),k.jsx(Zn,{label:"Throughput",value:`${Xr(r.item.bytesPerSec1s)} /s`})]})]})]})]})]})}function Cm({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 wM(r){return r<1e3?`${r} B`:r<1e6?`${(r/1e3).toFixed(2)} KB`:`${(r/1e6).toFixed(2)} MB`}const As={id:"1fr",net:"90px",gap:4};function bM({displays:r,layers:e,selectedDisplayId:t,selectedLayerIds:n,onSelectDisplay:i,onSelectLayer:s}){const o=new Set(n),[a,l]=$.useState("id"),[u,c]=$.useState("asc"),d=$.useMemo(()=>{const f=[...e];return f.sort((p,g)=>{const x=a==="id"?p.id:p.bytesTotal??0,y=a==="id"?g.id:g.bytesTotal??0,m=x===y?0:x<y?-1:1;return u==="asc"?m:-m}),f},[e,u,a]),h=f=>{l(p=>p===f?(c(g=>g==="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(Cm,{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:`${As.id} ${As.net}`,alignItems:"center",columnGap:As.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),g=f.name?`${f.id}:${f.name}`:String(f.id);return k.jsx(Cm,{isSelected:p,onClick:x=>s(f.id,x),children:k.jsxs("span",{style:{display:"grid",gridTemplateColumns:`${As.id} ${As.net}`,alignItems:"center",columnGap:As.gap,width:"100%"},children:[k.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:k.jsx("span",{style:{color:"inherit"},children:g})}),k.jsx("span",{style:{color:"#858585",fontSize:11,textAlign:"right",whiteSpace:"nowrap"},children:f.bytesTotal!==void 0&&wM(f.bytesTotal)})]})},`layer-${f.id}-${p}`)})]})]})}function CM({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(bM,{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 xM({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 Jc({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 SM({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(Jc,{title:"Audio",emptyLabel:"No audio loaded",headers:["Name","Source","Duration","Size","URL"],rows:r.audio.map(e=>[e.name,e.source,mM(e.duration),Xr(e.originalSize),e.originalUrl??"—"])}),k.jsx(Jc,{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(Jc,{title:"Palettes",emptyLabel:"No palette",headers:["Slot","Colors"],rows:r.palettes.map(e=>[String(e.slotId),String(e.colors)])})]})}const IM=!0,jt="u-",kM="uplot",EM=jt+"hz",MM=jt+"vt",TM=jt+"title",UM=jt+"wrap",AM=jt+"under",RM=jt+"over",PM=jt+"axis",ts=jt+"off",zM=jt+"select",DM=jt+"cursor-x",OM=jt+"cursor-y",BM=jt+"cursor-pt",FM=jt+"legend",LM=jt+"live",_M=jt+"inline",$M=jt+"series",NM=jt+"marker",xm=jt+"label",WM=jt+"value",qo="width",Qo="height",No="top",Sm="bottom",Rs="left",ed="right",Jf="#000",Im=Jf+"0",td="mousemove",km="mousedown",rd="mouseup",Em="mouseenter",Mm="mouseleave",Tm="dblclick",HM="resize",VM="scroll",Um="change",fu="dppxchange",ep="--",wo=typeof window<"u",Ah=wo?document:null,eo=wo?window:null,jM=wo?navigator:null;let Ve,pl;function Rh(){let r=devicePixelRatio;Ve!=r&&(Ve=r,pl&&zh(Um,pl,Rh),pl=matchMedia(`(min-resolution: ${Ve-.001}dppx) and (max-resolution: ${Ve+.001}dppx)`),as(Um,pl,Rh),eo.dispatchEvent(new CustomEvent(fu)))}function Yr(r,e){if(e!=null){let t=r.classList;!t.contains(e)&&t.add(e)}}function Ph(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=Ah.createElement(r);return e!=null&&Yr(i,e),t!=null&&t.insertBefore(i,n),i}function an(r,e){return Cn("div",r,e)}const Am=new WeakMap;function $n(r,e,t,n,i){let s="translate("+e+"px,"+t+"px)",o=Am.get(r);s!=o&&(r.style.transform=s,Am.set(r,s),e<0||t<0||e>n||t>i?Yr(r,ts):Ph(r,ts))}const Rm=new WeakMap;function Pm(r,e,t){let n=e+t,i=Rm.get(r);n!=i&&(Rm.set(r,n),r.style.background=e,r.style.borderColor=t)}const zm=new WeakMap;function Dm(r,e,t,n){let i=e+""+t,s=zm.get(r);i!=s&&(zm.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 tp={passive:!0},YM={...tp,capture:!0};function as(r,e,t,n){e.addEventListener(r,t,n?YM:tp)}function zh(r,e,t,n){e.removeEventListener(r,t,tp)}wo&&Rh();function kn(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 Lb(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 _b=r=>r!=null,$b=r=>r!=null&&r>0,Bu=Lb(_b),GM=Lb($b);function XM(r,e,t,n=0,i=!1){let s=i?GM:Bu,o=i?$b:_b;[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 Fu(r,e,t,n){let i=Fm(r),s=Fm(e);r==e&&(i==-1?(r*=t,e/=t):(r/=t,e*=t));let o=t==10?ti:Nb,a=i==1?qr:ln,l=s==1?ln:qr,u=a(o(Wt(r))),c=l(o(Wt(e))),d=uo(t,u),h=uo(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=jb(r,d),e=Lu(e,h)),[r,e]}function rp(r,e,t,n){let i=Fu(r,e,t,n);return r==0&&(i[0]=0),e==0&&(i[1]=0),i}const np=.1,Om={mode:3,pad:np},ha={pad:0,soft:null,mode:0},ZM={min:ha,max:ha};function pu(r,e,t,n){return _u(t)?Bm(r,e,t):(ha.pad=t,ha.soft=n?0:null,ha.mode=n?3:0,Bm(r,e,ZM))}function _e(r,e){return r??e}function KM(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 Bm(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=ti(f),g=Mr(Wt(r),Wt(e)),x=ti(g),y=Wt(x-p);(f<1e-24||y>10)&&(f=0,(r==0||e==0)&&(f=1e-24,d==2&&u!=Qe&&(s=0),h==2&&c!=-Qe&&(o=0)));let m=f||g||1e3,v=ti(m),b=uo(10,qr(v)),I=m*(f==0?r==0?.1:1:s),S=Je(jb(r-I,b/10),24),M=r>=u&&(d==1||d==3&&S<=u||d==2&&S>=u)?u:Qe,U=Mr(a,S<M&&r>=M?M:Mn(M,S)),z=m*(f==0?e==0?.1:1:o),O=Je(Lu(e+z,b/10),24),R=e<=c&&(h==1||h==3&&O>=c||h==2&&O<=c)?c:-Qe,B=Mn(l,O>R&&e<=R?R:Mr(R,O));return U==B&&U==0&&(B=100),[U,B]}const qM=new Intl.NumberFormat(wo?jM.language:"en-US"),ip=r=>qM.format(r),rn=Math,Ll=rn.PI,Wt=rn.abs,qr=rn.floor,Lt=rn.round,ln=rn.ceil,Mn=rn.min,Mr=rn.max,uo=rn.pow,Fm=rn.sign,ti=rn.log10,Nb=rn.log2,QM=(r,e=1)=>rn.sinh(r)*e,nd=(r,e=1)=>rn.asinh(r/e),Qe=1/0;function Lm(r){return(ti((r^r>>31)-(r>>31))|0)+1}function Dh(r,e,t){return Mn(Mr(r,e),t)}function Wb(r){return typeof r=="function"}function Pe(r){return Wb(r)?r:()=>r}const JM=()=>{},Hb=r=>r,Vb=(r,e)=>e,eT=r=>null,_m=r=>!0,$m=(r,e)=>r==e,tT=/\.\d*?(?=9{6,}|0{6,})/gm,fs=r=>{if(Gb(r)||Bi.has(r))return r;const e=`${r}`,t=e.match(tT);if(t==null)return r;let n=t[0].length-1;if(e.indexOf("e-")!=-1){let[i,s]=e.split("e");return+`${fs(i)}e${s}`}return Je(r,n)};function Ji(r,e){return fs(Je(fs(r/e))*e)}function Lu(r,e){return fs(ln(fs(r/e))*e)}function jb(r,e){return fs(qr(fs(r/e))*e)}function Je(r,e=0){if(Gb(r))return r;let t=10**e,n=r*t*(1+Number.EPSILON);return Lt(n)/t}const Bi=new Map;function Yb(r){return((""+r).split(".")[1]||"").length}function Ra(r,e,t,n){let i=[],s=n.map(Yb);for(let o=e;o<t;o++){let a=Wt(o),l=Je(uo(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),Bi.set(h,d)}}return i}const fa={},sp=[],co=[null,null],vi=Array.isArray,Gb=Number.isInteger,rT=r=>r===void 0;function Nm(r){return typeof r=="string"}function _u(r){let e=!1;if(r!=null){let t=r.constructor;e=t==null||t==Object}return e}function nT(r){return r!=null&&typeof r=="object"}const iT=Object.getPrototypeOf(Uint8Array),Xb="__proto__";function ho(r,e=_u){let t;if(vi(r)){let n=r.find(i=>i!=null);if(vi(n)||e(n)){t=Array(r.length);for(let i=0;i<r.length;i++)t[i]=ho(r[i],e)}else t=r.slice()}else if(r instanceof iT)t=r.slice();else if(e(r)){t={};for(let n in r)n!=Xb&&(t[n]=ho(r[n],e))}else t=r;return t}function Pt(r){let e=arguments;for(let t=1;t<e.length;t++){let n=e[t];for(let i in n)i!=Xb&&(_u(r[i])?Pt(r[i],ho(n[i])):r[i]=ho(n[i]))}return r}const sT=0,oT=1,aT=2;function lT(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 uT(r,e){if(hT(r)){let o=r[0].slice();for(let a=1;a<r.length;a++)o.push(...r[a].slice(1));return fT(o[0])||(o=dT(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]:oT,f=[];for(let p=0;p<c.length;p++){let g=c[p],x=s.get(l[p]);g===null?h!=sT&&(d[x]=g,h==aT&&f.push(x)):d[x]=g}lT(d,f,i),n.push(d)}}return n}const cT=typeof queueMicrotask>"u"?r=>Promise.resolve().then(r):queueMicrotask;function dT(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 hT(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 fT(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 Zb=["January","February","March","April","May","June","July","August","September","October","November","December"],Kb=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function qb(r){return r.slice(0,3)}const pT=Kb.map(qb),gT=Zb.map(qb),mT={MMMM:Zb,MMM:gT,WWWW:Kb,WWW:pT};function Wo(r){return(r<10?"0":"")+r}function yT(r){return(r<10?"00":r<100?"0":"")+r}const vT={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=>Wo(r.getMonth()+1),M:r=>r.getMonth()+1,DD:r=>Wo(r.getDate()),D:r=>r.getDate(),WWWW:(r,e)=>e.WWWW[r.getDay()],WWW:(r,e)=>e.WWW[r.getDay()],HH:r=>Wo(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=>Wo(r.getMinutes()),m:r=>r.getMinutes(),ss:r=>Wo(r.getSeconds()),s:r=>r.getSeconds(),fff:r=>yT(r.getMilliseconds())};function op(r,e){e=e||mT;let t=[],n=/\{([a-z]+)\}|[^{]+/gi,i;for(;i=n.exec(r);)t.push(i[0][0]=="{"?vT[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 wT=new Intl.DateTimeFormat().resolvedOptions().timeZone;function bT(r,e){let t;return e=="UTC"||e=="Etc/UTC"?t=new Date(+r+r.getTimezoneOffset()*6e4):e==wT?t=r:(t=new Date(r.toLocaleString("en-US",{timeZone:e})),t.setMilliseconds(r.getMilliseconds())),t}const Qb=r=>r%1==0,gu=[1,2,2.5,5],CT=Ra(10,-32,0,gu),Jb=Ra(10,0,32,gu),xT=Jb.filter(Qb),es=CT.concat(Jb),ap=`
|
|
272
|
-
`,eC="{YYYY}",Wm=ap+eC,tC="{M}/{D}",Jo=ap+tC,gl=Jo+"/{YY}",rC="{aa}",ST="{h}:{mm}",zs=ST+rC,Hm=ap+zs,Vm=":{ss}",je=null;function nC(r){let e=r*1e3,t=e*60,n=t*60,i=n*24,s=i*30,o=i*365,l=(r==1?Ra(10,0,3,gu).filter(Qb):Ra(10,-3,0,gu)).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,eC,je,je,je,je,je,je,1],[i*28,"{MMM}",Wm,je,je,je,je,je,1],[i,tC,Wm,je,je,je,je,je,1],[n,"{h}"+rC,gl,je,Jo,je,je,je,1],[t,zs,gl,je,Jo,je,je,je,1],[e,Vm,gl+" "+zs,je,Jo+" "+zs,je,Hm,je,1],[r,Vm+".{fff}",gl+" "+zs,je,Jo+" "+zs,je,Hm,je,1]];function c(d){return(h,f,p,g,x,y)=>{let m=[],v=x>=o,b=x>=s&&x<o,I=d(p),S=Je(I*r,3),M=id(I.getFullYear(),v?0:I.getMonth(),b||v?1:I.getDate()),U=Je(M*r,3);if(b||v){let z=b?x/s:0,O=v?x/o:0,R=S==U?S:Je(id(M.getFullYear()+O,M.getMonth()+z,1)*r,3),B=new Date(Lt(R/r)),A=B.getFullYear(),V=B.getMonth();for(let N=0;R<=g;N++){let H=id(A+O*N,V+z*N,1),P=H-d(Je(H*r,3));R=Je((+H+P)*r,3),R<=g&&m.push(R)}}else{let z=x>=i?i:x,O=qr(p)-qr(S),R=U+O+Lu(S-U,z);m.push(R);let B=d(R),A=B.getHours()+B.getMinutes()/t+B.getSeconds()/n,V=x/n,N=h.axes[f]._space,H=y/N;for(;R=Je(R+x,r==1?0:3),!(R>g);)if(V>1){let P=qr(Je(A+V,6))%24,X=d(R).getHours()-P;X>1&&(X=-1),R-=X*n,A=(A+V)%24;let te=m[m.length-1];Je((R-te)/x,3)*H>=.7&&m.push(R)}else m.push(R)}return m}}return[l,u,c]}const[IT,kT,ET]=nC(1),[MT,TT,UT]=nC(.001);Ra(2,-53,53,[1]);function jm(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 Ym(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 g=r(p),x=g.getFullYear(),y=g.getMonth(),m=g.getDate(),v=g.getHours(),b=g.getMinutes(),I=g.getSeconds(),S=x!=l&&a[2]||y!=u&&a[3]||m!=c&&a[4]||v!=d&&a[5]||b!=h&&a[6]||I!=f&&a[7]||a[1];return l=x,u=y,c=m,d=v,h=b,f=I,S(g)})}}function AT(r,e){let t=op(e);return(n,i,s,o,a)=>i.map(l=>t(r(l)))}function id(r,e,t){return new Date(r,e,t)}function Gm(r,e){return e(r)}const RT="{YYYY}-{MM}-{DD} {h}:{mm}{aa}";function Xm(r,e){return(t,n,i,s)=>s==null?ep:e(r(n))}function PT(r,e){let t=r.series[e];return t.width?t.stroke(r,e):t.points.width?t.points.stroke(r,e):null}function zT(r,e){return r.series[e].fill(r,e)}const DT={show:!0,live:!0,isolate:!1,mount:JM,markers:{show:!0,width:2,stroke:PT,fill:zT,dash:"solid"},idx:null,idxs:null,values:[]};function OT(r,e){let t=r.cursor.points,n=an(),i=t.size(r,e);lt(n,qo,i),lt(n,Qo,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 BT(r,e){let t=r.series[e].points;return t._fill||t._stroke}function FT(r,e){let t=r.series[e].points;return t._stroke||t._fill}function LT(r,e){return r.series[e].points.size}const sd=[0,0];function _T(r,e,t){return sd[0]=e,sd[1]=t,sd}function ml(r,e,t,n=!0){return i=>{i.button==0&&(!n||i.target==e)&&t(i)}}function od(r,e,t,n=!0){return i=>{(!n||i.target==e)&&t(i)}}const $T={show:!0,x:!0,y:!0,lock:!1,move:_T,points:{one:!1,show:OT,size:LT,width:0,stroke:FT,fill:BT},bind:{mousedown:ml,mouseup:ml,click:ml,dblclick:ml,mousemove:od,mouseleave:od,mouseenter:od},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},iC={show:!0,stroke:"rgba(0,0,0,0.07)",width:2},lp=Pt({},iC,{filter:Vb}),sC=Pt({},lp,{size:10}),oC=Pt({},iC,{show:!1}),up='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"',aC="bold "+up,lC=1.5,Zm={show:!0,scale:"x",stroke:Jf,space:50,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:aC,side:2,grid:lp,ticks:sC,border:oC,font:up,lineGap:lC,rotate:0},NT="Value",WT="Time",Km={show:!0,scale:"x",auto:!1,sorted:1,min:Qe,max:-Qe,idxs:[]};function HT(r,e,t,n,i){return e.map(s=>s==null?"":ip(s))}function VT(r,e,t,n,i,s,o){let a=[],l=Bi.get(i)||0;t=o?t:Je(Lu(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 Oh(r,e,t,n,i,s,o){const a=[],l=r.scales[r.axes[e].scale].log,u=l==10?ti:Nb,c=qr(u(t));i=uo(l,c),l==10&&(i=es[kn(i,es)]);let d=t,h=i*l;l==10&&(h=es[kn(h,es)]);do a.push(d),d=d+i,l==10&&!Bi.has(d)&&(d=Je(d,Bi.get(i))),d>=h&&(i=d,h=i*l,l==10&&(h=es[kn(h,es)]));while(d<=n);return a}function jT(r,e,t,n,i,s,o){let l=r.scales[r.axes[e].scale].asinh,u=n>l?Oh(r,e,Mr(l,t),n,i):[l],c=n>=0&&t<=0?[0]:[];return(t<-l?Oh(r,e,Mr(l,-n),-t,i):[l]).reverse().map(h=>-h).concat(c,u)}const uC=/./,YT=/[12357]/,GT=/[125]/,qm=/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 XT(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?uC:l(7,o)-c>=u?YT:l(5,o)-c>=u?GT:qm;if(d==qm){let h=Wt(l(1,o)-c);if(h<u)return Bh(e.slice().reverse(),a.distr,d,ln(u/h)).reverse()}return Bh(e,a.distr,d,1)}function ZT(r,e,t,n,i){let s=r.axes[t],o=s.scale,a=s._space,l=r.valToPos,u=Wt(l(1,o)-l(2,o));return u<a?Bh(e.slice().reverse(),3,uC,ln(a/u)).reverse():e}function KT(r,e,t,n){return n==null?ep:e==null?"":ip(e)}const Qm={show:!0,scale:"y",stroke:Jf,space:30,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:aC,side:3,grid:lp,ticks:sC,border:oC,font:up,lineGap:lC,rotate:0};function qT(r,e){let t=3+(r||1)*2;return Je(t*e,3)}function QT(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=Wt(o-s),l=r.series[e],u=a/(l.points.space*Ve);return n[1]-n[0]<=u}const Jm={scale:null,auto:!0,sorted:0,min:Qe,max:-Qe},cC=(r,e,t,n,i)=>i,ey={show:!0,auto:!0,sorted:0,gaps:cC,alpha:1,facets:[Pt({},Jm,{scale:"x"}),Pt({},Jm,{scale:"y"})]},ty={scale:"y",auto:!0,sorted:0,show:!0,spanGaps:!1,gaps:cC,alpha:1,points:{show:QT,filter:null},values:null,min:Qe,max:-Qe,idxs:[],path:null,clip:null};function JT(r,e,t,n,i){return t/10}const dC={time:IM,auto:!0,distr:1,log:10,asinh:1,min:null,max:null,dir:1,ori:0},e5=Pt({},dC,{time:!1,ori:1}),ry={};function hC(r,e){let t=ry[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&&(ry[r]=t)),t}const fo=1,Fh=2;function ms(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,g=a.height,x=r.valToPosH,y=r.valToPosV;return c.ori==0?t(i,l,u,c,d,x,y,h,f,p,g,Nu,bo,Hu,pC,mC):t(i,l,u,c,d,y,x,f,h,g,p,Wu,Co,hp,gC,yC)}function cp(r,e){let t=0,n=0,i=_e(r.bands,sp);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 t5(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 ri(r,e,t,n,i,s){return ms(r,e,(o,a,l,u,c,d,h,f,p,g,x)=>{let y=o.pxRound;const m=u.dir*(u.ori==0?1:-1),v=u.ori==0?bo:Co;let b,I;m==1?(b=t,I=n):(b=n,I=t);let S=y(d(a[b],u,g,f)),M=y(h(l[b],c,x,p)),U=y(d(a[I],u,g,f)),z=y(h(s==1?c.max:c.min,c,x,p)),O=new Path2D(i);return v(O,U,z),v(O,S,z),v(O,S,M),O})}function $u(r,e,t,n,i,s){let o=null;if(r.length>0){o=new Path2D;const a=e==0?Hu:hp;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 r5(r,e,t){let n=r[r.length-1];n&&n[0]==e?n[1]=t:r.push([e,t])}function dp(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]),g=d-i;f=o<=0&&g>=0&&g<l?s(r[g]):f;let y=h+i;p=o>=0&&y>=0&&y<l?s(r[y]):p,p>=f&&a.push([f,p])}return a}function ny(r){return r==0?Hb:r==1?Lt:e=>Ji(e,r)}function fC(r){let e=r==0?Nu:Wu,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=Mn(u,a/2,l/2),c=Mn(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 Nu=(r,e,t)=>{r.moveTo(e,t)},Wu=(r,e,t)=>{r.moveTo(t,e)},bo=(r,e,t)=>{r.lineTo(e,t)},Co=(r,e,t)=>{r.lineTo(t,e)},Hu=fC(0),hp=fC(1),pC=(r,e,t,n,i,s)=>{r.arc(e,t,n,i,s)},gC=(r,e,t,n,i,s)=>{r.arc(t,e,n,i,s)},mC=(r,e,t,n,i,s,o)=>{r.bezierCurveTo(e,t,n,i,s,o)},yC=(r,e,t,n,i,s,o)=>{r.bezierCurveTo(t,e,i,n,o,s)};function vC(r){return(e,t,n,i,s)=>ms(e,t,(o,a,l,u,c,d,h,f,p,g,x)=>{let{pxRound:y,points:m}=o,v,b;u.ori==0?(v=Nu,b=pC):(v=Wu,b=gC);const I=Je(m.width*Ve,3);let S=(m.size-m.width)/2*Ve,M=Je(S*2,3),U=new Path2D,z=new Path2D,{left:O,top:R,width:B,height:A}=e.bbox;Hu(z,O-M,R-M,B+M*2,A+M*2);const V=N=>{if(l[N]!=null){let H=y(d(a[N],u,g,f)),P=y(h(l[N],c,x,p));v(U,H+S,P),b(U,H,P,S,0,Ll*2)}};if(s)s.forEach(V);else for(let N=n;N<=i;N++)V(N);return{stroke:I>0?U:null,fill:U,clip:z,flags:fo|Fh}})}function wC(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 n5=wC(bo),i5=wC(Co);function bC(r){const e=_e(r==null?void 0:r.alignGaps,0);return(t,n,i,s)=>ms(t,n,(o,a,l,u,c,d,h,f,p,g,x)=>{[i,s]=Bu(l,i,s);let y=o.pxRound,m=A=>y(d(A,u,g,f)),v=A=>y(h(A,c,x,p)),b,I;u.ori==0?(b=bo,I=n5):(b=Co,I=i5);const S=u.dir*(u.ori==0?1:-1),M={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:fo},U=M.stroke;let z=!1;if(s-i>=g*4){let A=Z=>t.posToVal(Z,u.key,!0),V=null,N=null,H,P,W,j=m(a[S==1?i:s]),X=m(a[i]),te=m(a[s]),Q=A(S==1?X+1:te-1);for(let Z=S==1?i:s;Z>=i&&Z<=s;Z+=S){let se=a[Z],ge=(S==1?se<Q:se>Q)?j:m(se),be=l[Z];ge==j?be!=null?(P=be,V==null?(b(U,ge,v(P)),H=V=N=P):P<V?V=P:P>N&&(N=P)):be===null&&(z=!0):(V!=null&&I(U,j,v(V),v(N),v(H),v(P)),be!=null?(P=be,b(U,ge,v(P)),V=N=H=P):(V=N=null,be===null&&(z=!0)),j=ge,Q=A(j+S))}V!=null&&V!=N&&W!=j&&I(U,j,v(V),v(N),v(H),v(P))}else for(let A=S==1?i:s;A>=i&&A<=s;A+=S){let V=l[A];V===null?z=!0:V!=null&&b(U,m(a[A]),v(V))}let[R,B]=cp(t,n);if(o.fill!=null||R!=0){let A=M.fill=new Path2D(U),V=o.fillTo(t,n,o.min,o.max,R),N=v(V),H=m(a[i]),P=m(a[s]);S==-1&&([P,H]=[H,P]),b(A,P,N),b(A,H,N)}if(!o.spanGaps){let A=[];z&&A.push(...dp(a,l,i,s,S,m,e)),M.gaps=A=o.gaps(t,n,i,s,A),M.clip=$u(A,u.ori,f,p,g,x)}return B!=0&&(M.band=B==2?[ri(t,n,i,s,U,-1),ri(t,n,i,s,U,1)]:ri(t,n,i,s,U,B)),M})}function s5(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)=>ms(s,o,(u,c,d,h,f,p,g,x,y,m,v)=>{[a,l]=Bu(d,a,l);let b=u.pxRound,{left:I,width:S}=s.bbox,M=X=>b(p(X,h,m,x)),U=X=>b(g(X,f,v,y)),z=h.ori==0?bo:Co;const O={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:fo},R=O.stroke,B=h.dir*(h.ori==0?1:-1);let A=U(d[B==1?a:l]),V=M(c[B==1?a:l]),N=V,H=V;i&&e==-1&&(H=I,z(R,H,A)),z(R,V,A);for(let X=B==1?a:l;X>=a&&X<=l;X+=B){let te=d[X];if(te==null)continue;let Q=M(c[X]),Z=U(te);e==1?z(R,Q,A):z(R,N,Z),z(R,Q,Z),A=Z,N=Q}let P=N;i&&e==1&&(P=I+S,z(R,P,A));let[W,j]=cp(s,o);if(u.fill!=null||W!=0){let X=O.fill=new Path2D(R),te=u.fillTo(s,o,u.min,u.max,W),Q=U(te);z(X,P,Q),z(X,H,Q)}if(!u.spanGaps){let X=[];X.push(...dp(c,d,a,l,B,M,n));let te=u.width*Ve/2,Q=t||e==1?te:-te,Z=t||e==-1?-te:te;X.forEach(se=>{se[0]+=Q,se[1]+=Z}),O.gaps=X=u.gaps(s,o,a,l,X),O.clip=$u(X,h.ori,x,y,m,v)}return j!=0&&(O.band=j==2?[ri(s,o,a,l,R,-1),ri(s,o,a,l,R,1)]:ri(s,o,a,l,R,j)),O})}function iy(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=Wt(r[l]-r[a]);c<u&&(u=c,o=Wt(t(r[l],n,i,s)-t(r[a],n,i,s)))}a=l}}return o}function o5(r){r=r||fa;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,fa),c=_e(r.each,f=>{}),{fill:d,stroke:h}=u;return(f,p,g,x)=>ms(f,p,(y,m,v,b,I,S,M,U,z,O,R)=>{let B=y.pxRound,A=t,V=n*Ve,N=a*Ve,H=l*Ve,P,W;b.ori==0?[P,W]=s(f,p):[W,P]=s(f,p);const j=b.dir*(b.ori==0?1:-1);let X=b.ori==0?Hu:hp,te=b.ori==0?c:(ne,$e,ht,J,G,le,ye)=>{c(ne,$e,ht,G,J,ye,le)},Q=_e(f.bands,sp).find(ne=>ne.series[0]==p),Z=Q!=null?Q.dir:0,se=y.fillTo(f,p,y.min,y.max,Z),ve=B(M(se,I,R,z)),ge,be,ct,dt=O,Se=B(y.width*Ve),et=!1,Ze=null,qe=null,Mt=null,mt=null;d!=null&&(Se==0||h!=null)&&(et=!0,Ze=d.values(f,p,g,x),qe=new Map,new Set(Ze).forEach(ne=>{ne!=null&&qe.set(ne,new Path2D)}),Se>0&&(Mt=h.values(f,p,g,x),mt=new Map,new Set(Mt).forEach(ne=>{ne!=null&&mt.set(ne,new Path2D)})));let{x0:Ot,size:dr}=u;if(Ot!=null&&dr!=null){A=1,m=Ot.values(f,p,g,x),Ot.unit==2&&(m=m.map(ht=>f.posToVal(U+ht*O,b.key,!0)));let ne=dr.values(f,p,g,x);dr.unit==2?be=ne[0]*O:be=S(ne[0],b,O,U)-S(0,b,O,U),dt=iy(m,v,S,b,O,U,dt),ct=dt-be+V}else dt=iy(m,v,S,b,O,U,dt),ct=dt*o+V,be=dt-ct;ct<1&&(ct=0),Se>=be/2&&(Se=0),ct<5&&(B=Hb);let tt=ct>0,xt=dt-ct-(tt?Se:0);be=B(Dh(xt,H,N)),ge=(A==0?be/2:A==j?0:be)-A*j*((A==0?V/2:0)+(tt?Se/2:0));const nt={stroke:null,fill:null,clip:null,band:null,gaps:null,flags:0},br=et?null:new Path2D;let xe=null;if(Q!=null)xe=f.data[Q.series[1]];else{let{y0:ne,y1:$e}=u;ne!=null&&$e!=null&&(v=$e.values(f,p,g,x),xe=ne.values(f,p,g,x))}let Re=P*be,pe=W*be;for(let ne=j==1?g:x;ne>=g&&ne<=x;ne+=j){let $e=v[ne];if($e==null)continue;if(xe!=null){let Ee=xe[ne]??0;if($e-Ee==0)continue;ve=M(Ee,I,R,z)}let ht=b.distr!=2||u!=null?m[ne]:ne,J=S(ht,b,O,U),G=M(_e($e,se),I,R,z),le=B(J-ge),ye=B(Mr(G,ve)),de=B(Mn(G,ve)),Te=ye-de;if($e!=null){let Ee=$e<0?pe:Re,Me=$e<0?Re:pe;et?(Se>0&&Mt[ne]!=null&&X(mt.get(Mt[ne]),le,de+qr(Se/2),be,Mr(0,Te-Se),Ee,Me),Ze[ne]!=null&&X(qe.get(Ze[ne]),le,de+qr(Se/2),be,Mr(0,Te-Se),Ee,Me)):X(br,le,de+qr(Se/2),be,Mr(0,Te-Se),Ee,Me),te(f,p,ne,le-Se/2,de,be+Se,Te)}}return Se>0?nt.stroke=et?mt:br:et||(nt._fill=y.width==0?y._fill:y._stroke??y._fill,nt.width=0),nt.fill=et?qe:br,nt})}function a5(r,e){const t=_e(e==null?void 0:e.alignGaps,0);return(n,i,s,o)=>ms(n,i,(a,l,u,c,d,h,f,p,g,x,y)=>{[s,o]=Bu(u,s,o);let m=a.pxRound,v=P=>m(h(P,c,x,p)),b=P=>m(f(P,d,y,g)),I,S,M;c.ori==0?(I=Nu,M=bo,S=mC):(I=Wu,M=Co,S=yC);const U=c.dir*(c.ori==0?1:-1);let z=v(l[U==1?s:o]),O=z,R=[],B=[];for(let P=U==1?s:o;P>=s&&P<=o;P+=U)if(u[P]!=null){let j=l[P],X=v(j);R.push(O=X),B.push(b(u[P]))}const A={stroke:r(R,B,I,M,S,m),fill:null,clip:null,band:null,gaps:null,flags:fo},V=A.stroke;let[N,H]=cp(n,i);if(a.fill!=null||N!=0){let P=A.fill=new Path2D(V),W=a.fillTo(n,i,a.min,a.max,N),j=b(W);M(P,O,j),M(P,z,j)}if(!a.spanGaps){let P=[];P.push(...dp(l,u,s,o,U,v,t)),A.gaps=P=a.gaps(n,i,s,o,P),A.clip=$u(P,c.ori,p,g,x,y)}return H!=0&&(A.band=H==2?[ri(n,i,s,o,V,-1),ri(n,i,s,o,V,1)]:ri(n,i,s,o,V,H)),A})}function l5(r){return a5(u5,r)}function u5(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 Lh=new Set;function sy(){for(let r of Lh)r.syncRect(!0)}wo&&(as(HM,eo,sy),as(VM,eo,sy,!0),as(fu,eo,()=>{yr.pxRatio=Ve}));const c5=bC(),d5=vC();function oy(r,e,t,n){return(n?[r[0],r[1]].concat(r.slice(2)):[r[0]].concat(r.slice(1))).map((s,o)=>_h(s,o,e,t))}function h5(r,e){return r.map((t,n)=>n==0?{}:Pt({},e,t))}function _h(r,e,t,n){return Pt({},e==0?t:n,r)}function CC(r,e,t){return e==null?co:[e,t]}const f5=CC;function p5(r,e,t){return e==null?co:pu(e,t,np,!0)}function xC(r,e,t,n){return e==null?co:Fu(e,t,r.scales[n].log,!1)}const g5=xC;function SC(r,e,t,n){return e==null?co:rp(e,t,r.scales[n].log,!1)}const m5=SC;function y5(r,e,t,n,i){let s=Mr(Lm(r),Lm(e)),o=e-r,a=kn(i/n*o,t);do{let l=t[a],u=n*l/o;if(u>=i&&s+(l<5?Bi.get(l):0)<=17)return[l,u]}while(++a<t.length);return[0,0]}function ay(r){let e,t;return r=r.replace(/(\d+)px/,(n,i)=>(e=Lt((t=+i)*Ve))+"px"),[r,e,t]}function v5(r){r.show&&[r.font,r.labelFont].forEach(e=>{let t=Je(e[2]*Ve,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(w,C,E,T){let D=C.valToPct(w);return T+E*(C.dir==-1?1-D:D)}function o(w,C,E,T){let D=C.valToPct(w);return T+E*(C.dir==-1?D:1-D)}function a(w,C,E,T){return C.ori==0?s(w,C,E,T):o(w,C,E,T)}n.valToPosH=s,n.valToPosV=o;let l=!1;n.status=0;const u=n.root=an(kM);if(r.id!=null&&(u.id=r.id),Yr(u,r.class),r.title){let w=an(TM,u);w.textContent=r.title}const c=Cn("canvas"),d=n.ctx=c.getContext("2d"),h=an(UM,u);as("click",h,w=>{w.target===p&&(it!=Ss||pt!=Is)&&ir.click(n,w)},!0);const f=n.under=an(AM,h);h.appendChild(c);const p=n.over=an(RM,h);r=ho(r);const g=+_e(r.pxAlign,1),x=ny(g);(r.plugins||[]).forEach(w=>{w.opts&&(r=w.opts(n,r)||r)});const y=r.ms||.001,m=n.series=i==1?oy(r.series||[],Km,ty,!1):h5(r.series||[null],ey),v=n.axes=oy(r.axes||[],Zm,Qm,!0),b=n.scales={},I=n.bands=r.bands||[];I.forEach(w=>{w.fill=Pe(w.fill||null),w.dir=_e(w.dir,-1)});const S=i==2?m[1].facets[0].scale:m[0].scale,M={axes:BC,series:RC},U=(r.drawOrder||["axes","series"]).map(w=>M[w]);function z(w){const C=w.distr==3?E=>ti(E>0?E:w.clamp(n,E,w.min,w.max,w.key)):w.distr==4?E=>nd(E,w.asinh):w.distr==100?E=>w.fwd(E):E=>E;return E=>{let T=C(E),{_min:D,_max:_}=w,Y=_-D;return(T-D)/Y}}function O(w){let C=b[w];if(C==null){let E=(r.scales||fa)[w]||fa;if(E.from!=null){O(E.from);let T=Pt({},b[E.from],E,{key:w});T.valToPct=z(T),b[w]=T}else{C=b[w]=Pt({},w==S?dC:e5,E),C.key=w;let T=C.time,D=C.range,_=vi(D);if((w!=S||i==2&&!T)&&(_&&(D[0]==null||D[1]==null)&&(D={min:D[0]==null?Om:{mode:1,hard:D[0],soft:D[0]},max:D[1]==null?Om:{mode:1,hard:D[1],soft:D[1]}},_=!1),!_&&_u(D))){let Y=D;D=(q,re,ae)=>re==null?co:pu(re,ae,Y)}C.range=Pe(D||(T?f5:w==S?C.distr==3?g5:C.distr==4?m5:CC:C.distr==3?xC:C.distr==4?SC:p5)),C.auto=Pe(_?!1:C.auto),C.clamp=Pe(C.clamp||JT),C._min=C._max=null,C.valToPct=z(C)}}}O("x"),O("y"),i==1&&m.forEach(w=>{O(w.scale)}),v.forEach(w=>{O(w.scale)});for(let w in r.scales)O(w);const R=b[S],B=R.distr;let A,V;R.ori==0?(Yr(u,EM),A=s,V=o):(Yr(u,MM),A=o,V=s);const N={};for(let w in b){let C=b[w];(C.min!=null||C.max!=null)&&(N[w]={min:C.min,max:C.max},C.min=C.max=null)}const H=r.tzDate||(w=>new Date(Lt(w/y))),P=r.fmtDate||op,W=y==1?ET(H):UT(H),j=Ym(H,jm(y==1?kT:TT,P)),X=Xm(H,Gm(RT,P)),te=[],Q=n.legend=Pt({},DT,r.legend),Z=n.cursor=Pt({},$T,{drag:{y:i==2}},r.cursor),se=Q.show,ve=Z.show,ge=Q.markers;Q.idxs=te,ge.width=Pe(ge.width),ge.dash=Pe(ge.dash),ge.stroke=Pe(ge.stroke),ge.fill=Pe(ge.fill);let be,ct,dt,Se=[],et=[],Ze,qe=!1,Mt={};if(Q.live){const w=m[1]?m[1].values:null;qe=w!=null,Ze=qe?w(n,1,0):{_:0};for(let C in Ze)Mt[C]=ep}if(se)if(be=Cn("table",FM,u),dt=Cn("tbody",null,be),Q.mount(n,be),qe){ct=Cn("thead",null,be,dt);let w=Cn("tr",null,ct);Cn("th",null,w);for(var mt in Ze)Cn("th",xm,w).textContent=mt}else Yr(be,_M),Q.live&&Yr(be,LM);const Ot={show:!0},dr={show:!1};function tt(w,C){if(C==0&&(qe||!Q.live||i==2))return co;let E=[],T=Cn("tr",$M,dt,dt.childNodes[C]);Yr(T,w.class),w.show||Yr(T,ts);let D=Cn("th",null,T);if(ge.show){let q=an(NM,D);if(C>0){let re=ge.width(n,C);re&&(q.style.border=re+"px "+ge.dash(n,C)+" "+ge.stroke(n,C)),q.style.background=ge.fill(n,C)}}let _=an(xm,D);w.label instanceof HTMLElement?_.appendChild(w.label):_.textContent=w.label,C>0&&(ge.show||(_.style.color=w.width>0?ge.stroke(n,C):ge.fill(n,C)),nt("click",D,q=>{if(Z._lock)return;Pr(q);let re=m.indexOf(w);if((q.ctrlKey||q.metaKey)!=Q.isolate){let ae=m.some((ue,he)=>he>0&&he!=re&&ue.show);m.forEach((ue,he)=>{he>0&&On(he,ae?he==re?Ot:dr:Ot,!0,Rt.setSeries)})}else On(re,{show:!w.show},!0,Rt.setSeries)},!1),Rn&&nt(Em,D,q=>{Z._lock||(Pr(q),On(m.indexOf(w),Es,!0,Rt.setSeries))},!1));for(var Y in Ze){let q=Cn("td",WM,T);q.textContent="--",E.push(q)}return[T,E]}const xt=new Map;function nt(w,C,E,T=!0){const D=xt.get(C)||{},_=Z.bind[w](n,C,E,T);_&&(as(w,C,D[w]=_),xt.set(C,D))}function br(w,C,E){const T=xt.get(C)||{};for(let D in T)(w==null||D==w)&&(zh(D,C,T[D]),delete T[D]);w==null&&xt.delete(C)}let xe=0,Re=0,pe=0,ne=0,$e=0,ht=0,J=$e,G=ht,le=pe,ye=ne,de=0,Te=0,Ee=0,Me=0;n.bbox={};let Ne=!1,we=!1,Be=!1,Tt=!1,ft=!1,We=!1;function Yt(w,C,E){(E||w!=n.width||C!=n.height)&&Bt(w,C),ws(!1),Be=!0,we=!0,bs()}function Bt(w,C){n.width=xe=pe=w,n.height=Re=ne=C,$e=ht=0,Fe(),Wi();let E=n.bbox;de=E.left=Ji($e*Ve,.5),Te=E.top=Ji(ht*Ve,.5),Ee=E.width=Ji(pe*Ve,.5),Me=E.height=Ji(ne*Ve,.5)}const li=3;function $i(){let w=!1,C=0;for(;!w;){C++;let E=DC(C),T=OC(C);w=C==li||E&&T,w||(Bt(n.width,n.height),we=!0)}}function Ni({width:w,height:C}){Yt(w,C)}n.setSize=Ni;function Fe(){let w=!1,C=!1,E=!1,T=!1;v.forEach((D,_)=>{if(D.show&&D._show){let{side:Y,_size:q}=D,re=Y%2,ae=D.label!=null?D.labelSize:0,ue=q+ae;ue>0&&(re?(pe-=ue,Y==3?($e+=ue,T=!0):E=!0):(ne-=ue,Y==0?(ht+=ue,w=!0):C=!0))}}),Vi[0]=w,Vi[1]=E,Vi[2]=C,Vi[3]=T,pe-=ui[1]+ui[3],$e+=ui[3],ne-=ui[2]+ui[0],ht+=ui[0]}function Wi(){let w=$e+pe,C=ht+ne,E=$e,T=ht;function D(_,Y){switch(_){case 1:return w+=Y,w-Y;case 2:return C+=Y,C-Y;case 3:return E-=Y,E+Y;case 0:return T-=Y,T+Y}}v.forEach((_,Y)=>{if(_.show&&_._show){let q=_.side;_._pos=D(q,_._size),_.label!=null&&(_._lpos=D(q,_.labelSize))}})}if(Z.dataIdx==null){let w=Z.hover,C=w.skip=new Set(w.skip??[]);C.add(void 0);let E=w.prox=Pe(w.prox),T=w.bias??(w.bias=0);Z.dataIdx=(D,_,Y,q)=>{if(_==0)return Y;let re=Y,ae=E(D,_,Y,q)??Qe,ue=ae>=0&&ae<Qe,he=R.ori==0?pe:ne,Ie=Z.left,He=e[0],Le=e[_];if(C.has(Le[Y])){re=null;let Ue=null,Ce=null,me;if(T==0||T==-1)for(me=Y;Ue==null&&me-- >0;)C.has(Le[me])||(Ue=me);if(T==0||T==1)for(me=Y;Ce==null&&me++<Le.length;)C.has(Le[me])||(Ce=me);if(Ue!=null||Ce!=null)if(ue){let ot=Ue==null?-1/0:A(He[Ue],R,he,0),St=Ce==null?1/0:A(He[Ce],R,he,0),Qt=Ie-ot,Ke=St-Ie;Qt<=Ke?Qt<=ae&&(re=Ue):Ke<=ae&&(re=Ce)}else re=Ce==null?Ue:Ue==null?Ce:Y-Ue<=Ce-Y?Ue:Ce}else ue&&Wt(Ie-A(He[Y],R,he,0))>ae&&(re=null);return re}}const Pr=w=>{Z.event=w};Z.idxs=te,Z._lock=!1;let yt=Z.points;yt.show=Pe(yt.show),yt.size=Pe(yt.size),yt.stroke=Pe(yt.stroke),yt.width=Pe(yt.width),yt.fill=Pe(yt.fill);const hr=n.focus=Pt({},r.focus||{alpha:.3},Z.focus),Rn=hr.prox>=0,Pn=Rn&&yt.one;let fr=[],zn=[],Dn=[];function ys(w,C){let E=yt.show(n,C);if(E instanceof HTMLElement)return Yr(E,BM),Yr(E,w.class),$n(E,-10,-10,pe,ne),p.insertBefore(E,fr[C]),E}function At(w,C){if(i==1||C>0){let E=i==1&&b[w.scale].time,T=w.value;w.value=E?Nm(T)?Xm(H,Gm(T,P)):T||X:T||KT,w.label=w.label||(E?WT:NT)}if(Pn||C>0){w.width=w.width==null?1:w.width,w.paths=w.paths||c5||eT,w.fillTo=Pe(w.fillTo||t5),w.pxAlign=+_e(w.pxAlign,g),w.pxRound=ny(w.pxAlign),w.stroke=Pe(w.stroke||null),w.fill=Pe(w.fill||null),w._stroke=w._fill=w._paths=w._focus=null;let E=qT(Mr(1,w.width),1),T=w.points=Pt({},{size:E,width:Mr(1,E*.2),stroke:w.stroke,space:E*2,paths:d5,_stroke:null,_fill:null},w.points);T.show=Pe(T.show),T.filter=Pe(T.filter),T.fill=Pe(T.fill),T.stroke=Pe(T.stroke),T.paths=Pe(T.paths),T.pxAlign=w.pxAlign}if(se){let E=tt(w,C);Se.splice(C,0,E[0]),et.splice(C,0,E[1]),Q.values.push(null)}if(ve){te.splice(C,0,null);let E=null;Pn?C==0&&(E=ys(w,C)):C>0&&(E=ys(w,C)),fr.splice(C,0,E),zn.splice(C,0,0),Dn.splice(C,0,0)}qt("addSeries",C)}function vt(w,C){C=C??m.length,w=i==1?_h(w,C,Km,ty):_h(w,C,{},ey),m.splice(C,0,w),At(m[C],C)}n.addSeries=vt;function Hi(w){if(m.splice(w,1),se){Q.values.splice(w,1),et.splice(w,1);let C=Se.splice(w,1)[0];br(null,C.firstChild),C.remove()}ve&&(te.splice(w,1),fr.splice(w,1)[0].remove(),zn.splice(w,1),Dn.splice(w,1)),qt("delSeries",w)}n.delSeries=Hi;const Vi=[!1,!1,!1,!1];function TC(w,C){if(w._show=w.show,w.show){let E=w.side%2,T=b[w.scale];T==null&&(w.scale=E?m[1].scale:S,T=b[w.scale]);let D=T.time;w.size=Pe(w.size),w.space=Pe(w.space),w.rotate=Pe(w.rotate),vi(w.incrs)&&w.incrs.forEach(Y=>{!Bi.has(Y)&&Bi.set(Y,Yb(Y))}),w.incrs=Pe(w.incrs||(T.distr==2?xT:D?y==1?IT:MT:es)),w.splits=Pe(w.splits||(D&&T.distr==1?W:T.distr==3?Oh:T.distr==4?jT:VT)),w.stroke=Pe(w.stroke),w.grid.stroke=Pe(w.grid.stroke),w.ticks.stroke=Pe(w.ticks.stroke),w.border.stroke=Pe(w.border.stroke);let _=w.values;w.values=vi(_)&&!vi(_[0])?Pe(_):D?vi(_)?Ym(H,jm(_,P)):Nm(_)?AT(H,_):_||j:_||HT,w.filter=Pe(w.filter||(T.distr>=3&&T.log==10?XT:T.distr==3&&T.log==2?ZT:Vb)),w.font=ay(w.font),w.labelFont=ay(w.labelFont),w._size=w.size(n,null,C,0),w._space=w._rotate=w._incrs=w._found=w._splits=w._values=null,w._size>0&&(Vi[C]=!0,w._el=an(PM,h))}}function So(w,C,E,T){let[D,_,Y,q]=E,re=C%2,ae=0;return re==0&&(q||_)&&(ae=C==0&&!D||C==2&&!Y?Lt(Zm.size/3):0),re==1&&(D||Y)&&(ae=C==1&&!_||C==3&&!q?Lt(Qm.size/2):0),ae}const gp=n.padding=(r.padding||[So,So,So,So]).map(w=>Pe(_e(w,So))),ui=n._padding=gp.map((w,C)=>w(n,C,Vi,0));let nr,Gt=null,Xt=null;const Na=i==1?m[0].idxs:null;let mn=null,Io=!1;function mp(w,C){if(e=w??[],n.data=n._data=e,i==2){nr=0;for(let E=1;E<m.length;E++)nr+=e[E][0].length}else{e.length==0&&(n.data=n._data=e=[[]]),mn=e[0],nr=mn.length;let E=e;if(B==2){E=e.slice();let T=E[0]=Array(nr);for(let D=0;D<nr;D++)T[D]=D}n._data=e=E}if(ws(!0),qt("setData"),B==2&&(Be=!0),C!==!1){let E=R;E.auto(n,Io)?Vu():di(S,E.min,E.max),Tt=Tt||Z.left>=0,We=!0,bs()}}n.setData=mp;function Vu(){Io=!0;let w,C;i==1&&(nr>0?(Gt=Na[0]=0,Xt=Na[1]=nr-1,w=e[0][Gt],C=e[0][Xt],B==2?(w=Gt,C=Xt):w==C&&(B==3?[w,C]=Fu(w,w,R.log,!1):B==4?[w,C]=rp(w,w,R.log,!1):R.time?C=w+Lt(86400/y):[w,C]=pu(w,C,np,!0))):(Gt=Na[0]=w=null,Xt=Na[1]=C=null)),di(S,w,C)}let Wa,vs,ju,Yu,Gu,Xu,Zu,Ku,qu,zr;function yp(w,C,E,T,D,_){w??(w=Im),E??(E=sp),T??(T="butt"),D??(D=Im),_??(_="round"),w!=Wa&&(d.strokeStyle=Wa=w),D!=vs&&(d.fillStyle=vs=D),C!=ju&&(d.lineWidth=ju=C),_!=Gu&&(d.lineJoin=Gu=_),T!=Xu&&(d.lineCap=Xu=T),E!=Yu&&d.setLineDash(Yu=E)}function vp(w,C,E,T){C!=vs&&(d.fillStyle=vs=C),w!=Zu&&(d.font=Zu=w),E!=Ku&&(d.textAlign=Ku=E),T!=qu&&(d.textBaseline=qu=T)}function Qu(w,C,E,T,D=0){if(T.length>0&&w.auto(n,Io)&&(C==null||C.min==null)){let _=_e(Gt,0),Y=_e(Xt,T.length-1),q=E.min==null?XM(T,_,Y,D,w.distr==3):[E.min,E.max];w.min=Mn(w.min,E.min=q[0]),w.max=Mr(w.max,E.max=q[1])}}const wp={min:null,max:null};function UC(){for(let T in b){let D=b[T];N[T]==null&&(D.min==null||N[S]!=null&&D.auto(n,Io))&&(N[T]=wp)}for(let T in b){let D=b[T];N[T]==null&&D.from!=null&&N[D.from]!=null&&(N[T]=wp)}N[S]!=null&&ws(!0);let w={};for(let T in N){let D=N[T];if(D!=null){let _=w[T]=ho(b[T],nT);if(D.min!=null)Pt(_,D);else if(T!=S||i==2)if(nr==0&&_.from==null){let Y=_.range(n,null,null,T);_.min=Y[0],_.max=Y[1]}else _.min=Qe,_.max=-Qe}}if(nr>0){m.forEach((T,D)=>{if(i==1){let _=T.scale,Y=N[_];if(Y==null)return;let q=w[_];if(D==0){let re=q.range(n,q.min,q.max,_);q.min=re[0],q.max=re[1],Gt=kn(q.min,e[0]),Xt=kn(q.max,e[0]),Xt-Gt>1&&(e[0][Gt]<q.min&&Gt++,e[0][Xt]>q.max&&Xt--),T.min=mn[Gt],T.max=mn[Xt]}else T.show&&T.auto&&Qu(q,Y,T,e[D],T.sorted);T.idxs[0]=Gt,T.idxs[1]=Xt}else if(D>0&&T.show&&T.auto){let[_,Y]=T.facets,q=_.scale,re=Y.scale,[ae,ue]=e[D],he=w[q],Ie=w[re];he!=null&&Qu(he,N[q],_,ae,_.sorted),Ie!=null&&Qu(Ie,N[re],Y,ue,Y.sorted),T.min=Y.min,T.max=Y.max}});for(let T in w){let D=w[T],_=N[T];if(D.from==null&&(_==null||_.min==null)){let Y=D.range(n,D.min==Qe?null:D.min,D.max==-Qe?null:D.max,T);D.min=Y[0],D.max=Y[1]}}}for(let T in w){let D=w[T];if(D.from!=null){let _=w[D.from];if(_.min==null)D.min=D.max=null;else{let Y=D.range(n,_.min,_.max,T);D.min=Y[0],D.max=Y[1]}}}let C={},E=!1;for(let T in w){let D=w[T],_=b[T];if(_.min!=D.min||_.max!=D.max){_.min=D.min,_.max=D.max;let Y=_.distr;_._min=Y==3?ti(_.min):Y==4?nd(_.min,_.asinh):Y==100?_.fwd(_.min):_.min,_._max=Y==3?ti(_.max):Y==4?nd(_.max,_.asinh):Y==100?_.fwd(_.max):_.max,C[T]=E=!0}}if(E){m.forEach((T,D)=>{i==2?D>0&&C.y&&(T._paths=null):C[T.scale]&&(T._paths=null)});for(let T in C)Be=!0,qt("setScale",T);ve&&Z.left>=0&&(Tt=We=!0)}for(let T in N)N[T]=null}function AC(w){let C=Dh(Gt-1,0,nr-1),E=Dh(Xt+1,0,nr-1);for(;w[C]==null&&C>0;)C--;for(;w[E]==null&&E<nr-1;)E++;return[C,E]}function RC(){if(nr>0){let w=m.some(C=>C._focus)&&zr!=hr.alpha;w&&(d.globalAlpha=zr=hr.alpha),m.forEach((C,E)=>{if(E>0&&C.show&&(bp(E,!1),bp(E,!0),C._paths==null)){let T=zr;zr!=C.alpha&&(d.globalAlpha=zr=C.alpha);let D=i==2?[0,e[E][0].length-1]:AC(e[E]);C._paths=C.paths(n,E,D[0],D[1]),zr!=T&&(d.globalAlpha=zr=T)}}),m.forEach((C,E)=>{if(E>0&&C.show){let T=zr;zr!=C.alpha&&(d.globalAlpha=zr=C.alpha),C._paths!=null&&Cp(E,!1);{let D=C._paths!=null?C._paths.gaps:null,_=C.points.show(n,E,Gt,Xt,D),Y=C.points.filter(n,E,_,D);(_||Y)&&(C.points._paths=C.points.paths(n,E,Gt,Xt,Y),Cp(E,!0))}zr!=T&&(d.globalAlpha=zr=T),qt("drawSeries",E)}}),w&&(d.globalAlpha=zr=1)}}function bp(w,C){let E=C?m[w].points:m[w];E._stroke=E.stroke(n,w),E._fill=E.fill(n,w)}function Cp(w,C){let E=C?m[w].points:m[w],{stroke:T,fill:D,clip:_,flags:Y,_stroke:q=E._stroke,_fill:re=E._fill,_width:ae=E.width}=E._paths;ae=Je(ae*Ve,3);let ue=null,he=ae%2/2;C&&re==null&&(re=ae>0?"#fff":q);let Ie=E.pxAlign==1&&he>0;if(Ie&&d.translate(he,he),!C){let He=de-ae/2,Le=Te-ae/2,Ue=Ee+ae,Ce=Me+ae;ue=new Path2D,ue.rect(He,Le,Ue,Ce)}C?Ju(q,ae,E.dash,E.cap,re,T,D,Y,_):PC(w,q,ae,E.dash,E.cap,re,T,D,Y,ue,_),Ie&&d.translate(-he,-he)}function PC(w,C,E,T,D,_,Y,q,re,ae,ue){let he=!1;re!=0&&I.forEach((Ie,He)=>{if(Ie.series[0]==w){let Le=m[Ie.series[1]],Ue=e[Ie.series[1]],Ce=(Le._paths||fa).band;vi(Ce)&&(Ce=Ie.dir==1?Ce[0]:Ce[1]);let me,ot=null;Le.show&&Ce&&KM(Ue,Gt,Xt)?(ot=Ie.fill(n,He)||_,me=Le._paths.clip):Ce=null,Ju(C,E,T,D,ot,Y,q,re,ae,ue,me,Ce),he=!0}}),he||Ju(C,E,T,D,_,Y,q,re,ae,ue)}const xp=fo|Fh;function Ju(w,C,E,T,D,_,Y,q,re,ae,ue,he){yp(w,C,E,T,D),(re||ae||he)&&(d.save(),re&&d.clip(re),ae&&d.clip(ae)),he?(q&xp)==xp?(d.clip(he),ue&&d.clip(ue),Va(D,Y),Ha(w,_,C)):q&Fh?(Va(D,Y),d.clip(he),Ha(w,_,C)):q&fo&&(d.save(),d.clip(he),ue&&d.clip(ue),Va(D,Y),d.restore(),Ha(w,_,C)):(Va(D,Y),Ha(w,_,C)),(re||ae||he)&&d.restore()}function Ha(w,C,E){E>0&&(C instanceof Map?C.forEach((T,D)=>{d.strokeStyle=Wa=D,d.stroke(T)}):C!=null&&w&&d.stroke(C))}function Va(w,C){C instanceof Map?C.forEach((E,T)=>{d.fillStyle=vs=T,d.fill(E)}):C!=null&&w&&d.fill(C)}function zC(w,C,E,T){let D=v[w],_;if(T<=0)_=[0,0];else{let Y=D._space=D.space(n,w,C,E,T),q=D._incrs=D.incrs(n,w,C,E,T,Y);_=y5(C,E,q,T,Y)}return D._found=_}function ec(w,C,E,T,D,_,Y,q,re,ae){let ue=Y%2/2;g==1&&d.translate(ue,ue),yp(q,Y,re,ae,q),d.beginPath();let he,Ie,He,Le,Ue=D+(T==0||T==3?-_:_);E==0?(Ie=D,Le=Ue):(he=D,He=Ue);for(let Ce=0;Ce<w.length;Ce++)C[Ce]!=null&&(E==0?he=He=w[Ce]:Ie=Le=w[Ce],d.moveTo(he,Ie),d.lineTo(He,Le));d.stroke(),g==1&&d.translate(-ue,-ue)}function DC(w){let C=!0;return v.forEach((E,T)=>{if(!E.show)return;let D=b[E.scale];if(D.min==null){E._show&&(C=!1,E._show=!1,ws(!1));return}else E._show||(C=!1,E._show=!0,ws(!1));let _=E.side,Y=_%2,{min:q,max:re}=D,[ae,ue]=zC(T,q,re,Y==0?pe:ne);if(ue==0)return;let he=D.distr==2,Ie=E._splits=E.splits(n,T,q,re,ae,ue,he),He=D.distr==2?Ie.map(me=>mn[me]):Ie,Le=D.distr==2?mn[Ie[1]]-mn[Ie[0]]:ae,Ue=E._values=E.values(n,E.filter(n,He,T,ue,Le),T,ue,Le);E._rotate=_==2?E.rotate(n,Ue,T,ue):0;let Ce=E._size;E._size=ln(E.size(n,Ue,T,w)),Ce!=null&&E._size!=Ce&&(C=!1)}),C}function OC(w){let C=!0;return gp.forEach((E,T)=>{let D=E(n,T,Vi,w);D!=ui[T]&&(C=!1),ui[T]=D}),C}function BC(){for(let w=0;w<v.length;w++){let C=v[w];if(!C.show||!C._show)continue;let E=C.side,T=E%2,D,_,Y=C.stroke(n,w),q=E==0||E==3?-1:1,[re,ae]=C._found;if(C.label!=null){let xr=C.labelGap*q,Vr=Lt((C._lpos+xr)*Ve);vp(C.labelFont[0],Y,"center",E==2?No:Sm),d.save(),T==1?(D=_=0,d.translate(Vr,Lt(Te+Me/2)),d.rotate((E==3?-Ll:Ll)/2)):(D=Lt(de+Ee/2),_=Vr);let Gi=Wb(C.label)?C.label(n,w,re,ae):C.label;d.fillText(Gi,D,_),d.restore()}if(ae==0)continue;let ue=b[C.scale],he=T==0?Ee:Me,Ie=T==0?de:Te,He=C._splits,Le=ue.distr==2?He.map(xr=>mn[xr]):He,Ue=ue.distr==2?mn[He[1]]-mn[He[0]]:re,Ce=C.ticks,me=C.border,ot=Ce.show?Ce.size:0,St=Lt(ot*Ve),Qt=Lt((C.alignTo==2?C._size-ot-C.gap:C.gap)*Ve),Ke=C._rotate*-Ll/180,It=x(C._pos*Ve),Wr=(St+Qt)*q,Cr=It+Wr;_=T==0?Cr:0,D=T==1?Cr:0;let nn=C.font[0],yn=C.align==1?Rs:C.align==2?ed:Ke>0?Rs:Ke<0?ed:T==0?"center":E==3?ed:Rs,Fn=Ke||T==1?"middle":E==2?No:Sm;vp(nn,Y,yn,Fn);let Hr=C.font[1]*C.lineGap,sn=He.map(xr=>x(a(xr,ue,he,Ie))),vn=C._values;for(let xr=0;xr<vn.length;xr++){let Vr=vn[xr];if(Vr!=null){T==0?D=sn[xr]:_=sn[xr],Vr=""+Vr;let Gi=Vr.indexOf(`
|
|
273
|
-
`)==-1?[Vr]:Vr.split(/\n/gm);for(let Sr=0;Sr<Gi.length;Sr++){let Np=Gi[Sr];Ke?(d.save(),d.translate(D,_+Sr*Hr),d.rotate(Ke),d.fillText(Np,0,0),d.restore()):d.fillText(Np,D,_+Sr*Hr)}}}Ce.show&&ec(sn,Ce.filter(n,Le,w,ae,Ue),T,E,It,St,Je(Ce.width*Ve,3),Ce.stroke(n,w),Ce.dash,Ce.cap);let Ln=C.grid;Ln.show&&ec(sn,Ln.filter(n,Le,w,ae,Ue),T,T==0?2:1,T==0?Te:de,T==0?Me:Ee,Je(Ln.width*Ve,3),Ln.stroke(n,w),Ln.dash,Ln.cap),me.show&&ec([It],[1],T==0?1:0,T==0?1:2,T==1?Te:de,T==1?Me:Ee,Je(me.width*Ve,3),me.stroke(n,w),me.dash,me.cap)}qt("drawAxes")}function ws(w){m.forEach((C,E)=>{E>0&&(C._paths=null,w&&(i==1?(C.min=null,C.max=null):C.facets.forEach(T=>{T.min=null,T.max=null})))})}let ja=!1,tc=!1,ko=[];function FC(){tc=!1;for(let w=0;w<ko.length;w++)qt(...ko[w]);ko.length=0}function bs(){ja||(cT(Sp),ja=!0)}function LC(w,C=!1){ja=!0,tc=C,w(n),Sp(),C&&ko.length>0&&queueMicrotask(FC)}n.batch=LC;function Sp(){if(Ne&&(UC(),Ne=!1),Be&&($i(),Be=!1),we){if(lt(f,Rs,$e),lt(f,No,ht),lt(f,qo,pe),lt(f,Qo,ne),lt(p,Rs,$e),lt(p,No,ht),lt(p,qo,pe),lt(p,Qo,ne),lt(h,qo,xe),lt(h,Qo,Re),c.width=Lt(xe*Ve),c.height=Lt(Re*Ve),v.forEach(({_el:w,_show:C,_size:E,_pos:T,side:D})=>{if(w!=null)if(C){let _=D===3||D===0?E:0,Y=D%2==1;lt(w,Y?"left":"top",T-_),lt(w,Y?"width":"height",E),lt(w,Y?"top":"left",Y?ht:$e),lt(w,Y?"height":"width",Y?ne:pe),Ph(w,ts)}else Yr(w,ts)}),Wa=vs=ju=Gu=Xu=Zu=Ku=qu=Yu=null,zr=1,To(!0),$e!=J||ht!=G||pe!=le||ne!=ye){ws(!1);let w=pe/le,C=ne/ye;if(ve&&!Tt&&Z.left>=0){Z.left*=w,Z.top*=C,Cs&&$n(Cs,Lt(Z.left),0,pe,ne),xs&&$n(xs,0,Lt(Z.top),pe,ne);for(let E=0;E<fr.length;E++){let T=fr[E];T!=null&&(zn[E]*=w,Dn[E]*=C,$n(T,ln(zn[E]),ln(Dn[E]),pe,ne))}}if(st.show&&!ft&&st.left>=0&&st.width>0){st.left*=w,st.width*=w,st.top*=C,st.height*=C;for(let E in ac)lt(ks,E,st[E])}J=$e,G=ht,le=pe,ye=ne}qt("setSize"),we=!1}xe>0&&Re>0&&(d.clearRect(0,0,c.width,c.height),qt("drawClear"),U.forEach(w=>w()),qt("draw")),st.show&&ft&&(Ya(st),ft=!1),ve&&Tt&&(Yi(null,!0,!1),Tt=!1),Q.show&&Q.live&&We&&(sc(),We=!1),l||(l=!0,n.status=1,qt("ready")),Io=!1,ja=!1}n.redraw=(w,C)=>{Be=C||!1,w!==!1?di(S,R.min,R.max):bs()};function rc(w,C){let E=b[w];if(E.from==null){if(nr==0){let T=E.range(n,C.min,C.max,w);C.min=T[0],C.max=T[1]}if(C.min>C.max){let T=C.min;C.min=C.max,C.max=T}if(nr>1&&C.min!=null&&C.max!=null&&C.max-C.min<1e-16)return;w==S&&E.distr==2&&nr>0&&(C.min=kn(C.min,e[0]),C.max=kn(C.max,e[0]),C.min==C.max&&C.max++),N[w]=C,Ne=!0,bs()}}n.setScale=rc;let nc,ic,Cs,xs,Ip,kp,Ss,Is,Ep,Mp,it,pt,ci=!1;const ir=Z.drag;let Zt=ir.x,Kt=ir.y;ve&&(Z.x&&(nc=an(DM,p)),Z.y&&(ic=an(OM,p)),R.ori==0?(Cs=nc,xs=ic):(Cs=ic,xs=nc),it=Z.left,pt=Z.top);const st=n.select=Pt({show:!0,over:!0,left:0,width:0,top:0,height:0},r.select),ks=st.show?an(zM,st.over?p:f):null;function Ya(w,C){if(st.show){for(let E in w)st[E]=w[E],E in ac&<(ks,E,w[E]);C!==!1&&qt("setSelect")}}n.setSelect=Ya;function _C(w){if(m[w].show)se&&Ph(Se[w],ts);else if(se&&Yr(Se[w],ts),ve){let E=Pn?fr[0]:fr[w];E!=null&&$n(E,-10,-10,pe,ne)}}function di(w,C,E){rc(w,{min:C,max:E})}function On(w,C,E,T){C.focus!=null&&VC(w),C.show!=null&&m.forEach((D,_)=>{_>0&&(w==_||w==null)&&(D.show=C.show,_C(_),i==2?(di(D.facets[0].scale,null,null),di(D.facets[1].scale,null,null)):di(D.scale,null,null),bs())}),E!==!1&&qt("setSeries",w,C),T&&Uo("setSeries",n,w,C)}n.setSeries=On;function $C(w,C){Pt(I[w],C)}function NC(w,C){w.fill=Pe(w.fill||null),w.dir=_e(w.dir,-1),C=C??I.length,I.splice(C,0,w)}function WC(w){w==null?I.length=0:I.splice(w,1)}n.addBand=NC,n.setBand=$C,n.delBand=WC;function HC(w,C){m[w].alpha=C,ve&&fr[w]!=null&&(fr[w].style.opacity=C),se&&Se[w]&&(Se[w].style.opacity=C)}let Gn,hi,ji;const Es={focus:!0};function VC(w){if(w!=ji){let C=w==null,E=hr.alpha!=1;m.forEach((T,D)=>{if(i==1||D>0){let _=C||D==0||D==w;T._focus=C?null:_,E&&HC(D,_?1:hr.alpha)}}),ji=w,E&&bs()}}se&&Rn&&nt(Mm,be,w=>{Z._lock||(Pr(w),ji!=null&&On(null,Es,!0,Rt.setSeries))});function Bn(w,C,E){let T=b[C];E&&(w=w/Ve-(T.ori==1?ht:$e));let D=pe;T.ori==1&&(D=ne,w=D-w),T.dir==-1&&(w=D-w);let _=T._min,Y=T._max,q=w/D,re=_+(Y-_)*q,ae=T.distr;return ae==3?uo(10,re):ae==4?QM(re,T.asinh):ae==100?T.bwd(re):re}function jC(w,C){let E=Bn(w,S,C);return kn(E,e[0],Gt,Xt)}n.valToIdx=w=>kn(w,e[0]),n.posToIdx=jC,n.posToVal=Bn,n.valToPos=(w,C,E)=>b[C].ori==0?s(w,b[C],E?Ee:pe,E?de:0):o(w,b[C],E?Me:ne,E?Te:0),n.setCursor=(w,C,E)=>{it=w.left,pt=w.top,Yi(null,C,E)};function Tp(w,C){lt(ks,Rs,st.left=w),lt(ks,qo,st.width=C)}function Up(w,C){lt(ks,No,st.top=w),lt(ks,Qo,st.height=C)}let Eo=R.ori==0?Tp:Up,Mo=R.ori==1?Tp:Up;function YC(){if(se&&Q.live)for(let w=i==2?1:0;w<m.length;w++){if(w==0&&qe)continue;let C=Q.values[w],E=0;for(let T in C)et[w][E++].firstChild.nodeValue=C[T]}}function sc(w,C){if(w!=null&&(w.idxs?w.idxs.forEach((E,T)=>{te[T]=E}):rT(w.idx)||te.fill(w.idx),Q.idx=te[0]),se&&Q.live){for(let E=0;E<m.length;E++)(E>0||i==1&&!qe)&&GC(E,te[E]);YC()}We=!1,C!==!1&&qt("setLegend")}n.setLegend=sc;function GC(w,C){let E=m[w],T=w==0&&B==2?mn:e[w],D;qe?D=E.values(n,w,C)??Mt:(D=E.value(n,C==null?null:T[C],w,C),D=D==null?Mt:{_:D}),Q.values[w]=D}function Yi(w,C,E){Ep=it,Mp=pt,[it,pt]=Z.move(n,it,pt),Z.left=it,Z.top=pt,ve&&(Cs&&$n(Cs,Lt(it),0,pe,ne),xs&&$n(xs,0,Lt(pt),pe,ne));let T,D=Gt>Xt;Gn=Qe,hi=null;let _=R.ori==0?pe:ne,Y=R.ori==1?pe:ne;if(it<0||nr==0||D){T=Z.idx=null;for(let q=0;q<m.length;q++){let re=fr[q];re!=null&&$n(re,-10,-10,pe,ne)}Rn&&On(null,Es,!0,w==null&&Rt.setSeries),Q.live&&(te.fill(T),We=!0)}else{let q,re,ae;i==1&&(q=R.ori==0?it:pt,re=Bn(q,S),T=Z.idx=kn(re,e[0],Gt,Xt),ae=A(e[0][T],R,_,0));let ue=-10,he=-10,Ie=0,He=0,Le=!0,Ue="",Ce="";for(let me=i==2?1:0;me<m.length;me++){let ot=m[me],St=te[me],Qt=St==null?null:i==1?e[me][St]:e[me][1][St],Ke=Z.dataIdx(n,me,T,re),It=Ke==null?null:i==1?e[me][Ke]:e[me][1][Ke];if(We=We||It!=Qt||Ke!=St,te[me]=Ke,me>0&&ot.show){let Wr=Ke==null?-10:Ke==T?ae:A(i==1?e[0][Ke]:e[me][0][Ke],R,_,0),Cr=It==null?-10:V(It,i==1?b[ot.scale]:b[ot.facets[1].scale],Y,0);if(Rn&&It!=null){let nn=R.ori==1?it:pt,yn=Wt(hr.dist(n,me,Ke,Cr,nn));if(yn<Gn){let Fn=hr.bias;if(Fn!=0){let Hr=Bn(nn,ot.scale),sn=It>=0?1:-1,vn=Hr>=0?1:-1;vn==sn&&(vn==1?Fn==1?It>=Hr:It<=Hr:Fn==1?It<=Hr:It>=Hr)&&(Gn=yn,hi=me)}else Gn=yn,hi=me}}if(We||Pn){let nn,yn;R.ori==0?(nn=Wr,yn=Cr):(nn=Cr,yn=Wr);let Fn,Hr,sn,vn,Ln,xr,Vr=!0,Gi=yt.bbox;if(Gi!=null){Vr=!1;let Sr=Gi(n,me);sn=Sr.left,vn=Sr.top,Fn=Sr.width,Hr=Sr.height}else sn=nn,vn=yn,Fn=Hr=yt.size(n,me);if(xr=yt.fill(n,me),Ln=yt.stroke(n,me),Pn)me==hi&&Gn<=hr.prox&&(ue=sn,he=vn,Ie=Fn,He=Hr,Le=Vr,Ue=xr,Ce=Ln);else{let Sr=fr[me];Sr!=null&&(zn[me]=sn,Dn[me]=vn,Dm(Sr,Fn,Hr,Vr),Pm(Sr,xr,Ln),$n(Sr,ln(sn),ln(vn),pe,ne))}}}}if(Pn){let me=hr.prox,ot=ji==null?Gn<=me:Gn>me||hi!=ji;if(We||ot){let St=fr[0];St!=null&&(zn[0]=ue,Dn[0]=he,Dm(St,Ie,He,Le),Pm(St,Ue,Ce),$n(St,ln(ue),ln(he),pe,ne))}}}if(st.show&&ci)if(w!=null){let[q,re]=Rt.scales,[ae,ue]=Rt.match,[he,Ie]=w.cursor.sync.scales,He=w.cursor.drag;if(Zt=He._x,Kt=He._y,Zt||Kt){let{left:Le,top:Ue,width:Ce,height:me}=w.select,ot=w.scales[he].ori,St=w.posToVal,Qt,Ke,It,Wr,Cr,nn=q!=null&&ae(q,he),yn=re!=null&&ue(re,Ie);nn&&Zt?(ot==0?(Qt=Le,Ke=Ce):(Qt=Ue,Ke=me),It=b[q],Wr=A(St(Qt,he),It,_,0),Cr=A(St(Qt+Ke,he),It,_,0),Eo(Mn(Wr,Cr),Wt(Cr-Wr))):Eo(0,_),yn&&Kt?(ot==1?(Qt=Le,Ke=Ce):(Qt=Ue,Ke=me),It=b[re],Wr=V(St(Qt,Ie),It,Y,0),Cr=V(St(Qt+Ke,Ie),It,Y,0),Mo(Mn(Wr,Cr),Wt(Cr-Wr))):Mo(0,Y)}else lc()}else{let q=Wt(Ep-Ip),re=Wt(Mp-kp);if(R.ori==1){let Ie=q;q=re,re=Ie}Zt=ir.x&&q>=ir.dist,Kt=ir.y&&re>=ir.dist;let ae=ir.uni;ae!=null?Zt&&Kt&&(Zt=q>=ae,Kt=re>=ae,!Zt&&!Kt&&(re>q?Kt=!0:Zt=!0)):ir.x&&ir.y&&(Zt||Kt)&&(Zt=Kt=!0);let ue,he;Zt&&(R.ori==0?(ue=Ss,he=it):(ue=Is,he=pt),Eo(Mn(ue,he),Wt(he-ue)),Kt||Mo(0,Y)),Kt&&(R.ori==1?(ue=Ss,he=it):(ue=Is,he=pt),Mo(Mn(ue,he),Wt(he-ue)),Zt||Eo(0,_)),!Zt&&!Kt&&(Eo(0,0),Mo(0,0))}if(ir._x=Zt,ir._y=Kt,w==null){if(E){if($p!=null){let[q,re]=Rt.scales;Rt.values[0]=q!=null?Bn(R.ori==0?it:pt,q):null,Rt.values[1]=re!=null?Bn(R.ori==1?it:pt,re):null}Uo(td,n,it,pt,pe,ne,T)}if(Rn){let q=E&&Rt.setSeries,re=hr.prox;ji==null?Gn<=re&&On(hi,Es,!0,q):Gn>re?On(null,Es,!0,q):hi!=ji&&On(hi,Es,!0,q)}}We&&(Q.idx=T,sc()),C!==!1&&qt("setCursor")}let fi=null;Object.defineProperty(n,"rect",{get(){return fi==null&&To(!1),fi}});function To(w=!1){w?fi=null:(fi=p.getBoundingClientRect(),qt("syncRect",fi))}function Ap(w,C,E,T,D,_,Y){Z._lock||ci&&w!=null&&w.movementX==0&&w.movementY==0||(oc(w,C,E,T,D,_,Y,!1,w!=null),w!=null?Yi(null,!0,!0):Yi(C,!0,!1))}function oc(w,C,E,T,D,_,Y,q,re){if(fi==null&&To(!1),Pr(w),w!=null)E=w.clientX-fi.left,T=w.clientY-fi.top;else{if(E<0||T<0){it=-10,pt=-10;return}let[ae,ue]=Rt.scales,he=C.cursor.sync,[Ie,He]=he.values,[Le,Ue]=he.scales,[Ce,me]=Rt.match,ot=C.axes[0].side%2==1,St=R.ori==0?pe:ne,Qt=R.ori==1?pe:ne,Ke=ot?_:D,It=ot?D:_,Wr=ot?T:E,Cr=ot?E:T;if(Le!=null?E=Ce(ae,Le)?a(Ie,b[ae],St,0):-10:E=St*(Wr/Ke),Ue!=null?T=me(ue,Ue)?a(He,b[ue],Qt,0):-10:T=Qt*(Cr/It),R.ori==1){let nn=E;E=T,T=nn}}re&&(C==null||C.cursor.event.type==td)&&((E<=1||E>=pe-1)&&(E=Ji(E,pe)),(T<=1||T>=ne-1)&&(T=Ji(T,ne))),q?(Ip=E,kp=T,[Ss,Is]=Z.move(n,E,T)):(it=E,pt=T)}const ac={width:0,height:0,left:0,top:0};function lc(){Ya(ac,!1)}let Rp,Pp,zp,Dp;function Op(w,C,E,T,D,_,Y){ci=!0,Zt=Kt=ir._x=ir._y=!1,oc(w,C,E,T,D,_,Y,!0,!1),w!=null&&(nt(rd,Ah,Bp,!1),Uo(km,n,Ss,Is,pe,ne,null));let{left:q,top:re,width:ae,height:ue}=st;Rp=q,Pp=re,zp=ae,Dp=ue}function Bp(w,C,E,T,D,_,Y){ci=ir._x=ir._y=!1,oc(w,C,E,T,D,_,Y,!1,!0);let{left:q,top:re,width:ae,height:ue}=st,he=ae>0||ue>0,Ie=Rp!=q||Pp!=re||zp!=ae||Dp!=ue;if(he&&Ie&&Ya(st),ir.setScale&&he&&Ie){let He=q,Le=ae,Ue=re,Ce=ue;if(R.ori==1&&(He=re,Le=ue,Ue=q,Ce=ae),Zt&&di(S,Bn(He,S),Bn(He+Le,S)),Kt)for(let me in b){let ot=b[me];me!=S&&ot.from==null&&ot.min!=Qe&&di(me,Bn(Ue+Ce,me),Bn(Ue,me))}lc()}else Z.lock&&(Z._lock=!Z._lock,Yi(C,!0,w!=null));w!=null&&(br(rd,Ah),Uo(rd,n,it,pt,pe,ne,null))}function XC(w,C,E,T,D,_,Y){if(Z._lock)return;Pr(w);let q=ci;if(ci){let re=!0,ae=!0,ue=10,he,Ie;R.ori==0?(he=Zt,Ie=Kt):(he=Kt,Ie=Zt),he&&Ie&&(re=it<=ue||it>=pe-ue,ae=pt<=ue||pt>=ne-ue),he&&re&&(it=it<Ss?0:pe),Ie&&ae&&(pt=pt<Is?0:ne),Yi(null,!0,!0),ci=!1}it=-10,pt=-10,te.fill(null),Yi(null,!0,!0),q&&(ci=q)}function Fp(w,C,E,T,D,_,Y){Z._lock||(Pr(w),Vu(),lc(),w!=null&&Uo(Tm,n,it,pt,pe,ne,null))}function Lp(){v.forEach(v5),Yt(n.width,n.height,!0)}as(fu,eo,Lp);const Ms={};Ms.mousedown=Op,Ms.mousemove=Ap,Ms.mouseup=Bp,Ms.dblclick=Fp,Ms.setSeries=(w,C,E,T)=>{let D=Rt.match[2];E=D(n,C,E),E!=-1&&On(E,T,!0,!1)},ve&&(nt(km,p,Op),nt(td,p,Ap),nt(Em,p,w=>{Pr(w),To(!1)}),nt(Mm,p,XC),nt(Tm,p,Fp),Lh.add(n),n.syncRect=To);const Ga=n.hooks=r.hooks||{};function qt(w,C,E){tc?ko.push([w,C,E]):w in Ga&&Ga[w].forEach(T=>{T.call(null,n,C,E)})}(r.plugins||[]).forEach(w=>{for(let C in w.hooks)Ga[C]=(Ga[C]||[]).concat(w.hooks[C])});const _p=(w,C,E)=>E,Rt=Pt({key:null,setSeries:!1,filters:{pub:_m,sub:_m},scales:[S,m[1]?m[1].scale:null],match:[$m,$m,_p],values:[null,null]},Z.sync);Rt.match.length==2&&Rt.match.push(_p),Z.sync=Rt;const $p=Rt.key,uc=hC($p);function Uo(w,C,E,T,D,_,Y){Rt.filters.pub(w,C,E,T,D,_,Y)&&uc.pub(w,C,E,T,D,_,Y)}uc.sub(n);function ZC(w,C,E,T,D,_,Y){Rt.filters.sub(w,C,E,T,D,_,Y)&&Ms[w](null,C,E,T,D,_,Y)}n.pub=ZC;function KC(){uc.unsub(n),Lh.delete(n),xt.clear(),zh(fu,eo,Lp),u.remove(),be==null||be.remove(),qt("destroy")}n.destroy=KC;function cc(){qt("init",r,e),mp(e||r.data,!1),N[S]?rc(S,N[S]):Vu(),ft=st.show&&(st.width>0||st.height>0),Tt=We=!0,Yt(r.width,r.height)}return m.forEach(At),v.forEach(TC),t?t instanceof HTMLElement?(t.appendChild(u),cc()):t(n,cc):cc(),n}yr.assign=Pt;yr.fmtNum=ip;yr.rangeNum=pu;yr.rangeLog=Fu;yr.rangeAsinh=rp;yr.orient=ms;yr.pxRatio=Ve;yr.join=uT;yr.fmtDate=op,yr.tzDate=bT;yr.sync=hC;{yr.addGap=r5,yr.clipGaps=$u;let r=yr.paths={points:vC};r.linear=bC,r.stepped=s5,r.bars=o5,r.spline=l5}function w5(r,e){const t=/^#([0-9a-fA-F]{6})([0-9a-fA-F]{2})?$/.exec(r.trim());return t?`#${t[1]}${e}`:r}function IC({data:r,seriesKeys:e,seriesLabels:t,colors:n,height:i=300,tickRate:s=60,windowSeconds:o=20,hoveredKey:a=null,onHoverKey:l}){const u=$.useRef(null),c=$.useRef(null),d=$.useRef(null),h=$.useMemo(()=>e.join("|"),[e]),f=$.useMemo(()=>{const y=Math.max(1,Math.round(o*s)),m=Math.max(0,r.length-y),v=r.slice(m),b=Math.max(0,y-v.length),I=new Array(y);for(let M=0;M<y;M++)I[M]=M;const S=e.map(()=>new Array(y).fill(0));for(let M=0;M<v.length;M++){const U=v[M],z=b+M;for(let O=0;O<e.length;O++){const R=e[O],B=Number(U[R]??0);S[O][z]=Number.isFinite(B)?B:0}}return{x:I,series:S,windowPoints:y}},[r,e,s,o]),p=$.useMemo(()=>[f.x,...f.series],[f]),g=$.useMemo(()=>{const y=typeof globalThis.devicePixelRatio=="number"?globalThis.devicePixelRatio:1,m=[{label:"t"},...e.map((v,b)=>{const I=n[b%n.length]??"#4fc1ff";return{label:t[v]??v,stroke:I,width:2,points:{show:!1}}})];return{width:800,height:i,pxAlign:0,pxRatio:y,padding:[10,10,10,10],scales:{x:{time:!1},y:{}},axes:[{stroke:"#555",grid:{stroke:"#222",width:1},size:0,values:(v,b)=>b.map(()=>"")},{stroke:"#555",grid:{stroke:"#222",width:1}}],series:m,legend:{show:!1},cursor:{drag:{x:!1,y:!1}},hooks:{setCursor:[v=>{var O;if(!l)return;const b=v.cursor.idx;if(b==null||b<0){d.current!==null&&(d.current=null,l(null));return}const I=v.cursor.top;if(I==null||!Number.isFinite(I)){d.current!==null&&(d.current=null,l(null));return}let S=null,M=Number.POSITIVE_INFINITY;for(let R=1;R<v.series.length;R++){const B=e[R-1],A=(O=v.data[R])==null?void 0:O[b];if(A==null||!Number.isFinite(A))continue;const V=v.valToPos(A,"y",!0),N=Math.abs(V-I);N<M&&(M=N,S=B)}const z=M<=12?S:null;d.current!==z&&(d.current=z,l(z))}]}}},[n,i,l,e,t]),x=$.useMemo(()=>e.map((y,m)=>{const v=n[m%n.length]??"#4fc1ff",b=a!=null&&a===y;return{stroke:a!=null&&a!==y?w5(v,"66"):v,width:b?3:2}}),[n,a,e]);return $.useEffect(()=>{var S;const y=u.current;if(!y)return;const m=()=>{l&&d.current!==null&&(d.current=null,l(null))};y.addEventListener("mouseleave",m),(S=c.current)==null||S.destroy(),c.current=null;const v=new yr(g,p,y);c.current=v;const b=new ResizeObserver(()=>{const M=y.getBoundingClientRect();v.setSize({width:Math.max(1,Math.floor(M.width)),height:i})});b.observe(y);const I=y.getBoundingClientRect();return v.setSize({width:Math.max(1,Math.floor(I.width)),height:i}),()=>{y.removeEventListener("mouseleave",m),b.disconnect(),v.destroy(),c.current=null}},[g,p,i,l,h]),$.useEffect(()=>{var y;(y=c.current)==null||y.setData(p)},[p]),$.useEffect(()=>{const y=c.current;if(y)for(let m=0;m<x.length;m++){const v=m+1,b=x[m],I=y.series[v];!I||!b||(I.stroke!==b.stroke||I.width!==b.width)&&y.setSeries(v,{stroke:b.stroke,width:b.width})}},[x]),k.jsx("div",{ref:u,style:{width:"100%",height:i}})}const Dr=(r,e)=>r===e?0:r<e?-1:1,ly=(r,e)=>r.localeCompare(e,void 0,{numeric:!0}),yl=r=>(r??"").trim();function b5({sortedTraffic:r,topTraffic:e,chartData:t,topKeys:n,keyToLabel:i,keyToColor:s,tickRate:o,hoveredTrafficKey:a,setHoveredTrafficKey:l}){const[u,c]=$.useState("bps"),[d,h]=$.useState("desc"),[f,p]=$.useState("bps"),[g,x]=$.useState("desc"),[y,m]=$.useState("bps"),[v,b]=$.useState("desc"),I=P=>{if(P===u){h(W=>W==="asc"?"desc":"asc");return}c(P),h(P==="name"?"asc":"desc")},S=P=>{if(P===y){b(W=>W==="asc"?"desc":"asc");return}m(P),b(P==="name"?"asc":"desc")},M=P=>{if(P===f){x(W=>W==="asc"?"desc":"asc");return}p(P),x(P==="name"?"asc":"desc")},U=(P,W,j)=>{const X=j==="asc"?1:-1,te=[...P];return te.sort((Q,Z)=>{let se=0;switch(W){case"id":se=Dr(Q.id,Z.id);break;case"name":{const ve=yl(Q.name),ge=yl(Z.name);se=ly(ve,ge),se===0&&(se=Dr(Q.id,Z.id));break}case"encoding":{const ve=yl(Q.encoding),ge=yl(Z.encoding);se=ly(ve,ge),se===0&&(se=Dr(Q.id,Z.id));break}case"bps":se=Dr(Q.bps,Z.bps),se===0&&(se=Dr(Q.total,Z.total));break;case"total":se=Dr(Q.total,Z.total),se===0&&(se=Dr(Q.bps,Z.bps));break;case"size":{const ve=Q.size.x*Q.size.y,ge=Z.size.x*Z.size.y;se=Dr(ve,ge),se===0&&(se=Dr(Q.id,Z.id));break}case"position":{se=Dr(Q.position.x,Z.position.x),se===0&&(se=Dr(Q.position.y,Z.position.y)),se===0&&(se=Dr(Q.id,Z.id));break}case"zIndex":se=Dr(Q.zIndex,Z.zIndex),se===0&&(se=Dr(Q.id,Z.id));break}return se*X}),te},z=$.useMemo(()=>r.filter(P=>P.key.startsWith("layer-")),[r]),O=$.useMemo(()=>r.filter(P=>P.key.startsWith("misc-")),[r]),R=$.useMemo(()=>r.filter(P=>P.key.startsWith("display-")),[r]),B=$.useMemo(()=>U(z,u,d),[z,d,u]),A=$.useMemo(()=>U(O,y,v),[O,v,y]),V=$.useMemo(()=>U(R,f,g),[R,g,f]),N={userSelect:"none",cursor:"pointer"},H=(P,W,j)=>P!==W?"":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"}),z.length===0&&O.length===0&&k.jsx("div",{style:{color:"#888",fontSize:12},children:"No bandwidth data yet. Move the client or send data to see traffic."}),z.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(IC,{data:t,seriesKeys:n,seriesLabels:i,colors:n.map(P=>s[P]??"#4fc1ff"),height:260,tickRate:o,windowSeconds:60,hoveredKey:a,onHoverKey:l})]}),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:"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:N,onClick:()=>I("id"),title:"Sort by ID",children:["ID",H("id",u,d)]}),k.jsxs("div",{style:N,onClick:()=>I("name"),title:"Sort by name",children:["Name",H("name",u,d)]}),k.jsxs("div",{style:N,onClick:()=>I("encoding"),title:"Sort by encoding",children:["Encoding",H("encoding",u,d)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>I("bps"),title:"Sort by Network/s",children:["Network/s",H("bps",u,d)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>I("total"),title:"Sort by Network",children:["Network",H("total",u,d)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>I("size"),title:"Sort by size",children:["Size",H("size",u,d)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>I("position"),title:"Sort by position",children:["Position",H("position",u,d)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>I("zIndex"),title:"Sort by zIndex",children:["zIndex",H("zIndex",u,d)]})]}),B.map(P=>k.jsxs("div",{onMouseEnter:()=>l(P.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===P.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===P.key?"#1a1a1a":"transparent",outline:a===P.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:P.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[P.key]??"#666",boxShadow:a===P.key?`0 0 0 1px #000, 0 0 0 2px ${s[P.key]??"#666"}`:"0 0 0 1px #000"}}),(()=>{var j;const W=((j=P.name)==null?void 0:j.trim())||`Layer ${P.id}`;return P.id===255?`${W} (debug)`:W})()]}),k.jsx("div",{style:{color:"#bbb"},children:P.encoding??""}),k.jsxs("div",{style:{textAlign:"right"},children:[Xr(P.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Xr(P.total)}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[P.size.x,"×",P.size.y]}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[P.position.x,"/",P.position.y]}),k.jsx("div",{style:{textAlign:"right",color:"#999"},children:P.zIndex})]},P.key))]}),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:"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:N,onClick:()=>M("id"),title:"Sort by ID",children:["ID",H("id",f,g)]}),k.jsxs("div",{style:N,onClick:()=>M("name"),title:"Sort by name",children:["Name",H("name",f,g)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>M("bps"),title:"Sort by Network/s",children:["Network/s",H("bps",f,g)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>M("total"),title:"Sort by Network",children:["Network",H("total",f,g)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>M("size"),title:"Sort by size",children:["Size",H("size",f,g)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>M("position"),title:"Sort by position",children:["Position",H("position",f,g)]}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"zIndex"})]}),V.map(P=>{var W;return k.jsxs("div",{onMouseEnter:()=>l(P.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===P.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===P.key?"#1a1a1a":"transparent",outline:a===P.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:P.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[P.key]??"#666",boxShadow:a===P.key?`0 0 0 1px #000, 0 0 0 2px ${s[P.key]??"#666"}`:"0 0 0 1px #000"}}),((W=P.name)==null?void 0:W.trim())||`Display ${P.id}`]}),k.jsxs("div",{style:{textAlign:"right"},children:[Xr(P.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Xr(P.total)}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[P.size.x,"×",P.size.y]}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[P.position.x,"/",P.position.y]}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"})]},P.key)})]}),O.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:N,onClick:()=>S("id"),title:"Sort by ID",children:["ID",H("id",y,v)]}),k.jsxs("div",{style:N,onClick:()=>S("name"),title:"Sort by name",children:["Name",H("name",y,v)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>S("bps"),title:"Sort by Network/s",children:["Network/s",H("bps",y,v)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>S("total"),title:"Sort by Network",children:["Network",H("total",y,v)]}),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"})]}),A.map(P=>k.jsxs("div",{onMouseEnter:()=>l(P.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===P.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===P.key?"#1a1a1a":"transparent",outline:a===P.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:P.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[P.key]??"#666",boxShadow:a===P.key?`0 0 0 1px #000, 0 0 0 2px ${s[P.key]??"#666"}`:"0 0 0 1px #000"}}),P.name??"—"]}),k.jsxs("div",{style:{textAlign:"right"},children:[Xr(P.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Xr(P.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:"—"})]},P.key))]})]})}const Jt=65536,ad=.005,ld=32;function C5({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=$.useRef(null),[p,g]=$.useState(1),[x,y]=$.useState({x:0,y:0}),m=$.useRef(!1),v=$.useRef({x:0,y:0}),b=$.useRef(""),[I,S]=$.useState(!1),[M,U]=$.useState(null),[z,O]=$.useState(null),[R,B]=$.useState("none"),[A,V]=$.useState(null),N=$.useRef(null),[H,P]=$.useState(!1),W=$.useRef(!1),j=$.useRef(!1),X=$.useCallback((J,G,le)=>{const ye=t/le,de=n/le,Te=ye*.5,Ee=de*.5,Me=Math.max(0,Jt-ye)+Te,Ne=Math.max(0,Jt-de)+Ee,we=-Te,Be=-Ee;return{x:Math.max(we,Math.min(Me,J)),y:Math.max(Be,Math.min(Ne,G))}},[t,n]),te=$.useCallback(()=>{const J=Jt*p,G=Jt*p,le=J<t?(t-J)/2:0,ye=G<n?(n-G)/2:0;return{toScreenX:Ne=>(Ne-x.x)*p+le,toScreenY:Ne=>(Ne-x.y)*p+ye,toWorldX:Ne=>(Ne-le)/p+x.x,toWorldY:Ne=>(Ne-ye)/p+x.y}},[n,x.x,x.y,p,t]),Q=$.useCallback((J,G)=>{let le=null;for(let ye=0;ye<r.length;ye++){const de=r[ye];if(J<de.x||J>de.x+de.width||G<de.y||G>de.y+de.height)continue;const Te=de.zIndex??0;(!le||Te>le.z)&&(le={id:de.id,z:Te})}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(J>=de.x&&J<=de.x+de.width&&G>=de.y&&G<=de.y+de.height)return{kind:"display",id:de.id}}return null},[e,r]),Z=$.useCallback((J,G)=>{const le=[];for(let ye=0;ye<r.length;ye++){const de=r[ye];J<de.x||J>de.x+de.width||G<de.y||G>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]);$.useEffect(()=>{const J=f.current;if(!J)return;const G=J.getContext("2d");if(!G)return;G.clearRect(0,0,t,n),G.fillStyle="#0a0e14",G.fillRect(0,0,t,n);const le=Jt*p,ye=Jt*p,de=le<t?(t-le)/2:0,Te=ye<n?(n-ye)/2:0,Ee=we=>(we-x.x)*p+de,Me=we=>(we-x.y)*p+Te;{const we=Ee(0),Be=Ee(Jt),Tt=Me(0),ft=Me(Jt),We=Math.max(0,we),Yt=Math.min(t,Be),Bt=Math.max(0,Tt),li=Math.min(n,ft);if(!(Yt<=We||li<=Bt)){const $i=[{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}];G.save(),G.beginPath(),G.rect(We,Bt,Yt-We,li-Bt),G.clip();let Ni=!1;for(const Fe of $i){if(Fe.step*p<Fe.minGapPx)continue;Ni=!0,G.strokeStyle=`rgba(255,255,255,${Fe.alpha})`,G.lineWidth=Fe.lineWidth;const Pr=vt=>(vt-de)/p+x.x,yt=vt=>(vt-Te)/p+x.y,hr=Math.max(0,Pr(0)),Rn=Math.min(Jt,Pr(t)),Pn=Math.max(0,yt(0)),fr=Math.min(Jt,yt(n)),zn=Math.floor(hr/Fe.step)*Fe.step,Dn=Math.ceil(Rn/Fe.step)*Fe.step,ys=Math.floor(Pn/Fe.step)*Fe.step,At=Math.ceil(fr/Fe.step)*Fe.step;G.beginPath();for(let vt=zn;vt<=Dn;vt+=Fe.step){if(vt<0||vt>Jt)continue;const Hi=Ee(vt);G.moveTo(Hi,Bt),G.lineTo(Hi,li)}for(let vt=ys;vt<=At;vt+=Fe.step){if(vt<0||vt>Jt)continue;const Hi=Me(vt);G.moveTo(We,Hi),G.lineTo(Yt,Hi)}G.stroke()}if(!Ni){const Fe=$i[$i.length-1];G.strokeStyle=`rgba(255,255,255,${Fe.alpha})`,G.lineWidth=Fe.lineWidth;const Wi=At=>(At-de)/p+x.x,Pr=At=>(At-Te)/p+x.y,yt=Math.max(0,Wi(0)),hr=Math.min(Jt,Wi(t)),Rn=Math.max(0,Pr(0)),Pn=Math.min(Jt,Pr(n)),fr=Math.floor(yt/Fe.step)*Fe.step,zn=Math.ceil(hr/Fe.step)*Fe.step,Dn=Math.floor(Rn/Fe.step)*Fe.step,ys=Math.ceil(Pn/Fe.step)*Fe.step;G.beginPath();for(let At=fr;At<=zn;At+=Fe.step){if(At<0||At>Jt)continue;const vt=Ee(At);G.moveTo(vt,Bt),G.lineTo(vt,li)}for(let At=Dn;At<=ys;At+=Fe.step){if(At<0||At>Jt)continue;const vt=Me(At);G.moveTo(We,vt),G.lineTo(Yt,vt)}G.stroke()}G.restore()}}const Ne=[...r].sort((we,Be)=>(we.zIndex??0)-(Be.zIndex??0));for(const we of Ne){const Be=s!=null&&s.includes(we.id),Tt=i!=null&&we.id===i,ft=Ee(we.x),We=Me(we.y),Yt=we.width*p,Bt=we.height*p;if(ft+Yt<0||We+Bt<0||ft>t||We>n)continue;const li=we.zIndex??0,$i=we.color??(Be?"rgba(43, 140, 255, 0.60)":Tt?"rgba(102, 217, 239, 0.40)":"rgba(43, 140, 255, 0.42)");if(G.fillStyle=$i,G.fillRect(ft,We,Math.max(Yt,1),Math.max(Bt,1)),G.strokeStyle=Be?"#66d9ef":Tt?"rgba(102, 217, 239, 0.70)":"rgba(255,255,255,0.30)",G.lineWidth=Be?2:1,G.strokeRect(ft,We,Math.max(Yt,1),Math.max(Bt,1)),p>=3&&Yt>=40&&Bt>=16){G.font="11px monospace",G.textBaseline="top";const Ni=`z=${li}`,Fe=4,Wi=3,yt=G.measureText(Ni).width+Fe*2,hr=14;G.fillStyle="rgba(0,0,0,0.55)",G.fillRect(ft+3,We+3,yt,hr),G.fillStyle="rgba(255,255,255,0.85)",G.fillText(Ni,ft+3+Fe,We+3+Wi)}}for(const we of e){const Be=a!=null&&we.id===a,Tt=o!=null&&we.id===o,ft=Ee(we.x),We=Me(we.y),Yt=we.width*p,Bt=we.height*p;ft+Yt<0||We+Bt<0||ft>t||We>n||(G.strokeStyle=Be?"rgba(255, 120, 120, 1)":Tt?"rgba(255, 120, 120, 0.8)":"rgba(255, 80, 80, 0.9)",G.lineWidth=Be?3:2,G.strokeRect(ft,We,Math.max(Yt,1),Math.max(Bt,1)))}if(A){const we=Ee(A.x),Be=Me(A.y),Tt=A.width*p,ft=A.height*p;G.strokeStyle="rgba(43, 140, 255, 1)",G.lineWidth=2,G.setLineDash([6,4]),G.strokeRect(we,Be,Math.max(Tt,1),Math.max(ft,1)),G.setLineDash([])}},[r,e,t,n,p,x,i,s,o,a,A]);const se=$.useCallback((J,G)=>{var we;const le=(we=f.current)==null?void 0:we.getBoundingClientRect();if(!le)return null;const ye=J-le.left,de=G-le.top,{toWorldX:Te,toWorldY:Ee}=te(),Me=Te(ye),Ne=Ee(de);return{x:Me,y:Ne}},[te]),ve=$.useCallback((J,G)=>{const le=Math.floor(Math.min(J.x,G.x)),ye=Math.floor(Math.min(J.y,G.y)),de=Math.ceil(Math.max(J.x,G.x)),Te=Math.ceil(Math.max(J.y,G.y));return{x:le,y:ye,width:Math.max(1,de-le),height:Math.max(1,Te-ye)}},[]);$.useEffect(()=>{if(!l){b.current="";return}const J=`${u}-${l.id}-${l.x}-${l.y}-${l.width}-${l.height}-${t}-${n}`;if(J===b.current)return;if(j.current){j.current=!1,b.current=J;return}b.current=J;const G=1.25,le=Math.max(ad,Math.min(ld,Math.min(t/(l.width*G),n/(l.height*G)))),ye=t/le,de=n/le,Te=l.x+l.width/2,Ee=l.y+l.height/2,Me=X(Te-ye/2,Ee-de/2,le);g(le),y(Me)},[l,u,t,n,X]);const ge=$.useCallback(J=>{var Bt;const G=(Bt=f.current)==null?void 0:Bt.getBoundingClientRect();if(!G)return;J.preventDefault();const le=J.clientX-G.left,ye=J.clientY-G.top,{toWorldX:de,toWorldY:Te}=te(),Ee=de(le),Me=Te(ye),Ne=J.deltaY<0?1.15:1/1.15,we=Math.max(ad,Math.min(ld,p*Ne)),Be=Jt*we,Tt=Jt*we,ft=Be<t?(t-Be)/2:0,We=Tt<n?(n-Tt)/2:0,Yt=X(Ee-(le-ft)/we,Me-(ye-We)/we,we);g(we),y(Yt)},[X,te,n,x,p,t]);$.useEffect(()=>{const J=f.current;if(!J)return;const G=le=>ge(le);return J.addEventListener("wheel",G,{passive:!1}),()=>J.removeEventListener("wheel",G)},[ge]);const be=$.useCallback(J=>{m.current=!0,S(!0),v.current={x:J.clientX,y:J.clientY}},[]),ct=$.useCallback(()=>{m.current=!1,S(!1)},[]),dt=$.useCallback(()=>{m.current=!1,S(!1),U(null)},[]),Se=$.useCallback(J=>{const G=se(J.clientX,J.clientY);if(!G||R!=="rect"||!h)return;J.preventDefault(),J.stopPropagation(),W.current=!0;const le={x:Math.floor(G.x),y:Math.floor(G.y)};N.current={startWorld:le,moved:!1},P(!0),V({x:le.x,y:le.y,width:1,height:1})},[R,se,h]),et=$.useCallback(J=>{if(!N.current)return;const G=se(J.clientX,J.clientY);if(!G)return;const le=ve(N.current.startWorld,G);if(!N.current.moved){const ye=Math.abs(G.x-N.current.startWorld.x),de=Math.abs(G.y-N.current.startWorld.y);(ye>0||de>0)&&(N.current.moved=!0)}V(le)},[se,ve]),Ze=$.useCallback(()=>{!N.current||!A||(W.current=!0,h==null||h(A),j.current=!0,N.current=null,V(null),P(!1),B("none"))},[A,h]),qe=$.useCallback(J=>{if(N.current){if(J.preventDefault(),J.stopPropagation(),!N.current.moved){W.current=!0,N.current=null,V(null),P(!1),B("none");return}Ze()}},[Ze]);$.useEffect(()=>{if(!H)return;const J=le=>{et(le)},G=le=>{qe(le)};return window.addEventListener("mousemove",J,!0),window.addEventListener("mouseup",G,!0),()=>{window.removeEventListener("mousemove",J,!0),window.removeEventListener("mouseup",G,!0)}},[H,et,qe]),$.useEffect(()=>{if(!N.current)return;const J=G=>{G.key==="Enter"&&Ze()};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[Ze]);const Mt=$.useCallback(J=>{var we;if(N.current){et(J);return}if(m.current){const Be=J.clientX-v.current.x,Tt=J.clientY-v.current.y;v.current={x:J.clientX,y:J.clientY},y(ft=>X(ft.x-Be/p,ft.y-Tt/p,p));return}const G=(we=f.current)==null?void 0:we.getBoundingClientRect();if(!G)return;const le=J.clientX-G.left,ye=J.clientY-G.top,{toWorldX:de,toWorldY:Te}=te(),Ee=Math.floor(de(le)),Me=Math.floor(Te(ye)),Ne=Q(Ee,Me);if(!Ne){U({kind:"layer",id:-1,world:{x:Ee,y:Me},screen:{x:le,y:ye}});return}U({kind:Ne.kind,id:Ne.id,world:{x:Ee,y:Me},screen:{x:le,y:ye}})},[X,te,Q,p]),mt=$.useCallback(J=>{var Be;if(W.current){W.current=!1;return}if(R==="rect"||N.current||I)return;const G=(Be=f.current)==null?void 0:Be.getBoundingClientRect();if(!G)return;const le=J.clientX-G.left,ye=J.clientY-G.top,{toWorldX:de,toWorldY:Te}=te(),Ee=Math.floor(de(le)),Me=Math.floor(Te(ye)),Ne=Z(Ee,Me);if(Ne.length>=2){O({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:J.metaKey,ctrlKey:J.ctrlKey})),we.kind==="display"&&(d==null||d(we.id)))},[R,te,Q,Z,I,d,c]);$.useEffect(()=>{const J=G=>{G.key==="Escape"&&O(null)};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[]);const Ot=$.useCallback(()=>{g(1),y(X(0,0,1))},[X]),dr=$.useCallback(J=>{var Be;const G=(Be=f.current)==null?void 0:Be.getBoundingClientRect();if(!G)return;const le=G.width/2,ye=G.height/2,{toWorldX:de,toWorldY:Te}=te(),Ee=de(le),Me=Te(ye),Ne=Math.max(ad,Math.min(ld,p*J)),we=X(Ee-le/Ne,Me-ye/Ne,Ne);g(Ne),y(we)},[X,te,p]),tt=M&&M.id!==-1?M:null,xt=n<520?6:10,nt=Math.max(40,n-xt*2),br=88,xe=42,Re=nt<150,pe=nt<240,ne=nt<200,$e=Math.min(1,Math.max(.7,nt/(Re?64:br))),ht=Math.min(1,Math.max(.7,nt/xe));return k.jsxs("div",{style:{position:"absolute",inset:0},children:[k.jsx("canvas",{ref:f,width:t,height:n,style:{display:"block",cursor:R==="rect"?(N.current,"crosshair"):m.current?"grabbing":"grab"},onMouseDown:J=>{if(R==="rect"&&h){Se(J);return}be(J)},onMouseMove:Mt,onMouseUp:J=>{if(N.current){qe(J);return}ct()},onMouseLeave:dt,onClick:mt}),k.jsxs("div",{style:{position:"absolute",right:xt,bottom:pe?void 0:xt,top:pe?xt: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% - ${xt*2}px)`},onMouseDown:J=>J.stopPropagation(),children:[k.jsx("button",{onClick:()=>{const J=R==="rect"?"none":"rect";N.current=null,P(!1),B(J)},style:{width:34,height:34,borderRadius:8,border:R==="rect"?"1px solid rgba(79, 193, 255, 0.9)":"1px solid rgba(255,255,255,0.18)",background:R==="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:R==="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:()=>{N.current=null,P(!1),B("none")},style:{width:34,height:34,borderRadius:8,border:"1px solid rgba(255,255,255,0.18)",background:R==="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:"↔"})]}),(z==null?void 0:z.open)&&z.layers.length>=2&&k.jsxs("div",{style:{position:"absolute",left:Math.min(t-220,z.anchorScreen.x+12),top:Math.min(n-260,z.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:()=>O(null),style:{...vl,padding:"2px 6px",borderRadius:8},title:"Close",children:"✕"})]}),k.jsxs("div",{style:{color:"#9aa7b2",marginTop:4},children:["World: ",z.world.x.toFixed(0),",",z.world.y.toFixed(0)]}),k.jsx("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:6,maxHeight:220,overflow:"auto",paddingRight:2},children:z.layers.map((J,G)=>{var le;return k.jsx("button",{onClick:ye=>{c==null||c(J.id,{metaKey:ye.metaKey,ctrlKey:ye.ctrlKey}),O(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=J.name)!=null&&le.trim()?J.name:`Layer ${J.id}`," ",k.jsxs("span",{style:{color:"#9aa7b2",fontWeight:500},children:["z=",J.zIndex]}),G===0&&k.jsx("span",{style:{marginLeft:6,color:"#66d9ef",fontWeight:650},children:"top"})]})},J.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:()=>dr(1.15),style:vl,title:"Zoom in",children:"+"}),k.jsx("button",{onClick:()=>dr(1/1.15),style:vl,title:"Zoom out",children:"−"}),k.jsx("button",{onClick:Ot,style:vl,title:"Reset view",children:"Reset"})]}),k.jsxs("div",{style:{position:"absolute",left:xt,bottom:ne?void 0:xt,top:ne?xt: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% - ${xt*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:"})," (",x.x.toFixed(0),","," ",x.y.toFixed(0),")",M&&k.jsxs(k.Fragment,{children:[k.jsx("span",{style:{color:"#9aa7b2"},children:"| Mouse:"})," (",M.world.x.toFixed(0),",",M.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 vl={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 kC={},fp={},pp={},xo={};Object.defineProperty(xo,"__esModule",{value:!0});xo.Direction=void 0;var uy;(function(r){r.Right="to right",r.Left="to left",r.Down="to bottom",r.Up="to top"})(uy||(xo.Direction=uy={}));(function(r){var e=Nr&&Nr.__spreadArray||function(B,A,V){if(V||arguments.length===2)for(var N=0,H=A.length,P;N<H;N++)(P||!(N in A))&&(P||(P=Array.prototype.slice.call(A,0,N)),P[N]=A[N]);return B.concat(P||Array.prototype.slice.call(A))};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=xo,i=function(B){var A=B.toString().split(".")[1];return A?A.length:0};r.getStepDecimals=i;function s(B){return B.touches&&B.touches.length||B.changedTouches&&B.changedTouches.length}r.isTouchEvent=s;function o(B,A,V){var N=(A-B)/V,H=8,P=Number(N.toFixed(H));return parseInt(P.toString(),10)===P}r.isStepDivisible=o;function a(B,A,V,N,H,P,W){var j=1e11;if(B=Math.round(B*j)/j,!P){var X=W[A-1],te=W[A+1];if(X&&X>B)return X;if(te&&te<B)return te}if(B>N)return N;if(B<V)return V;var Q=Math.floor(B*j-V*j)%Math.floor(H*j),Z=Math.floor(B*j-Math.abs(Q)),se=Q===0?B:Z/j,ve=Math.abs(Q/j)<H/2?se:se+H,ge=(0,r.getStepDecimals)(H);return parseFloat(ve.toFixed(ge))}r.normalizeValue=a;function l(B,A,V){return(B-A)/(V-A)}r.relativeValue=l;function u(B){return B===n.Direction.Up||B===n.Direction.Down}r.isVertical=u;function c(B,A,V){if(A>=V)throw new RangeError("min (".concat(A,") is equal/bigger than max (").concat(V,")"));if(B<A)throw new RangeError("value (".concat(B,") is smaller than min (").concat(A,")"));if(B>V)throw new RangeError("value (".concat(B,") is bigger than max (").concat(V,")"))}r.checkBoundaries=c;function d(B,A,V){return B<A?A:B>V?V:B}r.checkValuesAgainstBoundaries=d;function h(B){if(!(B.length<2)&&!B.slice(1).every(function(A,V){return B[V]<=A}))throw new RangeError("values={[".concat(B,"]} needs to be sorted when allowOverlap={false}"))}r.checkInitialOverlap=h;function f(B){var A=window.getComputedStyle(B);return{top:parseInt(A["margin-top"],10),bottom:parseInt(A["margin-bottom"],10),left:parseInt(A["margin-left"],10),right:parseInt(A["margin-right"],10)}}r.getMargin=f;function p(B){var A=window.getComputedStyle(B);return{top:parseInt(A["padding-top"],10)+parseInt(A["border-top-width"],10),bottom:parseInt(A["padding-bottom"],10)+parseInt(A["border-bottom-width"],10),left:parseInt(A["padding-left"],10)+parseInt(A["border-left-width"],10),right:parseInt(A["padding-right"],10)+parseInt(A["border-right-width"],10)}}r.getPaddingAndBorder=p;function g(B,A,V){var N=V?-1:1;B.forEach(function(H,P){return y(H,N*A[P].x,A[P].y)})}r.translateThumbs=g;function x(B,A,V,N){for(var H=0,P=O(B[0],A,V,N),W=1;W<B.length;W++){var j=O(B[W],A,V,N);j<P&&(P=j,H=W)}return H}r.getClosestThumbIndex=x;function y(B,A,V){B.style.transform="translate(".concat(A,"px, ").concat(V,"px)")}r.translate=y;var m=function(B){var A=[],V=null,N=function(){for(var H=[],P=0;P<arguments.length;P++)H[P]=arguments[P];A=H,!V&&(V=requestAnimationFrame(function(){V=null,B.apply(void 0,A)}))};return N};r.schd=m;function v(B,A,V){var N=B.slice(0);return N[A]=V,N}r.replaceAt=v;function b(B){var A=B.values,V=B.colors,N=B.min,H=B.max,P=B.direction,W=P===void 0?n.Direction.Right:P,j=B.rtl,X=j===void 0?!1:j;X&&W===n.Direction.Right?W=n.Direction.Left:X&&n.Direction.Left&&(W=n.Direction.Right);var te=A.slice(0).sort(function(Z,se){return Z-se}).map(function(Z){return(Z-N)/(H-N)*100}),Q=te.reduce(function(Z,se,ve){return"".concat(Z,", ").concat(V[ve]," ").concat(se,"%, ").concat(V[ve+1]," ").concat(se,"%")},"");return"linear-gradient(".concat(W,", ").concat(V[0]," 0%").concat(Q,", ").concat(V[V.length-1]," 100%)")}r.getTrackBackground=b;function I(){}r.voidFn=I;function S(B){throw new Error("Didn't expect to get here")}r.assertUnreachable=S;var M=function(B,A,V,N,H){H===void 0&&(H=function(W){return W});var P=Math.ceil(e([B],Array.from(B.children),!0).reduce(function(W,j){var X=Math.ceil(j.getBoundingClientRect().width);if(j.innerText&&j.innerText.includes(V)&&j.childElementCount===0){var te=j.cloneNode(!0);te.innerHTML=H(A.toFixed(N)),te.style.visibility="hidden",document.body.appendChild(te),X=Math.ceil(te.getBoundingClientRect().width),document.body.removeChild(te)}return X>W?X:W},B.getBoundingClientRect().width));return P},U=function(B,A,V,N,H,P,W){W===void 0&&(W=function(te){return te});var j=[],X=function(te){var Q=M(V[te],N[te],H,P,W),Z=A[te].x;A.forEach(function(se,ve){var ge=se.x,be=M(V[ve],N[ve],H,P,W);te!==ve&&(Z>=ge&&Z<=ge+be||Z+Q>=ge&&Z+Q<=ge+be)&&(j.includes(ve)||(j.push(te),j.push(ve),j=e(e([],j,!0),[te,ve],!1),X(ve)))})};return X(B),Array.from(new Set(j.sort()))},z=function(B,A,V,N,H,P){N===void 0&&(N=.1),H===void 0&&(H=" - "),P===void 0&&(P=function(ve){return ve});var W=(0,r.getStepDecimals)(N),j=(0,t.useState)({}),X=j[0],te=j[1],Q=(0,t.useState)(P(A[V].toFixed(W))),Z=Q[0],se=Q[1];return(0,t.useEffect)(function(){if(B){var ve=B.getThumbs();if(ve.length<1)return;var ge={},be=B.getOffsets(),ct=U(V,be,ve,A,H,W,P),dt=P(A[V].toFixed(W));if(ct.length){var Se=ct.reduce(function(mt,Ot,dr,tt){return mt.length?e(e([],mt,!0),[be[tt[dr]].x],!1):[be[tt[dr]].x]},[]);if(Math.min.apply(Math,Se)===be[V].x){var et=[];ct.forEach(function(mt){et.push(A[mt].toFixed(W))}),dt=Array.from(new Set(et.sort(function(mt,Ot){return parseFloat(mt)-parseFloat(Ot)}))).map(P).join(H);var Ze=Math.min.apply(Math,Se),qe=Math.max.apply(Math,Se),Mt=ve[ct[Se.indexOf(qe)]].getBoundingClientRect().width;ge.left="".concat(Math.abs(Ze-(qe+Mt))/2,"px"),ge.transform="translate(-50%, 0)"}else ge.visibility="hidden"}se(dt),te(ge)}},[B,A]),[Z,X]};r.useThumbOverlap=z;function O(B,A,V,N){var H=B.getBoundingClientRect(),P=H.left,W=H.top,j=H.width,X=H.height;return u(N)?Math.abs(V-(W+X/2)):Math.abs(A-(P+j/2))}var R=function(){var B,A=((B=navigator.userAgentData)===null||B===void 0?void 0:B.platform)||navigator.platform;return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(A)||navigator.userAgent.includes("Mac")&&"ontouchend"in document};r.isIOS=R})(pp);var x5=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)}}(),S5=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]}),I5=Nr&&Nr.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),k5=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)&&S5(e,r,t);return I5(e,r),e},cy=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(fp,"__esModule",{value:!0});var wl=k5($),De=pp,Ft=xo,E5=["ArrowRight","ArrowUp","k","PageUp"],M5=["ArrowLeft","ArrowDown","j","PageDown"],T5=function(r){x5(e,r);function e(t){var n=r.call(this,t)||this;if(n.trackRef=wl.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,De.getPaddingAndBorder)(u);return n.getThumbs().map(function(h,f){var p={x:0,y:0},g=h.getBoundingClientRect(),x=(0,De.getMargin)(h);switch(s){case Ft.Direction.Right:return p.x=(x.left+d.left)*-1,p.y=((g.height-c.height)/2+d.top)*-1,p.x+=c.width*(0,De.relativeValue)(o[f],a,l)-g.width/2,p;case Ft.Direction.Left:return p.x=(x.right+d.right)*-1,p.y=((g.height-c.height)/2+d.top)*-1,p.x+=c.width-c.width*(0,De.relativeValue)(o[f],a,l)-g.width/2,p;case Ft.Direction.Up:return p.x=((g.width-c.width)/2+x.left+d.left)*-1,p.y=-d.left,p.y+=c.height-c.height*(0,De.relativeValue)(o[f],a,l)-g.height/2,p;case Ft.Direction.Down:return p.x=((g.width-c.width)/2+x.left+d.left)*-1,p.y=-d.left,p.y+=c.height*(0,De.relativeValue)(o[f],a,l)-g.height/2,p;default:return(0,De.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,De.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,De.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,De.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,De.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,De.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===Ft.Direction.Left||c===Ft.Direction.Down?-1:1;h!==-1&&(E5.includes(i.key)?(i.preventDefault(),n.setState({draggedThumbIndex:h,isChanged:!0}),a((0,De.replaceAt)(o,h,n.normalizeValue(o[h]+f*(i.key==="PageUp"?l*10:l),h)))):M5.includes(i.key)?(i.preventDefault(),n.setState({draggedThumbIndex:h,isChanged:!0}),a((0,De.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,g=u.step,x=u.rtl;if(a===-1&&l[0]===-1&&l[1]===-1)return null;var y=n.trackRef.current;if(!y)return null;var m=y.getBoundingClientRect(),v=(0,De.isVertical)(c)?m.height:m.width;if(l[0]!==-1&&l[1]!==-1){var b=i-l[0],I=s-l[1],S=0;switch(c){case Ft.Direction.Right:case Ft.Direction.Left:S=b/v*(h-d);break;case Ft.Direction.Down:case Ft.Direction.Up:S=I/v*(h-d);break;default:(0,De.assertUnreachable)(c)}if(x&&(S*=-1),Math.abs(S)>=g/2){for(var M=0;M<n.thumbRefs.length;M++){if(p[M]===h&&Math.sign(S)===1||p[M]===d&&Math.sign(S)===-1)return;var U=p[M]+S;U>h?S=h-p[M]:U<d&&(S=d-p[M])}for(var z=p.slice(0),M=0;M<n.thumbRefs.length;M++)z=(0,De.replaceAt)(z,M,n.normalizeValue(p[M]+S,M));n.setState({draggedTrackPos:[i,s]}),f(z)}}else{var O=0;switch(c){case Ft.Direction.Right:O=(i-m.left)/v*(h-d)+d;break;case Ft.Direction.Left:O=(v-(i-m.left))/v*(h-d)+d;break;case Ft.Direction.Down:O=(s-m.top)/v*(h-d)+d;break;case Ft.Direction.Up:O=(v-(s-m.top))/v*(h-d)+d;break;default:(0,De.assertUnreachable)(c)}x&&(O=h+d-O),Math.abs(p[a]-O)>=g/2&&f((0,De.replaceAt)(p,a,n.normalizeValue(O,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,De.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]=wl.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===Ft.Direction.Left||n.props.direction===Ft.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,De.schd)(n.onMouseMove),n.schdOnTouchMove=(0,De.schd)(n.onTouchMove),n.schdOnEnd=(0,De.schd)(n.onEnd),n.thumbRefs=t.values.map(function(){return wl.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,De.checkInitialOverlap)(this.props.values),this.props.values.forEach(function(a){return(0,De.checkBoundaries)(a,t.props.min,t.props.max)}),this.resizeObserver.observe(this.trackRef.current),(0,De.translateThumbs)(this.getThumbs(),this.getOffsets(),this.props.rtl),this.calculateMarkOffsets(),i.forEach(function(a){(0,De.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,De.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,De.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,g=this.state,x=g.draggedThumbIndex,y=g.thumbZIndexes,m=g.markOffsets;return o({props:{style:{transform:"scale(1)",cursor:x>-1?"grabbing":this.props.draggableTrack?(0,De.isVertical)(this.props.direction)?"ns-resize":"ew-resize":c.length===1&&!p?"pointer":"inherit"},onMouseDown:p?De.voidFn:this.onMouseDownTrack,onTouchStart:p?De.voidFn:this.onTouchStartTrack,ref:this.trackRef},isDragged:this.state.draggedThumbIndex>-1,disabled:p,children:cy(cy([],m.map(function(v,b,I){return u({props:{style:t.props.direction===Ft.Direction.Left||t.props.direction===Ft.Direction.Right?{position:"absolute",left:"".concat(v[0],"px"),marginTop:"".concat(v[1],"px")}:{position:"absolute",top:"".concat(v[0],"px"),marginLeft:"".concat(v[1],"px")},key:"mark".concat(b),ref:t.markRefs[b]},index:b})}),!0),c.map(function(v,b){var I=t.state.draggedThumbIndex===b;return a({index:b,value:v,isDragged:I,props:{style:{position:"absolute",zIndex:y[b],cursor:p?"inherit":I?"grabbing":"grab",userSelect:"none",touchAction:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none"},key:b,tabIndex:p?void 0:0,"aria-valuemax":f?h:c[b+1]||h,"aria-valuemin":f?d:c[b-1]||d,"aria-valuenow":v,draggable:!1,ref:t.thumbRefs[b],"aria-label":i,"aria-labelledby":s,role:"slider",onKeyDown:p?De.voidFn:t.onKeyDown,onKeyUp:p?De.voidFn:t.onKeyUp}})}),!0)})},e.defaultProps={label:"Accessibility label",labelledBy:null,step:1,direction:Ft.Direction.Right,rtl:!1,disabled:!1,allowOverlap:!1,draggableTrack:!1,min:0,max:100},e}(wl.Component);fp.default=T5;(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(fp);r.Range=t.default;var n=pp;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=xo;Object.defineProperty(r,"Direction",{enumerable:!0,get:function(){return i.Direction}})})(kC);const jr={fontSize:12,color:"#9aa7b2"},dy={background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:10};function ea(r,e,t){return Math.max(e,Math.min(t,r))}function hy(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},${ea(e,0,1)})`}function U5(r){const e=["#66d9ef","#a6e22e","#fd971f","#e6db74","#f92672","#ae81ff","#2aa198"];return e[Math.abs(r)%e.length]}function EC(r,e){const t=(r??"").trim();return t.length?t:e}function A5(r,e){return r.map(t=>{const n=e.get(t);return n?{id:t,name:EC(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 R5({user:r,selectedDisplayId:e,selectedLayerIds:t,onSelectLayer:n,onSelectDisplay:i,setVisibleLayers:s}){var b;const o=$.useMemo(()=>r.displays.filter(I=>I.id!==255),[r.displays]),[a,l]=$.useState(null),[u,c]=$.useState([0,0]),d=$.useRef(null),h=$.useMemo(()=>{var M,U,z;const I=(M=o.find(O=>O.id===e))==null?void 0:M.id;if(I!=null)return I;const S=(U=o.find(O=>O.id===a))==null?void 0:U.id;return S??((z=o[0])==null?void 0:z.id)??null},[a,o,e]),f=$.useMemo(()=>h==null?null:o.find(I=>I.id===h)??null,[o,h]),p=$.useMemo(()=>{var S,M;if(h==null)return null;const I=(M=(S=r.displayComposite)==null?void 0:S[h])==null?void 0:M.layerIdsTopToBottom;return I&&I.length?I:null},[h,r.displayComposite]),g=$.useMemo(()=>{const I=new Map;for(const S of r.layers)I.set(S.id,{id:S.id,name:S.name,z:S.z,origin:S.origin,width:S.width,height:S.height});return I},[r.layers]),x=$.useMemo(()=>{var R,B;if(h==null)return[];const I=(B=(R=r.displayComposite)==null?void 0:R[h])==null?void 0:B.layerIdsTopToBottom;if(I&&I.length)return A5(I,g);if(!f)return[];const S=f.origin.x,M=f.origin.y,U=S+f.size.x,z=M+f.size.y,O=[];for(const A of r.layers){const V=A.origin.x,N=A.origin.y,H=A.origin.x+A.width,P=A.origin.y+A.height;U<=V||S>=H||z<=N||M>=P||O.push({id:A.id,name:EC(A.name,`Layer ${A.id}`),z:A.z,layer:A})}return O.sort((A,V)=>V.z-A.z),O},[h,f,g,r.displayComposite,r.layers]);$.useEffect(()=>{const I=x.length;if(!I){c([0,0]);return}const S=Math.max(0,I-1);c([0,S])},[h,x.length]);const y=$.useMemo(()=>{const I=Math.max(0,x.length-1);let S=ea(u[0],0,I),M=ea(u[1],0,I);return S>M&&([S,M]=[M,S]),[S,M]},[x.length,u]),m=$.useMemo(()=>{if(!x.length)return x;const[I,S]=y;return x.slice(I,S+1)},[x,y]);$.useEffect(()=>{if(!s)return;if(!x.length){s(null);return}const[I,S]=y;if(I===0&&S===x.length-1){s(null);return}s(m.map(U=>U.id))},[x.length,y,s,m]);const v=$.useMemo(()=>{if(!f)return null;const I=m;if(!x.length)return{visible:[],minY:f.origin.y,maxY:f.origin.y+f.size.y,range:[0,0]};const[S,M]=y,U=I;let z=f.origin.y,O=f.origin.y+f.size.y;for(const R of U){const B=R.layer;B&&(z=Math.min(z,B.origin.y),O=Math.max(O,B.origin.y+B.height))}return{visible:U,minY:z,maxY:O,range:[S,M]}},[f,x.length,y,m]);return $.useEffect(()=>{const I=d.current;if(!I||!f||!v)return;const S=I.getContext("2d");if(!S)return;const M=window.devicePixelRatio||1,U=I.clientWidth,z=I.clientHeight,O=Math.max(1,Math.floor(U*M)),R=Math.max(1,Math.floor(z*M));(I.width!==O||I.height!==R)&&(I.width=O,I.height=R),S.setTransform(M,0,0,M,0,0),S.clearRect(0,0,U,z);const B=14,A=Math.max(1,U-B*2),V=Math.max(1,z-B*2),N=v.minY,H=v.maxY,P=Math.max(1,H-N),W=f.origin.x,j=f.origin.x+f.size.x,X=Math.max(1,j-W),te=Se=>B+(Se-W)/X*A,Q=Se=>Se/X*A,Z=Se=>B+(Se-N)/P*V,se=Se=>Se/P*V;S.fillStyle="rgba(0,0,0,0.20)",S.fillRect(0,0,U,z);const ve=te(f.origin.x),ge=Z(f.origin.y),be=Q(f.size.x),ct=se(f.size.y);S.strokeStyle="rgba(255,120,120,0.75)",S.lineWidth=1,S.strokeRect(ve,ge,be,ct),S.fillStyle="rgba(255,120,120,0.08)",S.fillRect(ve,ge,be,ct);const dt=v.visible;for(let Se=dt.length-1;Se>=0;Se--){const et=dt[Se],Ze=et.layer;if(!Ze)continue;const qe=te(Ze.origin.x),Mt=Z(Ze.origin.y),mt=Math.max(2,Q(Ze.width)),Ot=Math.max(2,se(Ze.height)),dr=U5(et.id),tt=t.includes(et.id);S.fillStyle=hy(dr,1),S.strokeStyle=hy(dr,tt?.95:.55),S.lineWidth=tt?2:1,S.fillRect(qe,Mt,mt,Ot),S.strokeRect(qe,Mt,mt,Ot),S.save(),S.beginPath(),S.rect(qe,Mt,mt,Ot),S.clip(),S.fillStyle="rgba(15,15,15,0.95)",S.font="12px Segoe UI, sans-serif";const xt=[`${et.name}`,`id ${et.id} • z ${et.z}`,`pos ${Ze.origin.x},${Ze.origin.y}`,`size ${Ze.width}×${Ze.height}`],nt=14;let br=Mt+16;const xe=qe+8;for(let Re=0;Re<xt.length&&!(br>Mt+Ot-4);Re++){const pe=xt[Re];S.fillText(pe,xe,br),br+=nt}S.restore()}dt.length===0&&(S.fillStyle="rgba(154,167,178,0.9)",S.font="12px Segoe UI, sans-serif",S.fillText("No layers in this range",B+8,B+18))},[f,t,v]),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:jr,children:"Side stack per display (core-derived)"})]}),k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[k.jsx("div",{style:jr,children:"Display"}),k.jsx("select",{value:h??"",onChange:I=>{const S=I.target.value===""?null:Number(I.target.value);l(S),S!=null&&i(S)},style:{height:28,background:"#252526",color:"#cccccc",border:"1px solid #3c3c3c",borderRadius:8,padding:"0 8px",fontSize:12,outline:"none"},children:o.map(I=>k.jsx("option",{value:I.id,children:I.id},I.id))})]})]}),k.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:12,background:"#14161a"},children:h==null?k.jsx("div",{style:{...jr,padding:16},children:"No display."}):k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 280px",gap:12,alignItems:"start"},children:[k.jsxs("div",{style:{...dy,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:jr,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:jr,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(kC.Range,{step:1,min:0,max:Math.max(0,x.length-1),values:(()=>{const I=Math.max(0,x.length-1),S=I-y[1],M=I-y[0];return[S,M]})(),onChange:I=>{const S=Math.max(0,x.length-1),M=Math.round(I[0]??0),U=Math.round(I[1]??0),z=ea(S-U,0,S),O=ea(S-M,0,S);c([z,O])},renderTrack:({props:I,children:S})=>k.jsxs("div",{...I,style:{...I.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 M=Math.max(1,x.length-1),U=(M-y[1])/M,z=(M-y[0])/M,O=U*100,R=z*100;return k.jsx("div",{style:{position:"absolute",left:`${Math.min(O,R)}%`,width:`${Math.max(0,Math.abs(R-O))}%`,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"}})})(),S]}),renderThumb:({props:I,index:S})=>k.jsx("div",{...I,style:{...I.style,height:14,width:14,borderRadius:999,background:S===0?"#66d9ef":"#fd971f",border:"1px solid rgba(0,0,0,0.35)",boxShadow:"0 2px 10px rgba(0,0,0,0.35)"},title:S===0?"Bottom handle":"Top handle"})})}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10},children:[k.jsx("div",{style:jr,children:"BOTTOM"}),k.jsxs("div",{style:jr,children:[x.length?`${y[0]} → ${y[1]}`:"—",x.length?` • ${m.length}/${x.length}`:""]}),k.jsx("div",{style:jr,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:{...dy,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:jr,children:[m.length," / ",x.length," layers"]})]}),p&&k.jsxs("div",{style:{...jr,marginTop:6},children:["core order: top→bottom • [",p.join(", "),"]"]}),k.jsxs("div",{style:{marginTop:10,display:"flex",flexDirection:"column",gap:8},children:[x.map((I,S)=>{const M=t.includes(I.id),U=S>=y[0]&&S<=y[1];return k.jsx("button",{onClick:z=>{n(I.id,{metaKey:z.metaKey,ctrlKey:z.ctrlKey});const O=x.findIndex(R=>R.id===I.id);O>=0&&c([O,O])},style:{textAlign:"left",width:"100%",background:M?"rgba(102, 217, 239, 0.10)":U?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",border:M?"1px solid rgba(102, 217, 239, 0.65)":U?"1px solid rgba(255,255,255,0.10)":"1px solid rgba(255,255,255,0.06)",borderRadius:10,padding:"8px 10px",cursor:"pointer",color:U?"#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:I.name}),k.jsxs("div",{style:{...jr,whiteSpace:"nowrap"},children:["z=",I.z]})]})},I.id)}),x.length===0&&k.jsx("div",{style:{...jr,padding:10},children:"No layers."}),((b=r.displayComposite)==null?void 0:b[h])==null&&k.jsx("div",{style:{...jr,paddingTop:8},children:"Using fallback intersection (core composition not present)."})]})]})]})})]})}function P5({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:g,sortedTraffic:x,topTraffic:y,chartData:m,topKeys:v,keyToLabel:b,keyToColor:I,tickRate:S,hoveredTrafficKey:M,setHoveredTrafficKey:U}){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(z=>{const O=r===z.id;return k.jsx("button",{onClick:()=>e(z.id),style:{border:"1px solid #3c3c3c",borderBottom:O?"1px solid #1e1e1e":"1px solid #3c3c3c",background:O?"#1e1e1e":"#2d2d2d",color:"#cccccc",padding:"4px 10px",cursor:"pointer",fontSize:12,borderRadius:"4px 4px 0 0",marginBottom:"-1px"},children:z.label},z.id)})}),k.jsxs("div",{ref:t,style:{position:"relative",flex:1,minHeight:0,overflow:"hidden",background:"#1e1e1e"},children:[r==="grid"&&k.jsx(C5,{layers:i,displays:s,width:n.width,height:n.height,selectedLayerIds:o,selectedDisplayId:l,focusRect:u,focusKey:c,onSelectLayer:d,onSelectDisplay:h,onToolRectCommit:z=>{window.dispatchEvent(new window.CustomEvent("__utsp_debug_display255_rect",{detail:z}))}}),r==="composer"&&p&&k.jsx(R5,{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(SM,{assetsSnapshot:f}),r==="renderer"&&!g&&k.jsx("div",{style:{position:"absolute",inset:0,background:"#111"}}),r==="renderer"&&g&&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(b5,{sortedTraffic:x,topTraffic:y,chartData:m,topKeys:v,keyToLabel:b,keyToColor:I,tickRate:S,hoveredTrafficKey:M,setHoveredTrafficKey:U})]})]})}function z5(r){var d,h;const{enabled:e,snapshot:t,layers:n}=r,[i,s]=$.useState([]),o=$.useRef(null),a=$.useRef(0),l=$.useMemo(()=>{let f=0;for(let p=0;p<n.length;p++){const g=n[p].bytesPerSec1s;typeof g=="number"&&(f+=g)}return f},[n]);$.useEffect(()=>{e&&s(f=>f.length>0?f:[{time:"—",total:0}])},[e]),$.useEffect(()=>{var v,b;if(!e)return;const f=((v=t==null?void 0:t.tick)==null?void 0:v.tickRate)??((b=t==null?void 0:t.tick)==null?void 0:b.tps)??60,p=Math.max(1,Math.round(f*10)),g=performance.now?performance.now():Date.now(),x=Math.max(1,Math.round(1e3/f));if(g-a.current<x)return;a.current=g;const m={time:new Date().toLocaleTimeString("en-US",{hour12:!1,minute:"2-digit",second:"2-digit"}),total:l};s(I=>{if(o.current!==f)return o.current=f,[m];const S=I.length===0?[m]:[...I,m];return S.length>p?S.slice(S.length-p):S})},[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=$.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 D5({primaryUser:r,tickRate:e,snapshot:t,assetsSnapshot:n}){const{totalBytesAll:i,totalBytesAssets:s,totalBytesNonAssets:o,totalBpsNonAssets:a}=$.useMemo(()=>{var v;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 b=0;b<u.length;b++){const I=u[b];typeof I.bytesTotal=="number"&&(h+=I.bytesTotal),typeof I.bytesPerSec1s=="number"&&(f+=I.bytesPerSec1s)}for(const b of Object.values(c))typeof(b==null?void 0:b.total)=="number"&&(h+=b.total),typeof(b==null?void 0:b.bytesPerSec1s)=="number"&&(f+=b.bytesPerSec1s);for(const b of Object.values(d))typeof(b==null?void 0:b.total)=="number"&&(h+=b.total),typeof(b==null?void 0:b.bytesPerSec1s)=="number"&&(f+=b.bytesPerSec1s);const p=Array.isArray(n==null?void 0:n.audio)?n.audio:[];let g=0;for(let b=0;b<p.length;b++){const I=(v=p[b])==null?void 0:v.originalSize;typeof I=="number"&&Number.isFinite(I)&&I>0&&(g+=I)}const x=Math.max(0,h),y=g>0?g:void 0;return{totalBytesAll:y!=null?y+x:x,totalBytesAssets:y,totalBytesNonAssets:x,totalBpsNonAssets:Math.max(0,f)}},[r,t,n]),{data:l}=z5({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:Xr(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:Xr(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:Xr(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:[Xr(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(IC,{data:l,seriesKeys:["total"],seriesLabels:{total:"Total"},colors:["#4fc1ff"],height:120,tickRate:e,windowSeconds:10})]})]})]})}function fy({enabled:r,initialRect:e,minSize:t}){const[n,i]=$.useState(e),[s,o]=$.useState(!1),a=$.useRef({x:0,y:0}),l=$.useRef({resizing:!1,startX:0,startY:0,startW:0,startH:0});return $.useEffect(()=>{if(!r)return;const d=()=>{i(h=>{const p=Math.max(t.width,window.innerWidth-16),g=Math.max(t.height,window.innerHeight-8*2),x=Math.min(Math.max(t.width,h.width),p),y=Math.min(Math.max(t.height,h.height),g),m=Math.min(Math.max(8,h.x),Math.max(8,window.innerWidth-8-x)),v=Math.min(Math.max(8,h.y),Math.max(8,window.innerHeight-8-y));return{x:m,y:v,width:x,height:y}})};return d(),window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)},[r,t.height,t.width]),$.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,g=f.clientY-l.current.startY;i(x=>({...x,width:Math.max(t.width,l.current.startW+p),height:Math.max(t.height,l.current.startH+g)}))}},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 py(r){const[e,t]=$.useState({width:600,height:400}),[n,i]=$.useState({left:0,top:0}),[s,o]=$.useState(null);return $.useLayoutEffect(()=>{const a=r.current??null;o(l=>l===a?l:a)},[r]),$.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 O5(r,e){const[t,n]=$.useState(null),[i,s]=$.useState([]),[o,a]=$.useState(null),[l,u]=$.useState(0),c=$.useMemo(()=>r?r.layers.map(v=>({id:v.id,x:v.origin.x,y:v.origin.y,width:v.width,height:v.height,color:i.includes(v.id)?"rgba(43, 140, 255, 0.7)":void 0})):[],[r,i]),d=$.useMemo(()=>r?r.displays.map(v=>({id:v.id,x:v.origin.x,y:v.origin.y,width:v.size.x,height:v.size.y})):[],[r]),h=$.useMemo(()=>o!=null?c.find(v=>v.id===o)??null:t!=null?d.find(v=>v.id===t)??null:null,[o,t,d,c]),f=$.useMemo(()=>`${t??"none"}-${i.join(",")}-${l}`,[t,i,l]),p=v=>{r!=null&&r.displays.some(b=>b.id===v)&&(u(b=>b+1),n(v),s([]),a(null),e.setVisibleLayers(null))},g=v=>{const b=r==null?void 0:r.layers.find(I=>I.id===v);return b?{x:b.origin.x,y:b.origin.y,width:b.width,height:b.height}:null},x=(v,b)=>{if(e.setVisibleLayersDisplay255(v.length>0?v:null),b!=null){const I=g(b);I&&e.sendDisplayTransform(I)}},y=(v,b)=>{if(!(r!=null&&r.layers.some(S=>S.id===v)))return;const I=!!(b&&(b.metaKey||b.ctrlKey));u(S=>S+1),n(null),s(S=>{if(!I)return S.includes(v)?(a(null),x([],null),[]):(a(v),x([v],v),[v]);const M=S.includes(v)?S.filter(z=>z!==v):[...S,v],U=M.length>0?M[M.length-1]:null;return a(U),x(M,U),M})},m=(v,b)=>{if(!(r!=null&&r.layers.some(S=>S.id===v)))return;const I=!!(b&&(b.metaKey||b.ctrlKey));u(S=>S+1),n(null),s(S=>{if(!I)return S.includes(v)?(a(null),x([],null),[]):(a(v),x([v],v),[v]);const M=S.includes(v)?S.filter(z=>z!==v):[...S,v],U=M.length>0?M[M.length-1]:null;return a(U),x(M,U),M})};return $.useEffect(()=>{if(!r){n(null),s([]),a(null),e.setVisibleLayers(null),e.setVisibleLayersDisplay255(null);return}const v=new Set(r.layers.map(I=>I.id)),b=new Set(r.displays.map(I=>I.id));s(I=>{const S=I.filter(U=>v.has(U)),M=S.length>0?S[S.length-1]:null;return a(M),x(S,M),S}),n(I=>I!=null&&b.has(I)?I:null)},[r,e]),{selectedDisplayId:t,selectedLayerIds:i,lastSelectedLayerId:o,focusKey:f,focusRect:h,handleSelectDisplay:p,handleSelectLayer:y,handleSelectLayerDisplay255Only:m,setFocusNonce:u}}function B5(r){const{enabled:e,snapshot:t,topKeys:n,topTraffic:i}=r,[s,o]=$.useState([]),a=$.useRef(null),l=$.useRef(0),u=$.useRef(i);u.current=i;const c=$.useMemo(()=>n.join(","),[n]);$.useEffect(()=>{e&&o(f=>{if(f.length>0)return f;const p={time:"—"};for(let g=0;g<n.length;g++)p[n[g]]=0;return[p]})},[e,c]),$.useEffect(()=>{var b,I;if(!e||!t)return;const f=((b=t==null?void 0:t.tick)==null?void 0:b.tickRate)??((I=t==null?void 0:t.tick)==null?void 0:I.tps)??60,p=Math.max(1,Math.round(f*60)),g=performance.now?performance.now():Date.now(),x=Math.max(1,Math.round(1e3/f));if(g-l.current<x)return;l.current=g;const m={time:new Date().toLocaleTimeString("en-US",{hour12:!1,minute:"2-digit",second:"2-digit"})},v=u.current;for(let S=0;S<v.length;S++){const M=v[S];m[M.key]=M.bps??0}o(S=>{if(a.current!==f)return a.current=f,[m];const M=S.length===0?[m]:[...S,m];return M.length>p?M.slice(M.length-p):M})},[e,t,c]);const d=a.current??60,h=$.useMemo(()=>{if(!e)return[];const f=new Array(s.length);for(let p=0;p<s.length;p++){const g=s[p],x={time:g.time};for(let y=0;y<n.length;y++){const m=n[y];x[m]=Number(g[m]??0)}f[p]=x}return f},[e,s,n]);return{trafficHistory:s,tickRate:d,chartData:h}}const F5=r=>typeof r!="string"?"8-bit":r.includes("16")?"16-bit":"8-bit";function L5(r){var y;const{primaryUser:e,selection:t,selectedDisplayId:n,lastSelectedLayerId:i,selectedLayerIds:s}=r,o=$.useMemo(()=>((e==null?void 0:e.displays)??[]).map(v=>({id:v.id,x:v.origin.x,y:v.origin.y,width:v.size.x,height:v.size.y})),[e]),a=((y=e==null?void 0:e.layers)==null?void 0:y.length)??0,l=$.useMemo(()=>e?!t.selectedLayerIds.length&&!e?[]:e.layers.map(m=>({id:m.id,x:m.origin.x,y:m.origin.y,width:m.width,height:m.height,zIndex:m.z??0,name:m.name})):[],[e,t.selectedLayerIds.length]),u=$.useMemo(()=>{if(!e)return null;if(s.length){const m=e.layers.find(v=>v.id===i);return m?{type:"layer",item:m}:null}if(n!=null){const m=e.displays.find(v=>v.id===n);return m?{type:"display",item:m}:null}return null},[i,e,n,s.length]),c=$.useMemo(()=>{const v=((e==null?void 0:e.layers)??[]).filter(O=>typeof O.bytesPerSec1s=="number").map(O=>({key:`layer-${O.id}`,id:O.id,name:O.name,encoding:F5(O.charCodeMode),total:O.bytesTotal??0,bps:O.bytesPerSec1s??0,size:{x:O.width,y:O.height},position:{x:O.origin.x,y:O.origin.y},zIndex:O.z??0})),b=(e==null?void 0:e.miscTraffic)??{},I=O=>{switch(O){case"update.audioOrders":return"Audio";case"update.vibrationOrders":return"Vibration";case"update.macroOrders":return"Macro";case"update.postProcessOrders":return"PostProcess";default:return O}},S=Object.entries(b).map(([O,R],B)=>({key:`misc-${O}`,id:1e5+B,name:I(O),total:R.total??0,bps:R.bytesPerSec1s??0,size:{x:0,y:0},position:{x:0,y:0},zIndex:0})),M=((e==null?void 0:e.displays)??[]).filter(O=>O.id!==255),U=(e==null?void 0:e.displayTraffic)??{},z=M.map(O=>{const R=U[O.id];return{key:`display-${O.id}`,id:O.id,name:`Display ${O.id}`,total:(R==null?void 0:R.total)??0,bps:(R==null?void 0:R.bytesPerSec1s)??0,size:{x:O.size.x,y:O.size.y},position:{x:O.origin.x,y:O.origin.y},zIndex:0}}).filter(O=>typeof O.bps=="number");return[...v,...z,...S]},[e]),d=$.useMemo(()=>[...c].sort((m,v)=>v.total-m.total),[c]),h=$.useMemo(()=>d.slice(0,6),[d]),f=$.useMemo(()=>h.map(m=>m.key),[h]),p=$.useMemo(()=>Object.fromEntries(d.map(m=>[m.key,m.name??String(m.id)])),[d]),g=["#4fc1ff","#9cdcfe","#7bd389","#f9d85c","#f38ba8","#c586c0"],x=$.useMemo(()=>{const m={},v=new Set(d.map(I=>I.key)),b=I=>{let S=2166136261;for(let M=0;M<I.length;M++)S^=I.charCodeAt(M),S=Math.imul(S,16777619);return S>>>0};return v.forEach(I=>{const S=/^layer-(\d+)$/.exec(I),M=S?Number(S[1]):NaN,U=Number.isFinite(M)?M:b(I);m[I]=g[U%g.length]??"#4fc1ff"}),m},[d]);return{worldDisplays:o,worldLayers:l,layerCount:a,detailTarget:u,trafficItems:c,sortedTraffic:d,topTraffic:h,topKeys:f,keyToLabel:p,keyToColor:x}}function _5(r){const{runtimeClient:e,serverUrl:t,renderer:n,muted:i,snapshot:s}=r,o=$.useRef(null),a=$.useRef(null),l=$.useRef(null),[u,c]=$.useState({audio:[],atlases:[],palettes:[]}),d=$.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 $.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]),$.useEffect(()=>{e.setMuted(i)},[i,e]),$.useEffect(()=>{c(e.getAssetsSnapshot())},[e,s]),{rendererContainerRef:o,debugDisplay255ContainerRef:a,connect:d,assetsSnapshot:u,setAssetsSnapshot:c}}function $5({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 bl=new pM;function N5(){var br;const[r,e]=$.useState(()=>{if(typeof window>"u")return"http://localhost:3200";const{protocol:xe,hostname:Re,port:pe}=window.location;return pe==="4173"||pe==="5173"?`${xe}//${Re}:3200`:`${xe}//${Re}${pe?`:${pe}`:""}`}),t=Gs(xe=>xe.lastSnapshot),n=Gs(xe=>xe.connected),[i,s]=$.useState(!1),[o,a]=$.useState("grid"),[l,u]=$.useState(null),[c,d]=$.useState("float"),[h,f]=$.useState({width:0,height:0}),[p,g]=$.useState("embedded"),[x,y]=$.useState("network"),m=28,v={width:220,height:160},b=c==="float",I=24,S={width:220,height:160},M=fy({enabled:b,initialRect:{x:12,y:80,width:360,height:220},minSize:v}),U=fy({enabled:p==="float",initialRect:{x:12,y:360,width:360,height:260},minSize:S}),z=((br=t==null?void 0:t.users)==null?void 0:br[0])??null,O=p==="float",R=O5(z,bl),B=R.selectedDisplayId,A=R.selectedLayerIds,V=R.lastSelectedLayerId,N=R.focusRect,H=R.focusKey,P=$.useRef(null),{rect:W,size:j}=py(P),{worldDisplays:X,worldLayers:te,detailTarget:Q,sortedTraffic:Z,topTraffic:se,topKeys:ve,keyToLabel:ge,keyToColor:be}=L5({primaryUser:z,selection:R,selectedDisplayId:B,lastSelectedLayerId:V,selectedLayerIds:A}),{tickRate:ct,chartData:dt}=B5({enabled:!0,snapshot:t,topKeys:ve,topTraffic:se}),{rendererContainerRef:Se,debugDisplay255ContainerRef:et,connect:Ze,assetsSnapshot:qe}=_5({runtimeClient:bl,serverUrl:r,renderer:Qf.TerminalGL,muted:i,snapshot:t});$.useEffect(()=>{const xe="/logo_debugger.ico",Re=document.querySelector("link[rel='icon']");if(Re)Re.href=xe;else{const pe=document.createElement("link");pe.rel="icon",pe.href=xe,document.head.appendChild(pe)}},[]),$.useEffect(()=>{const xe=Re=>{const pe=Re.detail;pe&&bl.sendDisplayTransform(pe)};return window.addEventListener("__utsp_debug_display255_rect",xe),()=>window.removeEventListener("__utsp_debug_display255_rect",xe)},[]),$.useEffect(()=>{const xe=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=xe,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 Mt=$.useRef(null),{size:mt,rect:Ot}=py(Mt);$.useEffect(()=>{const xe=Se.current;if(!xe)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(xe),()=>Re.disconnect()},[]);const dr=mt.width,tt=mt.height,xt={left:b?M.rect.x:Ot.left,top:b?M.rect.y:Ot.top,width:b?M.rect.width:dr,height:b?M.rect.height:tt},nt=O?U.rect:{x:W.left??0,y:W.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(xM,{connected:n,serverUrl:r,onServerUrlChange:e,onReconnect:()=>{Ze()}}),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(CM,{primaryUser:z??null,selectedDisplayId:B,selectedLayerIds:A,onSelectDisplay:R.handleSelectDisplay,onSelectLayer:R.handleSelectLayerDisplay255Only})}),k.jsx(P5,{centerTab:o,setCenterTab:a,centerPanelRef:Mt,centerSize:mt,worldLayers:te,worldDisplays:X,selectedLayerIds:A,setVisibleLayers:xe=>bl.setVisibleLayers(xe),selectedDisplayId:B,focusRect:N,focusKey:H,onSelectLayer:R.handleSelectLayer,onSelectDisplay:R.handleSelectDisplay,assetsSnapshot:qe,primaryUser:z,isFloating:b,sortedTraffic:Z,topTraffic:se,chartData:dt,topKeys:ve,keyToLabel:ge,keyToColor:be,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:P,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(xe=>{const Re=x===xe.id;return k.jsx("button",{onClick:()=>y(xe.id),style:{border:"1px solid #3c3c3c",background:Re?"#1e1e1e":"#2d2d2d",color:"#cccccc",padding:"4px 10px",cursor:"pointer",fontSize:12,borderRadius:6},children:xe.label},xe.id)})}),k.jsx("div",{style:{flex:1,minHeight:0},children:x==="network"?k.jsx(D5,{primaryUser:z,tickRate:ct,snapshot:t,assetsSnapshot:qe}):k.jsx("div",{style:{height:"100%",minHeight:0},children:k.jsx(vM,{detailTarget:Q})})})]})]}),k.jsx(gM,{connected:n,muted:i,rendererPlacement:c,centerTab:o,frameRect:xt,rendererHeaderHeight:m,rendererContentSize:h,rendererContainerRef:Se,onTogglePlacement:()=>{d(xe=>{const Re=xe==="float"?"embedded":"float";return Re==="embedded"&&a("renderer"),Re})},onToggleMuted:()=>{s(xe=>!xe)},onStartDrag:(xe,Re)=>{M.startDrag(xe,Re)},onStartResize:(xe,Re)=>{M.startResize(xe,Re)}}),k.jsx($5,{connected:n,placement:p,headerHeight:I,frameRect:nt,containerRef:et,onTogglePlacement:()=>g(xe=>xe==="float"?"embedded":"float"),onStartDrag:U.startDrag,onStartResize:U.startResize})]})}const MC=document.getElementById("root");if(!MC)throw new Error("Root container not found");ud.createRoot(MC).render(k.jsx(Ey.StrictMode,{children:k.jsx(N5,{})}));
|
|
271
|
+
*/var Ou=$,aM=oM;function lM(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var uM=typeof Object.is=="function"?Object.is:lM,cM=aM.useSyncExternalStore,dM=Ou.useRef,hM=Ou.useEffect,fM=Ou.useMemo,pM=Ou.useDebugValue;Nb.useSyncExternalStoreWithSelector=function(r,e,t,n,i){var s=dM(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=fM(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,uM(c,f))return p;var g=n(f);return i!==void 0&&i(p,g)?(c=f,p):(c=f,d=g)}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=cM(r,s[0],s[1]);return hM(function(){o.hasValue=!0,o.value=a},[a]),pM(a),a};$b.exports=Nb;var gM=$b.exports;const mM=Cy(gM),Vb={},{useDebugValue:yM}=Py,{useSyncExternalStoreWithSelector:vM}=mM;let Sm=!1;const wM=r=>r;function bM(r,e=wM,t){(Vb?"production":void 0)!=="production"&&t&&!Sm&&(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"),Sm=!0);const n=vM(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return yM(n),n}const km=r=>{(Vb?"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"?KE(r):r,t=(n,i)=>bM(e,n,i);return Object.assign(t,e),t},CM=r=>r?km(r):km,Xs=CM(r=>({connected:!1,lastSnapshot:void 0,setConnected:e=>r({connected:e}),setSnapshot:e=>r({lastSnapshot:e})}));class xM{constructor(){Xi(this,"runtime",null);Xi(this,"layerTraffic",{});Xi(this,"miscTraffic",{});Xi(this,"displayTraffic",{});Xi(this,"visibleLayerIds",null);Xi(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){Xs.getState().setConnected(!1),this.runtime&&this.destroy();const t={mode:"connected",serverUrl:e.serverUrl,container:e.container,displayContainers:e.displayContainers,width:e.width??80,height:e.height??25,renderer:e.renderer??tp.TerminalGL,inputEnabled:e.inputEnabled??!0,captureInput:e.captureInput??!0,debug:!1,autoplay:!1};try{if(this.runtime=new jE(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}Xs.getState().setConnected(!0),Xs.getState().setSnapshot(l)}catch{}}),await this.runtime.start(),this.runtime.sendBridge("__debug_auth",{})}catch(n){throw Xs.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 IM({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 Zr(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 SM(r){return`${r.toFixed(2)} s`}const kM={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 No({label:r,tone:e="muted"}){const t=kM[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 Em({children:r}){return k.jsx("div",{style:{border:"1px solid #2a2a2a",borderRadius:6,background:"#161616"},children:r})}function Zn({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 EM({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(No,{label:"Active",tone:"info"})]}),k.jsxs(Em,{children:[k.jsx(Zn,{label:"Origin",value:`(${r.item.origin.x}, ${r.item.origin.y})`,divider:!0}),k.jsx(Zn,{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(No,{label:`#${r.item.id}`,tone:"info"})]}),k.jsx(No,{label:`z ${r.item.z}`,tone:"muted"})]}),k.jsxs(Em,{children:[k.jsx(Zn,{label:"Mode",value:r.item.charCodeMode,divider:!0}),k.jsx(Zn,{label:"Orders",value:r.item.ordersCount,divider:!0}),k.jsx(Zn,{label:"Size",value:`${r.item.width} × ${r.item.height}`,divider:!0}),k.jsx(Zn,{label:"Origin",value:`(${r.item.origin.x}, ${r.item.origin.y})`,divider:!0}),k.jsx(Zn,{label:"Static",value:r.item.isStatic?k.jsx(No,{label:"Static",tone:"success"}):k.jsx(No,{label:"Dynamic",tone:"muted"}),divider:!0}),r.item.bytesTotal!==void 0&&k.jsxs(k.Fragment,{children:[k.jsx(Zn,{label:"Total",value:Zr(r.item.bytesTotal),divider:!0}),k.jsx(Zn,{label:"Throughput",value:`${Zr(r.item.bytesPerSec1s)} /s`})]})]})]})]})]})}function Mm({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 MM(r){return r<1e3?`${r} B`:r<1e6?`${(r/1e3).toFixed(2)} KB`:`${(r/1e6).toFixed(2)} MB`}const As={id:"1fr",net:"90px",gap:4};function TM({displays:r,layers:e,selectedDisplayId:t,selectedLayerIds:n,onSelectDisplay:i,onSelectLayer:s}){const o=new Set(n),[a,l]=$.useState("id"),[u,c]=$.useState("asc"),d=$.useMemo(()=>{const f=[...e];return f.sort((p,g)=>{const C=a==="id"?p.id:p.bytesTotal??0,y=a==="id"?g.id:g.bytesTotal??0,m=C===y?0:C<y?-1:1;return u==="asc"?m:-m}),f},[e,u,a]),h=f=>{l(p=>p===f?(c(g=>g==="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(Mm,{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:`${As.id} ${As.net}`,alignItems:"center",columnGap:As.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),g=f.name?`${f.id}:${f.name}`:String(f.id);return k.jsx(Mm,{isSelected:p,onClick:C=>s(f.id,C),children:k.jsxs("span",{style:{display:"grid",gridTemplateColumns:`${As.id} ${As.net}`,alignItems:"center",columnGap:As.gap,width:"100%"},children:[k.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:k.jsx("span",{style:{color:"inherit"},children:g})}),k.jsx("span",{style:{color:"#858585",fontSize:11,textAlign:"right",whiteSpace:"nowrap"},children:f.bytesTotal!==void 0&&MM(f.bytesTotal)})]})},`layer-${f.id}-${p}`)})]})]})}function UM({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(TM,{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 AM({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 rd({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 RM({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(rd,{title:"Audio",emptyLabel:"No audio loaded",headers:["Name","Source","Duration","Size","URL"],rows:r.audio.map(e=>[e.name,e.source,SM(e.duration),Zr(e.originalSize),e.originalUrl??"—"])}),k.jsx(rd,{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(rd,{title:"Palettes",emptyLabel:"No palette",headers:["Slot","Colors"],rows:r.palettes.map(e=>[String(e.slotId),String(e.colors)])})]})}const PM=!0,jt="u-",zM="uplot",DM=jt+"hz",OM=jt+"vt",BM=jt+"title",FM=jt+"wrap",LM=jt+"under",_M=jt+"over",$M=jt+"axis",ts=jt+"off",NM=jt+"select",WM=jt+"cursor-x",HM=jt+"cursor-y",VM=jt+"cursor-pt",jM=jt+"legend",YM=jt+"live",GM=jt+"inline",XM=jt+"series",ZM=jt+"marker",Tm=jt+"label",KM=jt+"value",qo="width",Qo="height",Wo="top",Um="bottom",Rs="left",nd="right",rp="#000",Am=rp+"0",id="mousemove",Rm="mousedown",sd="mouseup",Pm="mouseenter",zm="mouseleave",Dm="dblclick",qM="resize",QM="scroll",Om="change",fu="dppxchange",np="--",bo=typeof window<"u",zh=bo?document:null,to=bo?window:null,JM=bo?navigator:null;let Ve,pl;function Dh(){let r=devicePixelRatio;Ve!=r&&(Ve=r,pl&&Bh(Om,pl,Dh),pl=matchMedia(`(min-resolution: ${Ve-.001}dppx) and (max-resolution: ${Ve+.001}dppx)`),as(Om,pl,Dh),to.dispatchEvent(new CustomEvent(fu)))}function Gr(r,e){if(e!=null){let t=r.classList;!t.contains(e)&&t.add(e)}}function Oh(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=zh.createElement(r);return e!=null&&Gr(i,e),t!=null&&t.insertBefore(i,n),i}function an(r,e){return Cn("div",r,e)}const Bm=new WeakMap;function $n(r,e,t,n,i){let s="translate("+e+"px,"+t+"px)",o=Bm.get(r);s!=o&&(r.style.transform=s,Bm.set(r,s),e<0||t<0||e>n||t>i?Gr(r,ts):Oh(r,ts))}const Fm=new WeakMap;function Lm(r,e,t){let n=e+t,i=Fm.get(r);n!=i&&(Fm.set(r,n),r.style.background=e,r.style.borderColor=t)}const _m=new WeakMap;function $m(r,e,t,n){let i=e+""+t,s=_m.get(r);i!=s&&(_m.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 ip={passive:!0},eT={...ip,capture:!0};function as(r,e,t,n){e.addEventListener(r,t,n?eT:ip)}function Bh(r,e,t,n){e.removeEventListener(r,t,ip)}bo&&Dh();function kn(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 jb(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 Yb=r=>r!=null,Gb=r=>r!=null&&r>0,Bu=jb(Yb),tT=jb(Gb);function rT(r,e,t,n=0,i=!1){let s=i?tT:Bu,o=i?Gb:Yb;[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 Fu(r,e,t,n){let i=Hm(r),s=Hm(e);r==e&&(i==-1?(r*=t,e/=t):(r/=t,e*=t));let o=t==10?ti:Xb,a=i==1?Qr:ln,l=s==1?ln:Qr,u=a(o(Wt(r))),c=l(o(Wt(e))),d=co(t,u),h=co(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=Qb(r,d),e=Lu(e,h)),[r,e]}function sp(r,e,t,n){let i=Fu(r,e,t,n);return r==0&&(i[0]=0),e==0&&(i[1]=0),i}const op=.1,Nm={mode:3,pad:op},ha={pad:0,soft:null,mode:0},nT={min:ha,max:ha};function pu(r,e,t,n){return _u(t)?Wm(r,e,t):(ha.pad=t,ha.soft=n?0:null,ha.mode=n?3:0,Wm(r,e,nT))}function _e(r,e){return r??e}function iT(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 Wm(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=ti(f),g=Mr(Wt(r),Wt(e)),C=ti(g),y=Wt(C-p);(f<1e-24||y>10)&&(f=0,(r==0||e==0)&&(f=1e-24,d==2&&u!=Qe&&(s=0),h==2&&c!=-Qe&&(o=0)));let m=f||g||1e3,v=ti(m),b=co(10,Qr(v)),S=m*(f==0?r==0?.1:1:s),I=Je(Qb(r-S,b/10),24),E=r>=u&&(d==1||d==3&&I<=u||d==2&&I>=u)?u:Qe,U=Mr(a,I<E&&r>=E?E:Mn(E,I)),z=m*(f==0?e==0?.1:1:o),B=Je(Lu(e+z,b/10),24),R=e<=c&&(h==1||h==3&&B>=c||h==2&&B<=c)?c:-Qe,O=Mn(l,B>R&&e<=R?R:Mr(R,B));return U==O&&U==0&&(O=100),[U,O]}const sT=new Intl.NumberFormat(bo?JM.language:"en-US"),ap=r=>sT.format(r),rn=Math,Ll=rn.PI,Wt=rn.abs,Qr=rn.floor,Lt=rn.round,ln=rn.ceil,Mn=rn.min,Mr=rn.max,co=rn.pow,Hm=rn.sign,ti=rn.log10,Xb=rn.log2,oT=(r,e=1)=>rn.sinh(r)*e,od=(r,e=1)=>rn.asinh(r/e),Qe=1/0;function Vm(r){return(ti((r^r>>31)-(r>>31))|0)+1}function Fh(r,e,t){return Mn(Mr(r,e),t)}function Zb(r){return typeof r=="function"}function Pe(r){return Zb(r)?r:()=>r}const aT=()=>{},Kb=r=>r,qb=(r,e)=>e,lT=r=>null,jm=r=>!0,Ym=(r,e)=>r==e,uT=/\.\d*?(?=9{6,}|0{6,})/gm,fs=r=>{if(eC(r)||Bi.has(r))return r;const e=`${r}`,t=e.match(uT);if(t==null)return r;let n=t[0].length-1;if(e.indexOf("e-")!=-1){let[i,s]=e.split("e");return+`${fs(i)}e${s}`}return Je(r,n)};function Ji(r,e){return fs(Je(fs(r/e))*e)}function Lu(r,e){return fs(ln(fs(r/e))*e)}function Qb(r,e){return fs(Qr(fs(r/e))*e)}function Je(r,e=0){if(eC(r))return r;let t=10**e,n=r*t*(1+Number.EPSILON);return Lt(n)/t}const Bi=new Map;function Jb(r){return((""+r).split(".")[1]||"").length}function Ra(r,e,t,n){let i=[],s=n.map(Jb);for(let o=e;o<t;o++){let a=Wt(o),l=Je(co(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),Bi.set(h,d)}}return i}const fa={},lp=[],ho=[null,null],vi=Array.isArray,eC=Number.isInteger,cT=r=>r===void 0;function Gm(r){return typeof r=="string"}function _u(r){let e=!1;if(r!=null){let t=r.constructor;e=t==null||t==Object}return e}function dT(r){return r!=null&&typeof r=="object"}const hT=Object.getPrototypeOf(Uint8Array),tC="__proto__";function fo(r,e=_u){let t;if(vi(r)){let n=r.find(i=>i!=null);if(vi(n)||e(n)){t=Array(r.length);for(let i=0;i<r.length;i++)t[i]=fo(r[i],e)}else t=r.slice()}else if(r instanceof hT)t=r.slice();else if(e(r)){t={};for(let n in r)n!=tC&&(t[n]=fo(r[n],e))}else t=r;return t}function Pt(r){let e=arguments;for(let t=1;t<e.length;t++){let n=e[t];for(let i in n)i!=tC&&(_u(r[i])?Pt(r[i],fo(n[i])):r[i]=fo(n[i]))}return r}const fT=0,pT=1,gT=2;function mT(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 yT(r,e){if(bT(r)){let o=r[0].slice();for(let a=1;a<r.length;a++)o.push(...r[a].slice(1));return CT(o[0])||(o=wT(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]:pT,f=[];for(let p=0;p<c.length;p++){let g=c[p],C=s.get(l[p]);g===null?h!=fT&&(d[C]=g,h==gT&&f.push(C)):d[C]=g}mT(d,f,i),n.push(d)}}return n}const vT=typeof queueMicrotask>"u"?r=>Promise.resolve().then(r):queueMicrotask;function wT(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 bT(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 CT(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 rC=["January","February","March","April","May","June","July","August","September","October","November","December"],nC=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function iC(r){return r.slice(0,3)}const xT=nC.map(iC),IT=rC.map(iC),ST={MMMM:rC,MMM:IT,WWWW:nC,WWW:xT};function Ho(r){return(r<10?"0":"")+r}function kT(r){return(r<10?"00":r<100?"0":"")+r}const ET={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=>Ho(r.getMonth()+1),M:r=>r.getMonth()+1,DD:r=>Ho(r.getDate()),D:r=>r.getDate(),WWWW:(r,e)=>e.WWWW[r.getDay()],WWW:(r,e)=>e.WWW[r.getDay()],HH:r=>Ho(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=>Ho(r.getMinutes()),m:r=>r.getMinutes(),ss:r=>Ho(r.getSeconds()),s:r=>r.getSeconds(),fff:r=>kT(r.getMilliseconds())};function up(r,e){e=e||ST;let t=[],n=/\{([a-z]+)\}|[^{]+/gi,i;for(;i=n.exec(r);)t.push(i[0][0]=="{"?ET[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 MT=new Intl.DateTimeFormat().resolvedOptions().timeZone;function TT(r,e){let t;return e=="UTC"||e=="Etc/UTC"?t=new Date(+r+r.getTimezoneOffset()*6e4):e==MT?t=r:(t=new Date(r.toLocaleString("en-US",{timeZone:e})),t.setMilliseconds(r.getMilliseconds())),t}const sC=r=>r%1==0,gu=[1,2,2.5,5],UT=Ra(10,-32,0,gu),oC=Ra(10,0,32,gu),AT=oC.filter(sC),es=UT.concat(oC),cp=`
|
|
272
|
+
`,aC="{YYYY}",Xm=cp+aC,lC="{M}/{D}",Jo=cp+lC,gl=Jo+"/{YY}",uC="{aa}",RT="{h}:{mm}",Ds=RT+uC,Zm=cp+Ds,Km=":{ss}",je=null;function cC(r){let e=r*1e3,t=e*60,n=t*60,i=n*24,s=i*30,o=i*365,l=(r==1?Ra(10,0,3,gu).filter(sC):Ra(10,-3,0,gu)).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,aC,je,je,je,je,je,je,1],[i*28,"{MMM}",Xm,je,je,je,je,je,1],[i,lC,Xm,je,je,je,je,je,1],[n,"{h}"+uC,gl,je,Jo,je,je,je,1],[t,Ds,gl,je,Jo,je,je,je,1],[e,Km,gl+" "+Ds,je,Jo+" "+Ds,je,Zm,je,1],[r,Km+".{fff}",gl+" "+Ds,je,Jo+" "+Ds,je,Zm,je,1]];function c(d){return(h,f,p,g,C,y)=>{let m=[],v=C>=o,b=C>=s&&C<o,S=d(p),I=Je(S*r,3),E=ad(S.getFullYear(),v?0:S.getMonth(),b||v?1:S.getDate()),U=Je(E*r,3);if(b||v){let z=b?C/s:0,B=v?C/o:0,R=I==U?I:Je(ad(E.getFullYear()+B,E.getMonth()+z,1)*r,3),O=new Date(Lt(R/r)),A=O.getFullYear(),V=O.getMonth();for(let N=0;R<=g;N++){let H=ad(A+B*N,V+z*N,1),P=H-d(Je(H*r,3));R=Je((+H+P)*r,3),R<=g&&m.push(R)}}else{let z=C>=i?i:C,B=Qr(p)-Qr(I),R=U+B+Lu(I-U,z);m.push(R);let O=d(R),A=O.getHours()+O.getMinutes()/t+O.getSeconds()/n,V=C/n,N=h.axes[f]._space,H=y/N;for(;R=Je(R+C,r==1?0:3),!(R>g);)if(V>1){let P=Qr(Je(A+V,6))%24,X=d(R).getHours()-P;X>1&&(X=-1),R-=X*n,A=(A+V)%24;let te=m[m.length-1];Je((R-te)/C,3)*H>=.7&&m.push(R)}else m.push(R)}return m}}return[l,u,c]}const[PT,zT,DT]=cC(1),[OT,BT,FT]=cC(.001);Ra(2,-53,53,[1]);function qm(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 Qm(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 g=r(p),C=g.getFullYear(),y=g.getMonth(),m=g.getDate(),v=g.getHours(),b=g.getMinutes(),S=g.getSeconds(),I=C!=l&&a[2]||y!=u&&a[3]||m!=c&&a[4]||v!=d&&a[5]||b!=h&&a[6]||S!=f&&a[7]||a[1];return l=C,u=y,c=m,d=v,h=b,f=S,I(g)})}}function LT(r,e){let t=up(e);return(n,i,s,o,a)=>i.map(l=>t(r(l)))}function ad(r,e,t){return new Date(r,e,t)}function Jm(r,e){return e(r)}const _T="{YYYY}-{MM}-{DD} {h}:{mm}{aa}";function ey(r,e){return(t,n,i,s)=>s==null?np:e(r(n))}function $T(r,e){let t=r.series[e];return t.width?t.stroke(r,e):t.points.width?t.points.stroke(r,e):null}function NT(r,e){return r.series[e].fill(r,e)}const WT={show:!0,live:!0,isolate:!1,mount:aT,markers:{show:!0,width:2,stroke:$T,fill:NT,dash:"solid"},idx:null,idxs:null,values:[]};function HT(r,e){let t=r.cursor.points,n=an(),i=t.size(r,e);lt(n,qo,i),lt(n,Qo,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 VT(r,e){let t=r.series[e].points;return t._fill||t._stroke}function jT(r,e){let t=r.series[e].points;return t._stroke||t._fill}function YT(r,e){return r.series[e].points.size}const ld=[0,0];function GT(r,e,t){return ld[0]=e,ld[1]=t,ld}function ml(r,e,t,n=!0){return i=>{i.button==0&&(!n||i.target==e)&&t(i)}}function ud(r,e,t,n=!0){return i=>{(!n||i.target==e)&&t(i)}}const XT={show:!0,x:!0,y:!0,lock:!1,move:GT,points:{one:!1,show:HT,size:YT,width:0,stroke:jT,fill:VT},bind:{mousedown:ml,mouseup:ml,click:ml,dblclick:ml,mousemove:ud,mouseleave:ud,mouseenter:ud},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},dC={show:!0,stroke:"rgba(0,0,0,0.07)",width:2},dp=Pt({},dC,{filter:qb}),hC=Pt({},dp,{size:10}),fC=Pt({},dC,{show:!1}),hp='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"',pC="bold "+hp,gC=1.5,ty={show:!0,scale:"x",stroke:rp,space:50,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:pC,side:2,grid:dp,ticks:hC,border:fC,font:hp,lineGap:gC,rotate:0},ZT="Value",KT="Time",ry={show:!0,scale:"x",auto:!1,sorted:1,min:Qe,max:-Qe,idxs:[]};function qT(r,e,t,n,i){return e.map(s=>s==null?"":ap(s))}function QT(r,e,t,n,i,s,o){let a=[],l=Bi.get(i)||0;t=o?t:Je(Lu(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 Lh(r,e,t,n,i,s,o){const a=[],l=r.scales[r.axes[e].scale].log,u=l==10?ti:Xb,c=Qr(u(t));i=co(l,c),l==10&&(i=es[kn(i,es)]);let d=t,h=i*l;l==10&&(h=es[kn(h,es)]);do a.push(d),d=d+i,l==10&&!Bi.has(d)&&(d=Je(d,Bi.get(i))),d>=h&&(i=d,h=i*l,l==10&&(h=es[kn(h,es)]));while(d<=n);return a}function JT(r,e,t,n,i,s,o){let l=r.scales[r.axes[e].scale].asinh,u=n>l?Lh(r,e,Mr(l,t),n,i):[l],c=n>=0&&t<=0?[0]:[];return(t<-l?Lh(r,e,Mr(l,-n),-t,i):[l]).reverse().map(h=>-h).concat(c,u)}const mC=/./,e5=/[12357]/,t5=/[125]/,ny=/1/,_h=(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 r5(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?mC:l(7,o)-c>=u?e5:l(5,o)-c>=u?t5:ny;if(d==ny){let h=Wt(l(1,o)-c);if(h<u)return _h(e.slice().reverse(),a.distr,d,ln(u/h)).reverse()}return _h(e,a.distr,d,1)}function n5(r,e,t,n,i){let s=r.axes[t],o=s.scale,a=s._space,l=r.valToPos,u=Wt(l(1,o)-l(2,o));return u<a?_h(e.slice().reverse(),3,mC,ln(a/u)).reverse():e}function i5(r,e,t,n){return n==null?np:e==null?"":ap(e)}const iy={show:!0,scale:"y",stroke:rp,space:30,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:pC,side:3,grid:dp,ticks:hC,border:fC,font:hp,lineGap:gC,rotate:0};function s5(r,e){let t=3+(r||1)*2;return Je(t*e,3)}function o5(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=Wt(o-s),l=r.series[e],u=a/(l.points.space*Ve);return n[1]-n[0]<=u}const sy={scale:null,auto:!0,sorted:0,min:Qe,max:-Qe},yC=(r,e,t,n,i)=>i,oy={show:!0,auto:!0,sorted:0,gaps:yC,alpha:1,facets:[Pt({},sy,{scale:"x"}),Pt({},sy,{scale:"y"})]},ay={scale:"y",auto:!0,sorted:0,show:!0,spanGaps:!1,gaps:yC,alpha:1,points:{show:o5,filter:null},values:null,min:Qe,max:-Qe,idxs:[],path:null,clip:null};function a5(r,e,t,n,i){return t/10}const vC={time:PM,auto:!0,distr:1,log:10,asinh:1,min:null,max:null,dir:1,ori:0},l5=Pt({},vC,{time:!1,ori:1}),ly={};function wC(r,e){let t=ly[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&&(ly[r]=t)),t}const po=1,$h=2;function ms(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,g=a.height,C=r.valToPosH,y=r.valToPosV;return c.ori==0?t(i,l,u,c,d,C,y,h,f,p,g,Nu,Co,Hu,CC,IC):t(i,l,u,c,d,y,C,f,h,g,p,Wu,xo,gp,xC,SC)}function fp(r,e){let t=0,n=0,i=_e(r.bands,lp);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 u5(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 ri(r,e,t,n,i,s){return ms(r,e,(o,a,l,u,c,d,h,f,p,g,C)=>{let y=o.pxRound;const m=u.dir*(u.ori==0?1:-1),v=u.ori==0?Co:xo;let b,S;m==1?(b=t,S=n):(b=n,S=t);let I=y(d(a[b],u,g,f)),E=y(h(l[b],c,C,p)),U=y(d(a[S],u,g,f)),z=y(h(s==1?c.max:c.min,c,C,p)),B=new Path2D(i);return v(B,U,z),v(B,I,z),v(B,I,E),B})}function $u(r,e,t,n,i,s){let o=null;if(r.length>0){o=new Path2D;const a=e==0?Hu:gp;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 c5(r,e,t){let n=r[r.length-1];n&&n[0]==e?n[1]=t:r.push([e,t])}function pp(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]),g=d-i;f=o<=0&&g>=0&&g<l?s(r[g]):f;let y=h+i;p=o>=0&&y>=0&&y<l?s(r[y]):p,p>=f&&a.push([f,p])}return a}function uy(r){return r==0?Kb:r==1?Lt:e=>Ji(e,r)}function bC(r){let e=r==0?Nu:Wu,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=Mn(u,a/2,l/2),c=Mn(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 Nu=(r,e,t)=>{r.moveTo(e,t)},Wu=(r,e,t)=>{r.moveTo(t,e)},Co=(r,e,t)=>{r.lineTo(e,t)},xo=(r,e,t)=>{r.lineTo(t,e)},Hu=bC(0),gp=bC(1),CC=(r,e,t,n,i,s)=>{r.arc(e,t,n,i,s)},xC=(r,e,t,n,i,s)=>{r.arc(t,e,n,i,s)},IC=(r,e,t,n,i,s,o)=>{r.bezierCurveTo(e,t,n,i,s,o)},SC=(r,e,t,n,i,s,o)=>{r.bezierCurveTo(t,e,i,n,o,s)};function kC(r){return(e,t,n,i,s)=>ms(e,t,(o,a,l,u,c,d,h,f,p,g,C)=>{let{pxRound:y,points:m}=o,v,b;u.ori==0?(v=Nu,b=CC):(v=Wu,b=xC);const S=Je(m.width*Ve,3);let I=(m.size-m.width)/2*Ve,E=Je(I*2,3),U=new Path2D,z=new Path2D,{left:B,top:R,width:O,height:A}=e.bbox;Hu(z,B-E,R-E,O+E*2,A+E*2);const V=N=>{if(l[N]!=null){let H=y(d(a[N],u,g,f)),P=y(h(l[N],c,C,p));v(U,H+I,P),b(U,H,P,I,0,Ll*2)}};if(s)s.forEach(V);else for(let N=n;N<=i;N++)V(N);return{stroke:S>0?U:null,fill:U,clip:z,flags:po|$h}})}function EC(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 d5=EC(Co),h5=EC(xo);function MC(r){const e=_e(r==null?void 0:r.alignGaps,0);return(t,n,i,s)=>ms(t,n,(o,a,l,u,c,d,h,f,p,g,C)=>{[i,s]=Bu(l,i,s);let y=o.pxRound,m=A=>y(d(A,u,g,f)),v=A=>y(h(A,c,C,p)),b,S;u.ori==0?(b=Co,S=d5):(b=xo,S=h5);const I=u.dir*(u.ori==0?1:-1),E={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:po},U=E.stroke;let z=!1;if(s-i>=g*4){let A=Z=>t.posToVal(Z,u.key,!0),V=null,N=null,H,P,W,j=m(a[I==1?i:s]),X=m(a[i]),te=m(a[s]),Q=A(I==1?X+1:te-1);for(let Z=I==1?i:s;Z>=i&&Z<=s;Z+=I){let se=a[Z],ge=(I==1?se<Q:se>Q)?j:m(se),be=l[Z];ge==j?be!=null?(P=be,V==null?(b(U,ge,v(P)),H=V=N=P):P<V?V=P:P>N&&(N=P)):be===null&&(z=!0):(V!=null&&S(U,j,v(V),v(N),v(H),v(P)),be!=null?(P=be,b(U,ge,v(P)),V=N=H=P):(V=N=null,be===null&&(z=!0)),j=ge,Q=A(j+I))}V!=null&&V!=N&&W!=j&&S(U,j,v(V),v(N),v(H),v(P))}else for(let A=I==1?i:s;A>=i&&A<=s;A+=I){let V=l[A];V===null?z=!0:V!=null&&b(U,m(a[A]),v(V))}let[R,O]=fp(t,n);if(o.fill!=null||R!=0){let A=E.fill=new Path2D(U),V=o.fillTo(t,n,o.min,o.max,R),N=v(V),H=m(a[i]),P=m(a[s]);I==-1&&([P,H]=[H,P]),b(A,P,N),b(A,H,N)}if(!o.spanGaps){let A=[];z&&A.push(...pp(a,l,i,s,I,m,e)),E.gaps=A=o.gaps(t,n,i,s,A),E.clip=$u(A,u.ori,f,p,g,C)}return O!=0&&(E.band=O==2?[ri(t,n,i,s,U,-1),ri(t,n,i,s,U,1)]:ri(t,n,i,s,U,O)),E})}function f5(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)=>ms(s,o,(u,c,d,h,f,p,g,C,y,m,v)=>{[a,l]=Bu(d,a,l);let b=u.pxRound,{left:S,width:I}=s.bbox,E=X=>b(p(X,h,m,C)),U=X=>b(g(X,f,v,y)),z=h.ori==0?Co:xo;const B={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:po},R=B.stroke,O=h.dir*(h.ori==0?1:-1);let A=U(d[O==1?a:l]),V=E(c[O==1?a:l]),N=V,H=V;i&&e==-1&&(H=S,z(R,H,A)),z(R,V,A);for(let X=O==1?a:l;X>=a&&X<=l;X+=O){let te=d[X];if(te==null)continue;let Q=E(c[X]),Z=U(te);e==1?z(R,Q,A):z(R,N,Z),z(R,Q,Z),A=Z,N=Q}let P=N;i&&e==1&&(P=S+I,z(R,P,A));let[W,j]=fp(s,o);if(u.fill!=null||W!=0){let X=B.fill=new Path2D(R),te=u.fillTo(s,o,u.min,u.max,W),Q=U(te);z(X,P,Q),z(X,H,Q)}if(!u.spanGaps){let X=[];X.push(...pp(c,d,a,l,O,E,n));let te=u.width*Ve/2,Q=t||e==1?te:-te,Z=t||e==-1?-te:te;X.forEach(se=>{se[0]+=Q,se[1]+=Z}),B.gaps=X=u.gaps(s,o,a,l,X),B.clip=$u(X,h.ori,C,y,m,v)}return j!=0&&(B.band=j==2?[ri(s,o,a,l,R,-1),ri(s,o,a,l,R,1)]:ri(s,o,a,l,R,j)),B})}function cy(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=Wt(r[l]-r[a]);c<u&&(u=c,o=Wt(t(r[l],n,i,s)-t(r[a],n,i,s)))}a=l}}return o}function p5(r){r=r||fa;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,fa),c=_e(r.each,f=>{}),{fill:d,stroke:h}=u;return(f,p,g,C)=>ms(f,p,(y,m,v,b,S,I,E,U,z,B,R)=>{let O=y.pxRound,A=t,V=n*Ve,N=a*Ve,H=l*Ve,P,W;b.ori==0?[P,W]=s(f,p):[W,P]=s(f,p);const j=b.dir*(b.ori==0?1:-1);let X=b.ori==0?Hu:gp,te=b.ori==0?c:(ie,$e,ht,J,G,le,ye)=>{c(ie,$e,ht,G,J,ye,le)},Q=_e(f.bands,lp).find(ie=>ie.series[0]==p),Z=Q!=null?Q.dir:0,se=y.fillTo(f,p,y.min,y.max,Z),ve=O(E(se,S,R,z)),ge,be,ct,dt=B,Ie=O(y.width*Ve),et=!1,Ze=null,qe=null,Mt=null,mt=null;d!=null&&(Ie==0||h!=null)&&(et=!0,Ze=d.values(f,p,g,C),qe=new Map,new Set(Ze).forEach(ie=>{ie!=null&&qe.set(ie,new Path2D)}),Ie>0&&(Mt=h.values(f,p,g,C),mt=new Map,new Set(Mt).forEach(ie=>{ie!=null&&mt.set(ie,new Path2D)})));let{x0:Ot,size:dr}=u;if(Ot!=null&&dr!=null){A=1,m=Ot.values(f,p,g,C),Ot.unit==2&&(m=m.map(ht=>f.posToVal(U+ht*B,b.key,!0)));let ie=dr.values(f,p,g,C);dr.unit==2?be=ie[0]*B:be=I(ie[0],b,B,U)-I(0,b,B,U),dt=cy(m,v,I,b,B,U,dt),ct=dt-be+V}else dt=cy(m,v,I,b,B,U,dt),ct=dt*o+V,be=dt-ct;ct<1&&(ct=0),Ie>=be/2&&(Ie=0),ct<5&&(O=Kb);let tt=ct>0,xt=dt-ct-(tt?Ie:0);be=O(Fh(xt,H,N)),ge=(A==0?be/2:A==j?0:be)-A*j*((A==0?V/2:0)+(tt?Ie/2:0));const nt={stroke:null,fill:null,clip:null,band:null,gaps:null,flags:0},br=et?null:new Path2D;let xe=null;if(Q!=null)xe=f.data[Q.series[1]];else{let{y0:ie,y1:$e}=u;ie!=null&&$e!=null&&(v=$e.values(f,p,g,C),xe=ie.values(f,p,g,C))}let Re=P*be,pe=W*be;for(let ie=j==1?g:C;ie>=g&&ie<=C;ie+=j){let $e=v[ie];if($e==null)continue;if(xe!=null){let Ee=xe[ie]??0;if($e-Ee==0)continue;ve=E(Ee,S,R,z)}let ht=b.distr!=2||u!=null?m[ie]:ie,J=I(ht,b,B,U),G=E(_e($e,se),S,R,z),le=O(J-ge),ye=O(Mr(G,ve)),de=O(Mn(G,ve)),Te=ye-de;if($e!=null){let Ee=$e<0?pe:Re,Me=$e<0?Re:pe;et?(Ie>0&&Mt[ie]!=null&&X(mt.get(Mt[ie]),le,de+Qr(Ie/2),be,Mr(0,Te-Ie),Ee,Me),Ze[ie]!=null&&X(qe.get(Ze[ie]),le,de+Qr(Ie/2),be,Mr(0,Te-Ie),Ee,Me)):X(br,le,de+Qr(Ie/2),be,Mr(0,Te-Ie),Ee,Me),te(f,p,ie,le-Ie/2,de,be+Ie,Te)}}return Ie>0?nt.stroke=et?mt:br:et||(nt._fill=y.width==0?y._fill:y._stroke??y._fill,nt.width=0),nt.fill=et?qe:br,nt})}function g5(r,e){const t=_e(e==null?void 0:e.alignGaps,0);return(n,i,s,o)=>ms(n,i,(a,l,u,c,d,h,f,p,g,C,y)=>{[s,o]=Bu(u,s,o);let m=a.pxRound,v=P=>m(h(P,c,C,p)),b=P=>m(f(P,d,y,g)),S,I,E;c.ori==0?(S=Nu,E=Co,I=IC):(S=Wu,E=xo,I=SC);const U=c.dir*(c.ori==0?1:-1);let z=v(l[U==1?s:o]),B=z,R=[],O=[];for(let P=U==1?s:o;P>=s&&P<=o;P+=U)if(u[P]!=null){let j=l[P],X=v(j);R.push(B=X),O.push(b(u[P]))}const A={stroke:r(R,O,S,E,I,m),fill:null,clip:null,band:null,gaps:null,flags:po},V=A.stroke;let[N,H]=fp(n,i);if(a.fill!=null||N!=0){let P=A.fill=new Path2D(V),W=a.fillTo(n,i,a.min,a.max,N),j=b(W);E(P,B,j),E(P,z,j)}if(!a.spanGaps){let P=[];P.push(...pp(l,u,s,o,U,v,t)),A.gaps=P=a.gaps(n,i,s,o,P),A.clip=$u(P,c.ori,p,g,C,y)}return H!=0&&(A.band=H==2?[ri(n,i,s,o,V,-1),ri(n,i,s,o,V,1)]:ri(n,i,s,o,V,H)),A})}function m5(r){return g5(y5,r)}function y5(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 Nh=new Set;function dy(){for(let r of Nh)r.syncRect(!0)}bo&&(as(qM,to,dy),as(QM,to,dy,!0),as(fu,to,()=>{yr.pxRatio=Ve}));const v5=MC(),w5=kC();function hy(r,e,t,n){return(n?[r[0],r[1]].concat(r.slice(2)):[r[0]].concat(r.slice(1))).map((s,o)=>Wh(s,o,e,t))}function b5(r,e){return r.map((t,n)=>n==0?{}:Pt({},e,t))}function Wh(r,e,t,n){return Pt({},e==0?t:n,r)}function TC(r,e,t){return e==null?ho:[e,t]}const C5=TC;function x5(r,e,t){return e==null?ho:pu(e,t,op,!0)}function UC(r,e,t,n){return e==null?ho:Fu(e,t,r.scales[n].log,!1)}const I5=UC;function AC(r,e,t,n){return e==null?ho:sp(e,t,r.scales[n].log,!1)}const S5=AC;function k5(r,e,t,n,i){let s=Mr(Vm(r),Vm(e)),o=e-r,a=kn(i/n*o,t);do{let l=t[a],u=n*l/o;if(u>=i&&s+(l<5?Bi.get(l):0)<=17)return[l,u]}while(++a<t.length);return[0,0]}function fy(r){let e,t;return r=r.replace(/(\d+)px/,(n,i)=>(e=Lt((t=+i)*Ve))+"px"),[r,e,t]}function E5(r){r.show&&[r.font,r.labelFont].forEach(e=>{let t=Je(e[2]*Ve,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(w,x,M,T){let D=x.valToPct(w);return T+M*(x.dir==-1?1-D:D)}function o(w,x,M,T){let D=x.valToPct(w);return T+M*(x.dir==-1?D:1-D)}function a(w,x,M,T){return x.ori==0?s(w,x,M,T):o(w,x,M,T)}n.valToPosH=s,n.valToPosV=o;let l=!1;n.status=0;const u=n.root=an(zM);if(r.id!=null&&(u.id=r.id),Gr(u,r.class),r.title){let w=an(BM,u);w.textContent=r.title}const c=Cn("canvas"),d=n.ctx=c.getContext("2d"),h=an(FM,u);as("click",h,w=>{w.target===p&&(it!=Is||pt!=Ss)&&ir.click(n,w)},!0);const f=n.under=an(LM,h);h.appendChild(c);const p=n.over=an(_M,h);r=fo(r);const g=+_e(r.pxAlign,1),C=uy(g);(r.plugins||[]).forEach(w=>{w.opts&&(r=w.opts(n,r)||r)});const y=r.ms||.001,m=n.series=i==1?hy(r.series||[],ry,ay,!1):b5(r.series||[null],oy),v=n.axes=hy(r.axes||[],ty,iy,!0),b=n.scales={},S=n.bands=r.bands||[];S.forEach(w=>{w.fill=Pe(w.fill||null),w.dir=_e(w.dir,-1)});const I=i==2?m[1].facets[0].scale:m[0].scale,E={axes:HC,series:LC},U=(r.drawOrder||["axes","series"]).map(w=>E[w]);function z(w){const x=w.distr==3?M=>ti(M>0?M:w.clamp(n,M,w.min,w.max,w.key)):w.distr==4?M=>od(M,w.asinh):w.distr==100?M=>w.fwd(M):M=>M;return M=>{let T=x(M),{_min:D,_max:_}=w,Y=_-D;return(T-D)/Y}}function B(w){let x=b[w];if(x==null){let M=(r.scales||fa)[w]||fa;if(M.from!=null){B(M.from);let T=Pt({},b[M.from],M,{key:w});T.valToPct=z(T),b[w]=T}else{x=b[w]=Pt({},w==I?vC:l5,M),x.key=w;let T=x.time,D=x.range,_=vi(D);if((w!=I||i==2&&!T)&&(_&&(D[0]==null||D[1]==null)&&(D={min:D[0]==null?Nm:{mode:1,hard:D[0],soft:D[0]},max:D[1]==null?Nm:{mode:1,hard:D[1],soft:D[1]}},_=!1),!_&&_u(D))){let Y=D;D=(q,re,ae)=>re==null?ho:pu(re,ae,Y)}x.range=Pe(D||(T?C5:w==I?x.distr==3?I5:x.distr==4?S5:TC:x.distr==3?UC:x.distr==4?AC:x5)),x.auto=Pe(_?!1:x.auto),x.clamp=Pe(x.clamp||a5),x._min=x._max=null,x.valToPct=z(x)}}}B("x"),B("y"),i==1&&m.forEach(w=>{B(w.scale)}),v.forEach(w=>{B(w.scale)});for(let w in r.scales)B(w);const R=b[I],O=R.distr;let A,V;R.ori==0?(Gr(u,DM),A=s,V=o):(Gr(u,OM),A=o,V=s);const N={};for(let w in b){let x=b[w];(x.min!=null||x.max!=null)&&(N[w]={min:x.min,max:x.max},x.min=x.max=null)}const H=r.tzDate||(w=>new Date(Lt(w/y))),P=r.fmtDate||up,W=y==1?DT(H):FT(H),j=Qm(H,qm(y==1?zT:BT,P)),X=ey(H,Jm(_T,P)),te=[],Q=n.legend=Pt({},WT,r.legend),Z=n.cursor=Pt({},XT,{drag:{y:i==2}},r.cursor),se=Q.show,ve=Z.show,ge=Q.markers;Q.idxs=te,ge.width=Pe(ge.width),ge.dash=Pe(ge.dash),ge.stroke=Pe(ge.stroke),ge.fill=Pe(ge.fill);let be,ct,dt,Ie=[],et=[],Ze,qe=!1,Mt={};if(Q.live){const w=m[1]?m[1].values:null;qe=w!=null,Ze=qe?w(n,1,0):{_:0};for(let x in Ze)Mt[x]=np}if(se)if(be=Cn("table",jM,u),dt=Cn("tbody",null,be),Q.mount(n,be),qe){ct=Cn("thead",null,be,dt);let w=Cn("tr",null,ct);Cn("th",null,w);for(var mt in Ze)Cn("th",Tm,w).textContent=mt}else Gr(be,GM),Q.live&&Gr(be,YM);const Ot={show:!0},dr={show:!1};function tt(w,x){if(x==0&&(qe||!Q.live||i==2))return ho;let M=[],T=Cn("tr",XM,dt,dt.childNodes[x]);Gr(T,w.class),w.show||Gr(T,ts);let D=Cn("th",null,T);if(ge.show){let q=an(ZM,D);if(x>0){let re=ge.width(n,x);re&&(q.style.border=re+"px "+ge.dash(n,x)+" "+ge.stroke(n,x)),q.style.background=ge.fill(n,x)}}let _=an(Tm,D);w.label instanceof HTMLElement?_.appendChild(w.label):_.textContent=w.label,x>0&&(ge.show||(_.style.color=w.width>0?ge.stroke(n,x):ge.fill(n,x)),nt("click",D,q=>{if(Z._lock)return;Pr(q);let re=m.indexOf(w);if((q.ctrlKey||q.metaKey)!=Q.isolate){let ae=m.some((ue,he)=>he>0&&he!=re&&ue.show);m.forEach((ue,he)=>{he>0&&On(he,ae?he==re?Ot:dr:Ot,!0,Rt.setSeries)})}else On(re,{show:!w.show},!0,Rt.setSeries)},!1),Rn&&nt(Pm,D,q=>{Z._lock||(Pr(q),On(m.indexOf(w),Es,!0,Rt.setSeries))},!1));for(var Y in Ze){let q=Cn("td",KM,T);q.textContent="--",M.push(q)}return[T,M]}const xt=new Map;function nt(w,x,M,T=!0){const D=xt.get(x)||{},_=Z.bind[w](n,x,M,T);_&&(as(w,x,D[w]=_),xt.set(x,D))}function br(w,x,M){const T=xt.get(x)||{};for(let D in T)(w==null||D==w)&&(Bh(D,x,T[D]),delete T[D]);w==null&&xt.delete(x)}let xe=0,Re=0,pe=0,ie=0,$e=0,ht=0,J=$e,G=ht,le=pe,ye=ie,de=0,Te=0,Ee=0,Me=0;n.bbox={};let Ne=!1,we=!1,Be=!1,Tt=!1,ft=!1,We=!1;function Yt(w,x,M){(M||w!=n.width||x!=n.height)&&Bt(w,x),ws(!1),Be=!0,we=!0,bs()}function Bt(w,x){n.width=xe=pe=w,n.height=Re=ie=x,$e=ht=0,Fe(),Wi();let M=n.bbox;de=M.left=Ji($e*Ve,.5),Te=M.top=Ji(ht*Ve,.5),Ee=M.width=Ji(pe*Ve,.5),Me=M.height=Ji(ie*Ve,.5)}const li=3;function $i(){let w=!1,x=0;for(;!w;){x++;let M=NC(x),T=WC(x);w=x==li||M&&T,w||(Bt(n.width,n.height),we=!0)}}function Ni({width:w,height:x}){Yt(w,x)}n.setSize=Ni;function Fe(){let w=!1,x=!1,M=!1,T=!1;v.forEach((D,_)=>{if(D.show&&D._show){let{side:Y,_size:q}=D,re=Y%2,ae=D.label!=null?D.labelSize:0,ue=q+ae;ue>0&&(re?(pe-=ue,Y==3?($e+=ue,T=!0):M=!0):(ie-=ue,Y==0?(ht+=ue,w=!0):x=!0))}}),Vi[0]=w,Vi[1]=M,Vi[2]=x,Vi[3]=T,pe-=ui[1]+ui[3],$e+=ui[3],ie-=ui[2]+ui[0],ht+=ui[0]}function Wi(){let w=$e+pe,x=ht+ie,M=$e,T=ht;function D(_,Y){switch(_){case 1:return w+=Y,w-Y;case 2:return x+=Y,x-Y;case 3:return M-=Y,M+Y;case 0:return T-=Y,T+Y}}v.forEach((_,Y)=>{if(_.show&&_._show){let q=_.side;_._pos=D(q,_._size),_.label!=null&&(_._lpos=D(q,_.labelSize))}})}if(Z.dataIdx==null){let w=Z.hover,x=w.skip=new Set(w.skip??[]);x.add(void 0);let M=w.prox=Pe(w.prox),T=w.bias??(w.bias=0);Z.dataIdx=(D,_,Y,q)=>{if(_==0)return Y;let re=Y,ae=M(D,_,Y,q)??Qe,ue=ae>=0&&ae<Qe,he=R.ori==0?pe:ie,Se=Z.left,He=e[0],Le=e[_];if(x.has(Le[Y])){re=null;let Ue=null,Ce=null,me;if(T==0||T==-1)for(me=Y;Ue==null&&me-- >0;)x.has(Le[me])||(Ue=me);if(T==0||T==1)for(me=Y;Ce==null&&me++<Le.length;)x.has(Le[me])||(Ce=me);if(Ue!=null||Ce!=null)if(ue){let ot=Ue==null?-1/0:A(He[Ue],R,he,0),It=Ce==null?1/0:A(He[Ce],R,he,0),Qt=Se-ot,Ke=It-Se;Qt<=Ke?Qt<=ae&&(re=Ue):Ke<=ae&&(re=Ce)}else re=Ce==null?Ue:Ue==null?Ce:Y-Ue<=Ce-Y?Ue:Ce}else ue&&Wt(Se-A(He[Y],R,he,0))>ae&&(re=null);return re}}const Pr=w=>{Z.event=w};Z.idxs=te,Z._lock=!1;let yt=Z.points;yt.show=Pe(yt.show),yt.size=Pe(yt.size),yt.stroke=Pe(yt.stroke),yt.width=Pe(yt.width),yt.fill=Pe(yt.fill);const hr=n.focus=Pt({},r.focus||{alpha:.3},Z.focus),Rn=hr.prox>=0,Pn=Rn&&yt.one;let fr=[],zn=[],Dn=[];function ys(w,x){let M=yt.show(n,x);if(M instanceof HTMLElement)return Gr(M,VM),Gr(M,w.class),$n(M,-10,-10,pe,ie),p.insertBefore(M,fr[x]),M}function At(w,x){if(i==1||x>0){let M=i==1&&b[w.scale].time,T=w.value;w.value=M?Gm(T)?ey(H,Jm(T,P)):T||X:T||i5,w.label=w.label||(M?KT:ZT)}if(Pn||x>0){w.width=w.width==null?1:w.width,w.paths=w.paths||v5||lT,w.fillTo=Pe(w.fillTo||u5),w.pxAlign=+_e(w.pxAlign,g),w.pxRound=uy(w.pxAlign),w.stroke=Pe(w.stroke||null),w.fill=Pe(w.fill||null),w._stroke=w._fill=w._paths=w._focus=null;let M=s5(Mr(1,w.width),1),T=w.points=Pt({},{size:M,width:Mr(1,M*.2),stroke:w.stroke,space:M*2,paths:w5,_stroke:null,_fill:null},w.points);T.show=Pe(T.show),T.filter=Pe(T.filter),T.fill=Pe(T.fill),T.stroke=Pe(T.stroke),T.paths=Pe(T.paths),T.pxAlign=w.pxAlign}if(se){let M=tt(w,x);Ie.splice(x,0,M[0]),et.splice(x,0,M[1]),Q.values.push(null)}if(ve){te.splice(x,0,null);let M=null;Pn?x==0&&(M=ys(w,x)):x>0&&(M=ys(w,x)),fr.splice(x,0,M),zn.splice(x,0,0),Dn.splice(x,0,0)}qt("addSeries",x)}function vt(w,x){x=x??m.length,w=i==1?Wh(w,x,ry,ay):Wh(w,x,{},oy),m.splice(x,0,w),At(m[x],x)}n.addSeries=vt;function Hi(w){if(m.splice(w,1),se){Q.values.splice(w,1),et.splice(w,1);let x=Ie.splice(w,1)[0];br(null,x.firstChild),x.remove()}ve&&(te.splice(w,1),fr.splice(w,1)[0].remove(),zn.splice(w,1),Dn.splice(w,1)),qt("delSeries",w)}n.delSeries=Hi;const Vi=[!1,!1,!1,!1];function OC(w,x){if(w._show=w.show,w.show){let M=w.side%2,T=b[w.scale];T==null&&(w.scale=M?m[1].scale:I,T=b[w.scale]);let D=T.time;w.size=Pe(w.size),w.space=Pe(w.space),w.rotate=Pe(w.rotate),vi(w.incrs)&&w.incrs.forEach(Y=>{!Bi.has(Y)&&Bi.set(Y,Jb(Y))}),w.incrs=Pe(w.incrs||(T.distr==2?AT:D?y==1?PT:OT:es)),w.splits=Pe(w.splits||(D&&T.distr==1?W:T.distr==3?Lh:T.distr==4?JT:QT)),w.stroke=Pe(w.stroke),w.grid.stroke=Pe(w.grid.stroke),w.ticks.stroke=Pe(w.ticks.stroke),w.border.stroke=Pe(w.border.stroke);let _=w.values;w.values=vi(_)&&!vi(_[0])?Pe(_):D?vi(_)?Qm(H,qm(_,P)):Gm(_)?LT(H,_):_||j:_||qT,w.filter=Pe(w.filter||(T.distr>=3&&T.log==10?r5:T.distr==3&&T.log==2?n5:qb)),w.font=fy(w.font),w.labelFont=fy(w.labelFont),w._size=w.size(n,null,x,0),w._space=w._rotate=w._incrs=w._found=w._splits=w._values=null,w._size>0&&(Vi[x]=!0,w._el=an($M,h))}}function So(w,x,M,T){let[D,_,Y,q]=M,re=x%2,ae=0;return re==0&&(q||_)&&(ae=x==0&&!D||x==2&&!Y?Lt(ty.size/3):0),re==1&&(D||Y)&&(ae=x==1&&!_||x==3&&!q?Lt(iy.size/2):0),ae}const vp=n.padding=(r.padding||[So,So,So,So]).map(w=>Pe(_e(w,So))),ui=n._padding=vp.map((w,x)=>w(n,x,Vi,0));let nr,Gt=null,Xt=null;const Na=i==1?m[0].idxs:null;let mn=null,ko=!1;function wp(w,x){if(e=w??[],n.data=n._data=e,i==2){nr=0;for(let M=1;M<m.length;M++)nr+=e[M][0].length}else{e.length==0&&(n.data=n._data=e=[[]]),mn=e[0],nr=mn.length;let M=e;if(O==2){M=e.slice();let T=M[0]=Array(nr);for(let D=0;D<nr;D++)T[D]=D}n._data=e=M}if(ws(!0),qt("setData"),O==2&&(Be=!0),x!==!1){let M=R;M.auto(n,ko)?Vu():di(I,M.min,M.max),Tt=Tt||Z.left>=0,We=!0,bs()}}n.setData=wp;function Vu(){ko=!0;let w,x;i==1&&(nr>0?(Gt=Na[0]=0,Xt=Na[1]=nr-1,w=e[0][Gt],x=e[0][Xt],O==2?(w=Gt,x=Xt):w==x&&(O==3?[w,x]=Fu(w,w,R.log,!1):O==4?[w,x]=sp(w,w,R.log,!1):R.time?x=w+Lt(86400/y):[w,x]=pu(w,x,op,!0))):(Gt=Na[0]=w=null,Xt=Na[1]=x=null)),di(I,w,x)}let Wa,vs,ju,Yu,Gu,Xu,Zu,Ku,qu,zr;function bp(w,x,M,T,D,_){w??(w=Am),M??(M=lp),T??(T="butt"),D??(D=Am),_??(_="round"),w!=Wa&&(d.strokeStyle=Wa=w),D!=vs&&(d.fillStyle=vs=D),x!=ju&&(d.lineWidth=ju=x),_!=Gu&&(d.lineJoin=Gu=_),T!=Xu&&(d.lineCap=Xu=T),M!=Yu&&d.setLineDash(Yu=M)}function Cp(w,x,M,T){x!=vs&&(d.fillStyle=vs=x),w!=Zu&&(d.font=Zu=w),M!=Ku&&(d.textAlign=Ku=M),T!=qu&&(d.textBaseline=qu=T)}function Qu(w,x,M,T,D=0){if(T.length>0&&w.auto(n,ko)&&(x==null||x.min==null)){let _=_e(Gt,0),Y=_e(Xt,T.length-1),q=M.min==null?rT(T,_,Y,D,w.distr==3):[M.min,M.max];w.min=Mn(w.min,M.min=q[0]),w.max=Mr(w.max,M.max=q[1])}}const xp={min:null,max:null};function BC(){for(let T in b){let D=b[T];N[T]==null&&(D.min==null||N[I]!=null&&D.auto(n,ko))&&(N[T]=xp)}for(let T in b){let D=b[T];N[T]==null&&D.from!=null&&N[D.from]!=null&&(N[T]=xp)}N[I]!=null&&ws(!0);let w={};for(let T in N){let D=N[T];if(D!=null){let _=w[T]=fo(b[T],dT);if(D.min!=null)Pt(_,D);else if(T!=I||i==2)if(nr==0&&_.from==null){let Y=_.range(n,null,null,T);_.min=Y[0],_.max=Y[1]}else _.min=Qe,_.max=-Qe}}if(nr>0){m.forEach((T,D)=>{if(i==1){let _=T.scale,Y=N[_];if(Y==null)return;let q=w[_];if(D==0){let re=q.range(n,q.min,q.max,_);q.min=re[0],q.max=re[1],Gt=kn(q.min,e[0]),Xt=kn(q.max,e[0]),Xt-Gt>1&&(e[0][Gt]<q.min&&Gt++,e[0][Xt]>q.max&&Xt--),T.min=mn[Gt],T.max=mn[Xt]}else T.show&&T.auto&&Qu(q,Y,T,e[D],T.sorted);T.idxs[0]=Gt,T.idxs[1]=Xt}else if(D>0&&T.show&&T.auto){let[_,Y]=T.facets,q=_.scale,re=Y.scale,[ae,ue]=e[D],he=w[q],Se=w[re];he!=null&&Qu(he,N[q],_,ae,_.sorted),Se!=null&&Qu(Se,N[re],Y,ue,Y.sorted),T.min=Y.min,T.max=Y.max}});for(let T in w){let D=w[T],_=N[T];if(D.from==null&&(_==null||_.min==null)){let Y=D.range(n,D.min==Qe?null:D.min,D.max==-Qe?null:D.max,T);D.min=Y[0],D.max=Y[1]}}}for(let T in w){let D=w[T];if(D.from!=null){let _=w[D.from];if(_.min==null)D.min=D.max=null;else{let Y=D.range(n,_.min,_.max,T);D.min=Y[0],D.max=Y[1]}}}let x={},M=!1;for(let T in w){let D=w[T],_=b[T];if(_.min!=D.min||_.max!=D.max){_.min=D.min,_.max=D.max;let Y=_.distr;_._min=Y==3?ti(_.min):Y==4?od(_.min,_.asinh):Y==100?_.fwd(_.min):_.min,_._max=Y==3?ti(_.max):Y==4?od(_.max,_.asinh):Y==100?_.fwd(_.max):_.max,x[T]=M=!0}}if(M){m.forEach((T,D)=>{i==2?D>0&&x.y&&(T._paths=null):x[T.scale]&&(T._paths=null)});for(let T in x)Be=!0,qt("setScale",T);ve&&Z.left>=0&&(Tt=We=!0)}for(let T in N)N[T]=null}function FC(w){let x=Fh(Gt-1,0,nr-1),M=Fh(Xt+1,0,nr-1);for(;w[x]==null&&x>0;)x--;for(;w[M]==null&&M<nr-1;)M++;return[x,M]}function LC(){if(nr>0){let w=m.some(x=>x._focus)&&zr!=hr.alpha;w&&(d.globalAlpha=zr=hr.alpha),m.forEach((x,M)=>{if(M>0&&x.show&&(Ip(M,!1),Ip(M,!0),x._paths==null)){let T=zr;zr!=x.alpha&&(d.globalAlpha=zr=x.alpha);let D=i==2?[0,e[M][0].length-1]:FC(e[M]);x._paths=x.paths(n,M,D[0],D[1]),zr!=T&&(d.globalAlpha=zr=T)}}),m.forEach((x,M)=>{if(M>0&&x.show){let T=zr;zr!=x.alpha&&(d.globalAlpha=zr=x.alpha),x._paths!=null&&Sp(M,!1);{let D=x._paths!=null?x._paths.gaps:null,_=x.points.show(n,M,Gt,Xt,D),Y=x.points.filter(n,M,_,D);(_||Y)&&(x.points._paths=x.points.paths(n,M,Gt,Xt,Y),Sp(M,!0))}zr!=T&&(d.globalAlpha=zr=T),qt("drawSeries",M)}}),w&&(d.globalAlpha=zr=1)}}function Ip(w,x){let M=x?m[w].points:m[w];M._stroke=M.stroke(n,w),M._fill=M.fill(n,w)}function Sp(w,x){let M=x?m[w].points:m[w],{stroke:T,fill:D,clip:_,flags:Y,_stroke:q=M._stroke,_fill:re=M._fill,_width:ae=M.width}=M._paths;ae=Je(ae*Ve,3);let ue=null,he=ae%2/2;x&&re==null&&(re=ae>0?"#fff":q);let Se=M.pxAlign==1&&he>0;if(Se&&d.translate(he,he),!x){let He=de-ae/2,Le=Te-ae/2,Ue=Ee+ae,Ce=Me+ae;ue=new Path2D,ue.rect(He,Le,Ue,Ce)}x?Ju(q,ae,M.dash,M.cap,re,T,D,Y,_):_C(w,q,ae,M.dash,M.cap,re,T,D,Y,ue,_),Se&&d.translate(-he,-he)}function _C(w,x,M,T,D,_,Y,q,re,ae,ue){let he=!1;re!=0&&S.forEach((Se,He)=>{if(Se.series[0]==w){let Le=m[Se.series[1]],Ue=e[Se.series[1]],Ce=(Le._paths||fa).band;vi(Ce)&&(Ce=Se.dir==1?Ce[0]:Ce[1]);let me,ot=null;Le.show&&Ce&&iT(Ue,Gt,Xt)?(ot=Se.fill(n,He)||_,me=Le._paths.clip):Ce=null,Ju(x,M,T,D,ot,Y,q,re,ae,ue,me,Ce),he=!0}}),he||Ju(x,M,T,D,_,Y,q,re,ae,ue)}const kp=po|$h;function Ju(w,x,M,T,D,_,Y,q,re,ae,ue,he){bp(w,x,M,T,D),(re||ae||he)&&(d.save(),re&&d.clip(re),ae&&d.clip(ae)),he?(q&kp)==kp?(d.clip(he),ue&&d.clip(ue),Va(D,Y),Ha(w,_,x)):q&$h?(Va(D,Y),d.clip(he),Ha(w,_,x)):q&po&&(d.save(),d.clip(he),ue&&d.clip(ue),Va(D,Y),d.restore(),Ha(w,_,x)):(Va(D,Y),Ha(w,_,x)),(re||ae||he)&&d.restore()}function Ha(w,x,M){M>0&&(x instanceof Map?x.forEach((T,D)=>{d.strokeStyle=Wa=D,d.stroke(T)}):x!=null&&w&&d.stroke(x))}function Va(w,x){x instanceof Map?x.forEach((M,T)=>{d.fillStyle=vs=T,d.fill(M)}):x!=null&&w&&d.fill(x)}function $C(w,x,M,T){let D=v[w],_;if(T<=0)_=[0,0];else{let Y=D._space=D.space(n,w,x,M,T),q=D._incrs=D.incrs(n,w,x,M,T,Y);_=k5(x,M,q,T,Y)}return D._found=_}function ec(w,x,M,T,D,_,Y,q,re,ae){let ue=Y%2/2;g==1&&d.translate(ue,ue),bp(q,Y,re,ae,q),d.beginPath();let he,Se,He,Le,Ue=D+(T==0||T==3?-_:_);M==0?(Se=D,Le=Ue):(he=D,He=Ue);for(let Ce=0;Ce<w.length;Ce++)x[Ce]!=null&&(M==0?he=He=w[Ce]:Se=Le=w[Ce],d.moveTo(he,Se),d.lineTo(He,Le));d.stroke(),g==1&&d.translate(-ue,-ue)}function NC(w){let x=!0;return v.forEach((M,T)=>{if(!M.show)return;let D=b[M.scale];if(D.min==null){M._show&&(x=!1,M._show=!1,ws(!1));return}else M._show||(x=!1,M._show=!0,ws(!1));let _=M.side,Y=_%2,{min:q,max:re}=D,[ae,ue]=$C(T,q,re,Y==0?pe:ie);if(ue==0)return;let he=D.distr==2,Se=M._splits=M.splits(n,T,q,re,ae,ue,he),He=D.distr==2?Se.map(me=>mn[me]):Se,Le=D.distr==2?mn[Se[1]]-mn[Se[0]]:ae,Ue=M._values=M.values(n,M.filter(n,He,T,ue,Le),T,ue,Le);M._rotate=_==2?M.rotate(n,Ue,T,ue):0;let Ce=M._size;M._size=ln(M.size(n,Ue,T,w)),Ce!=null&&M._size!=Ce&&(x=!1)}),x}function WC(w){let x=!0;return vp.forEach((M,T)=>{let D=M(n,T,Vi,w);D!=ui[T]&&(x=!1),ui[T]=D}),x}function HC(){for(let w=0;w<v.length;w++){let x=v[w];if(!x.show||!x._show)continue;let M=x.side,T=M%2,D,_,Y=x.stroke(n,w),q=M==0||M==3?-1:1,[re,ae]=x._found;if(x.label!=null){let xr=x.labelGap*q,jr=Lt((x._lpos+xr)*Ve);Cp(x.labelFont[0],Y,"center",M==2?Wo:Um),d.save(),T==1?(D=_=0,d.translate(jr,Lt(Te+Me/2)),d.rotate((M==3?-Ll:Ll)/2)):(D=Lt(de+Ee/2),_=jr);let Gi=Zb(x.label)?x.label(n,w,re,ae):x.label;d.fillText(Gi,D,_),d.restore()}if(ae==0)continue;let ue=b[x.scale],he=T==0?Ee:Me,Se=T==0?de:Te,He=x._splits,Le=ue.distr==2?He.map(xr=>mn[xr]):He,Ue=ue.distr==2?mn[He[1]]-mn[He[0]]:re,Ce=x.ticks,me=x.border,ot=Ce.show?Ce.size:0,It=Lt(ot*Ve),Qt=Lt((x.alignTo==2?x._size-ot-x.gap:x.gap)*Ve),Ke=x._rotate*-Ll/180,St=C(x._pos*Ve),Hr=(It+Qt)*q,Cr=St+Hr;_=T==0?Cr:0,D=T==1?Cr:0;let nn=x.font[0],yn=x.align==1?Rs:x.align==2?nd:Ke>0?Rs:Ke<0?nd:T==0?"center":M==3?nd:Rs,Fn=Ke||T==1?"middle":M==2?Wo:Um;Cp(nn,Y,yn,Fn);let Vr=x.font[1]*x.lineGap,sn=He.map(xr=>C(a(xr,ue,he,Se))),vn=x._values;for(let xr=0;xr<vn.length;xr++){let jr=vn[xr];if(jr!=null){T==0?D=sn[xr]:_=sn[xr],jr=""+jr;let Gi=jr.indexOf(`
|
|
273
|
+
`)==-1?[jr]:jr.split(/\n/gm);for(let Ir=0;Ir<Gi.length;Ir++){let Vp=Gi[Ir];Ke?(d.save(),d.translate(D,_+Ir*Vr),d.rotate(Ke),d.fillText(Vp,0,0),d.restore()):d.fillText(Vp,D,_+Ir*Vr)}}}Ce.show&&ec(sn,Ce.filter(n,Le,w,ae,Ue),T,M,St,It,Je(Ce.width*Ve,3),Ce.stroke(n,w),Ce.dash,Ce.cap);let Ln=x.grid;Ln.show&&ec(sn,Ln.filter(n,Le,w,ae,Ue),T,T==0?2:1,T==0?Te:de,T==0?Me:Ee,Je(Ln.width*Ve,3),Ln.stroke(n,w),Ln.dash,Ln.cap),me.show&&ec([St],[1],T==0?1:0,T==0?1:2,T==1?Te:de,T==1?Me:Ee,Je(me.width*Ve,3),me.stroke(n,w),me.dash,me.cap)}qt("drawAxes")}function ws(w){m.forEach((x,M)=>{M>0&&(x._paths=null,w&&(i==1?(x.min=null,x.max=null):x.facets.forEach(T=>{T.min=null,T.max=null})))})}let ja=!1,tc=!1,Eo=[];function VC(){tc=!1;for(let w=0;w<Eo.length;w++)qt(...Eo[w]);Eo.length=0}function bs(){ja||(vT(Ep),ja=!0)}function jC(w,x=!1){ja=!0,tc=x,w(n),Ep(),x&&Eo.length>0&&queueMicrotask(VC)}n.batch=jC;function Ep(){if(Ne&&(BC(),Ne=!1),Be&&($i(),Be=!1),we){if(lt(f,Rs,$e),lt(f,Wo,ht),lt(f,qo,pe),lt(f,Qo,ie),lt(p,Rs,$e),lt(p,Wo,ht),lt(p,qo,pe),lt(p,Qo,ie),lt(h,qo,xe),lt(h,Qo,Re),c.width=Lt(xe*Ve),c.height=Lt(Re*Ve),v.forEach(({_el:w,_show:x,_size:M,_pos:T,side:D})=>{if(w!=null)if(x){let _=D===3||D===0?M:0,Y=D%2==1;lt(w,Y?"left":"top",T-_),lt(w,Y?"width":"height",M),lt(w,Y?"top":"left",Y?ht:$e),lt(w,Y?"height":"width",Y?ie:pe),Oh(w,ts)}else Gr(w,ts)}),Wa=vs=ju=Gu=Xu=Zu=Ku=qu=Yu=null,zr=1,Uo(!0),$e!=J||ht!=G||pe!=le||ie!=ye){ws(!1);let w=pe/le,x=ie/ye;if(ve&&!Tt&&Z.left>=0){Z.left*=w,Z.top*=x,Cs&&$n(Cs,Lt(Z.left),0,pe,ie),xs&&$n(xs,0,Lt(Z.top),pe,ie);for(let M=0;M<fr.length;M++){let T=fr[M];T!=null&&(zn[M]*=w,Dn[M]*=x,$n(T,ln(zn[M]),ln(Dn[M]),pe,ie))}}if(st.show&&!ft&&st.left>=0&&st.width>0){st.left*=w,st.width*=w,st.top*=x,st.height*=x;for(let M in ac)lt(ks,M,st[M])}J=$e,G=ht,le=pe,ye=ie}qt("setSize"),we=!1}xe>0&&Re>0&&(d.clearRect(0,0,c.width,c.height),qt("drawClear"),U.forEach(w=>w()),qt("draw")),st.show&&ft&&(Ya(st),ft=!1),ve&&Tt&&(Yi(null,!0,!1),Tt=!1),Q.show&&Q.live&&We&&(sc(),We=!1),l||(l=!0,n.status=1,qt("ready")),ko=!1,ja=!1}n.redraw=(w,x)=>{Be=x||!1,w!==!1?di(I,R.min,R.max):bs()};function rc(w,x){let M=b[w];if(M.from==null){if(nr==0){let T=M.range(n,x.min,x.max,w);x.min=T[0],x.max=T[1]}if(x.min>x.max){let T=x.min;x.min=x.max,x.max=T}if(nr>1&&x.min!=null&&x.max!=null&&x.max-x.min<1e-16)return;w==I&&M.distr==2&&nr>0&&(x.min=kn(x.min,e[0]),x.max=kn(x.max,e[0]),x.min==x.max&&x.max++),N[w]=x,Ne=!0,bs()}}n.setScale=rc;let nc,ic,Cs,xs,Mp,Tp,Is,Ss,Up,Ap,it,pt,ci=!1;const ir=Z.drag;let Zt=ir.x,Kt=ir.y;ve&&(Z.x&&(nc=an(WM,p)),Z.y&&(ic=an(HM,p)),R.ori==0?(Cs=nc,xs=ic):(Cs=ic,xs=nc),it=Z.left,pt=Z.top);const st=n.select=Pt({show:!0,over:!0,left:0,width:0,top:0,height:0},r.select),ks=st.show?an(NM,st.over?p:f):null;function Ya(w,x){if(st.show){for(let M in w)st[M]=w[M],M in ac&<(ks,M,w[M]);x!==!1&&qt("setSelect")}}n.setSelect=Ya;function YC(w){if(m[w].show)se&&Oh(Ie[w],ts);else if(se&&Gr(Ie[w],ts),ve){let M=Pn?fr[0]:fr[w];M!=null&&$n(M,-10,-10,pe,ie)}}function di(w,x,M){rc(w,{min:x,max:M})}function On(w,x,M,T){x.focus!=null&&qC(w),x.show!=null&&m.forEach((D,_)=>{_>0&&(w==_||w==null)&&(D.show=x.show,YC(_),i==2?(di(D.facets[0].scale,null,null),di(D.facets[1].scale,null,null)):di(D.scale,null,null),bs())}),M!==!1&&qt("setSeries",w,x),T&&Ao("setSeries",n,w,x)}n.setSeries=On;function GC(w,x){Pt(S[w],x)}function XC(w,x){w.fill=Pe(w.fill||null),w.dir=_e(w.dir,-1),x=x??S.length,S.splice(x,0,w)}function ZC(w){w==null?S.length=0:S.splice(w,1)}n.addBand=XC,n.setBand=GC,n.delBand=ZC;function KC(w,x){m[w].alpha=x,ve&&fr[w]!=null&&(fr[w].style.opacity=x),se&&Ie[w]&&(Ie[w].style.opacity=x)}let Gn,hi,ji;const Es={focus:!0};function qC(w){if(w!=ji){let x=w==null,M=hr.alpha!=1;m.forEach((T,D)=>{if(i==1||D>0){let _=x||D==0||D==w;T._focus=x?null:_,M&&KC(D,_?1:hr.alpha)}}),ji=w,M&&bs()}}se&&Rn&&nt(zm,be,w=>{Z._lock||(Pr(w),ji!=null&&On(null,Es,!0,Rt.setSeries))});function Bn(w,x,M){let T=b[x];M&&(w=w/Ve-(T.ori==1?ht:$e));let D=pe;T.ori==1&&(D=ie,w=D-w),T.dir==-1&&(w=D-w);let _=T._min,Y=T._max,q=w/D,re=_+(Y-_)*q,ae=T.distr;return ae==3?co(10,re):ae==4?oT(re,T.asinh):ae==100?T.bwd(re):re}function QC(w,x){let M=Bn(w,I,x);return kn(M,e[0],Gt,Xt)}n.valToIdx=w=>kn(w,e[0]),n.posToIdx=QC,n.posToVal=Bn,n.valToPos=(w,x,M)=>b[x].ori==0?s(w,b[x],M?Ee:pe,M?de:0):o(w,b[x],M?Me:ie,M?Te:0),n.setCursor=(w,x,M)=>{it=w.left,pt=w.top,Yi(null,x,M)};function Rp(w,x){lt(ks,Rs,st.left=w),lt(ks,qo,st.width=x)}function Pp(w,x){lt(ks,Wo,st.top=w),lt(ks,Qo,st.height=x)}let Mo=R.ori==0?Rp:Pp,To=R.ori==1?Rp:Pp;function JC(){if(se&&Q.live)for(let w=i==2?1:0;w<m.length;w++){if(w==0&&qe)continue;let x=Q.values[w],M=0;for(let T in x)et[w][M++].firstChild.nodeValue=x[T]}}function sc(w,x){if(w!=null&&(w.idxs?w.idxs.forEach((M,T)=>{te[T]=M}):cT(w.idx)||te.fill(w.idx),Q.idx=te[0]),se&&Q.live){for(let M=0;M<m.length;M++)(M>0||i==1&&!qe)&&ex(M,te[M]);JC()}We=!1,x!==!1&&qt("setLegend")}n.setLegend=sc;function ex(w,x){let M=m[w],T=w==0&&O==2?mn:e[w],D;qe?D=M.values(n,w,x)??Mt:(D=M.value(n,x==null?null:T[x],w,x),D=D==null?Mt:{_:D}),Q.values[w]=D}function Yi(w,x,M){Up=it,Ap=pt,[it,pt]=Z.move(n,it,pt),Z.left=it,Z.top=pt,ve&&(Cs&&$n(Cs,Lt(it),0,pe,ie),xs&&$n(xs,0,Lt(pt),pe,ie));let T,D=Gt>Xt;Gn=Qe,hi=null;let _=R.ori==0?pe:ie,Y=R.ori==1?pe:ie;if(it<0||nr==0||D){T=Z.idx=null;for(let q=0;q<m.length;q++){let re=fr[q];re!=null&&$n(re,-10,-10,pe,ie)}Rn&&On(null,Es,!0,w==null&&Rt.setSeries),Q.live&&(te.fill(T),We=!0)}else{let q,re,ae;i==1&&(q=R.ori==0?it:pt,re=Bn(q,I),T=Z.idx=kn(re,e[0],Gt,Xt),ae=A(e[0][T],R,_,0));let ue=-10,he=-10,Se=0,He=0,Le=!0,Ue="",Ce="";for(let me=i==2?1:0;me<m.length;me++){let ot=m[me],It=te[me],Qt=It==null?null:i==1?e[me][It]:e[me][1][It],Ke=Z.dataIdx(n,me,T,re),St=Ke==null?null:i==1?e[me][Ke]:e[me][1][Ke];if(We=We||St!=Qt||Ke!=It,te[me]=Ke,me>0&&ot.show){let Hr=Ke==null?-10:Ke==T?ae:A(i==1?e[0][Ke]:e[me][0][Ke],R,_,0),Cr=St==null?-10:V(St,i==1?b[ot.scale]:b[ot.facets[1].scale],Y,0);if(Rn&&St!=null){let nn=R.ori==1?it:pt,yn=Wt(hr.dist(n,me,Ke,Cr,nn));if(yn<Gn){let Fn=hr.bias;if(Fn!=0){let Vr=Bn(nn,ot.scale),sn=St>=0?1:-1,vn=Vr>=0?1:-1;vn==sn&&(vn==1?Fn==1?St>=Vr:St<=Vr:Fn==1?St<=Vr:St>=Vr)&&(Gn=yn,hi=me)}else Gn=yn,hi=me}}if(We||Pn){let nn,yn;R.ori==0?(nn=Hr,yn=Cr):(nn=Cr,yn=Hr);let Fn,Vr,sn,vn,Ln,xr,jr=!0,Gi=yt.bbox;if(Gi!=null){jr=!1;let Ir=Gi(n,me);sn=Ir.left,vn=Ir.top,Fn=Ir.width,Vr=Ir.height}else sn=nn,vn=yn,Fn=Vr=yt.size(n,me);if(xr=yt.fill(n,me),Ln=yt.stroke(n,me),Pn)me==hi&&Gn<=hr.prox&&(ue=sn,he=vn,Se=Fn,He=Vr,Le=jr,Ue=xr,Ce=Ln);else{let Ir=fr[me];Ir!=null&&(zn[me]=sn,Dn[me]=vn,$m(Ir,Fn,Vr,jr),Lm(Ir,xr,Ln),$n(Ir,ln(sn),ln(vn),pe,ie))}}}}if(Pn){let me=hr.prox,ot=ji==null?Gn<=me:Gn>me||hi!=ji;if(We||ot){let It=fr[0];It!=null&&(zn[0]=ue,Dn[0]=he,$m(It,Se,He,Le),Lm(It,Ue,Ce),$n(It,ln(ue),ln(he),pe,ie))}}}if(st.show&&ci)if(w!=null){let[q,re]=Rt.scales,[ae,ue]=Rt.match,[he,Se]=w.cursor.sync.scales,He=w.cursor.drag;if(Zt=He._x,Kt=He._y,Zt||Kt){let{left:Le,top:Ue,width:Ce,height:me}=w.select,ot=w.scales[he].ori,It=w.posToVal,Qt,Ke,St,Hr,Cr,nn=q!=null&&ae(q,he),yn=re!=null&&ue(re,Se);nn&&Zt?(ot==0?(Qt=Le,Ke=Ce):(Qt=Ue,Ke=me),St=b[q],Hr=A(It(Qt,he),St,_,0),Cr=A(It(Qt+Ke,he),St,_,0),Mo(Mn(Hr,Cr),Wt(Cr-Hr))):Mo(0,_),yn&&Kt?(ot==1?(Qt=Le,Ke=Ce):(Qt=Ue,Ke=me),St=b[re],Hr=V(It(Qt,Se),St,Y,0),Cr=V(It(Qt+Ke,Se),St,Y,0),To(Mn(Hr,Cr),Wt(Cr-Hr))):To(0,Y)}else lc()}else{let q=Wt(Up-Mp),re=Wt(Ap-Tp);if(R.ori==1){let Se=q;q=re,re=Se}Zt=ir.x&&q>=ir.dist,Kt=ir.y&&re>=ir.dist;let ae=ir.uni;ae!=null?Zt&&Kt&&(Zt=q>=ae,Kt=re>=ae,!Zt&&!Kt&&(re>q?Kt=!0:Zt=!0)):ir.x&&ir.y&&(Zt||Kt)&&(Zt=Kt=!0);let ue,he;Zt&&(R.ori==0?(ue=Is,he=it):(ue=Ss,he=pt),Mo(Mn(ue,he),Wt(he-ue)),Kt||To(0,Y)),Kt&&(R.ori==1?(ue=Is,he=it):(ue=Ss,he=pt),To(Mn(ue,he),Wt(he-ue)),Zt||Mo(0,_)),!Zt&&!Kt&&(Mo(0,0),To(0,0))}if(ir._x=Zt,ir._y=Kt,w==null){if(M){if(Hp!=null){let[q,re]=Rt.scales;Rt.values[0]=q!=null?Bn(R.ori==0?it:pt,q):null,Rt.values[1]=re!=null?Bn(R.ori==1?it:pt,re):null}Ao(id,n,it,pt,pe,ie,T)}if(Rn){let q=M&&Rt.setSeries,re=hr.prox;ji==null?Gn<=re&&On(hi,Es,!0,q):Gn>re?On(null,Es,!0,q):hi!=ji&&On(hi,Es,!0,q)}}We&&(Q.idx=T,sc()),x!==!1&&qt("setCursor")}let fi=null;Object.defineProperty(n,"rect",{get(){return fi==null&&Uo(!1),fi}});function Uo(w=!1){w?fi=null:(fi=p.getBoundingClientRect(),qt("syncRect",fi))}function zp(w,x,M,T,D,_,Y){Z._lock||ci&&w!=null&&w.movementX==0&&w.movementY==0||(oc(w,x,M,T,D,_,Y,!1,w!=null),w!=null?Yi(null,!0,!0):Yi(x,!0,!1))}function oc(w,x,M,T,D,_,Y,q,re){if(fi==null&&Uo(!1),Pr(w),w!=null)M=w.clientX-fi.left,T=w.clientY-fi.top;else{if(M<0||T<0){it=-10,pt=-10;return}let[ae,ue]=Rt.scales,he=x.cursor.sync,[Se,He]=he.values,[Le,Ue]=he.scales,[Ce,me]=Rt.match,ot=x.axes[0].side%2==1,It=R.ori==0?pe:ie,Qt=R.ori==1?pe:ie,Ke=ot?_:D,St=ot?D:_,Hr=ot?T:M,Cr=ot?M:T;if(Le!=null?M=Ce(ae,Le)?a(Se,b[ae],It,0):-10:M=It*(Hr/Ke),Ue!=null?T=me(ue,Ue)?a(He,b[ue],Qt,0):-10:T=Qt*(Cr/St),R.ori==1){let nn=M;M=T,T=nn}}re&&(x==null||x.cursor.event.type==id)&&((M<=1||M>=pe-1)&&(M=Ji(M,pe)),(T<=1||T>=ie-1)&&(T=Ji(T,ie))),q?(Mp=M,Tp=T,[Is,Ss]=Z.move(n,M,T)):(it=M,pt=T)}const ac={width:0,height:0,left:0,top:0};function lc(){Ya(ac,!1)}let Dp,Op,Bp,Fp;function Lp(w,x,M,T,D,_,Y){ci=!0,Zt=Kt=ir._x=ir._y=!1,oc(w,x,M,T,D,_,Y,!0,!1),w!=null&&(nt(sd,zh,_p,!1),Ao(Rm,n,Is,Ss,pe,ie,null));let{left:q,top:re,width:ae,height:ue}=st;Dp=q,Op=re,Bp=ae,Fp=ue}function _p(w,x,M,T,D,_,Y){ci=ir._x=ir._y=!1,oc(w,x,M,T,D,_,Y,!1,!0);let{left:q,top:re,width:ae,height:ue}=st,he=ae>0||ue>0,Se=Dp!=q||Op!=re||Bp!=ae||Fp!=ue;if(he&&Se&&Ya(st),ir.setScale&&he&&Se){let He=q,Le=ae,Ue=re,Ce=ue;if(R.ori==1&&(He=re,Le=ue,Ue=q,Ce=ae),Zt&&di(I,Bn(He,I),Bn(He+Le,I)),Kt)for(let me in b){let ot=b[me];me!=I&&ot.from==null&&ot.min!=Qe&&di(me,Bn(Ue+Ce,me),Bn(Ue,me))}lc()}else Z.lock&&(Z._lock=!Z._lock,Yi(x,!0,w!=null));w!=null&&(br(sd,zh),Ao(sd,n,it,pt,pe,ie,null))}function tx(w,x,M,T,D,_,Y){if(Z._lock)return;Pr(w);let q=ci;if(ci){let re=!0,ae=!0,ue=10,he,Se;R.ori==0?(he=Zt,Se=Kt):(he=Kt,Se=Zt),he&&Se&&(re=it<=ue||it>=pe-ue,ae=pt<=ue||pt>=ie-ue),he&&re&&(it=it<Is?0:pe),Se&&ae&&(pt=pt<Ss?0:ie),Yi(null,!0,!0),ci=!1}it=-10,pt=-10,te.fill(null),Yi(null,!0,!0),q&&(ci=q)}function $p(w,x,M,T,D,_,Y){Z._lock||(Pr(w),Vu(),lc(),w!=null&&Ao(Dm,n,it,pt,pe,ie,null))}function Np(){v.forEach(E5),Yt(n.width,n.height,!0)}as(fu,to,Np);const Ms={};Ms.mousedown=Lp,Ms.mousemove=zp,Ms.mouseup=_p,Ms.dblclick=$p,Ms.setSeries=(w,x,M,T)=>{let D=Rt.match[2];M=D(n,x,M),M!=-1&&On(M,T,!0,!1)},ve&&(nt(Rm,p,Lp),nt(id,p,zp),nt(Pm,p,w=>{Pr(w),Uo(!1)}),nt(zm,p,tx),nt(Dm,p,$p),Nh.add(n),n.syncRect=Uo);const Ga=n.hooks=r.hooks||{};function qt(w,x,M){tc?Eo.push([w,x,M]):w in Ga&&Ga[w].forEach(T=>{T.call(null,n,x,M)})}(r.plugins||[]).forEach(w=>{for(let x in w.hooks)Ga[x]=(Ga[x]||[]).concat(w.hooks[x])});const Wp=(w,x,M)=>M,Rt=Pt({key:null,setSeries:!1,filters:{pub:jm,sub:jm},scales:[I,m[1]?m[1].scale:null],match:[Ym,Ym,Wp],values:[null,null]},Z.sync);Rt.match.length==2&&Rt.match.push(Wp),Z.sync=Rt;const Hp=Rt.key,uc=wC(Hp);function Ao(w,x,M,T,D,_,Y){Rt.filters.pub(w,x,M,T,D,_,Y)&&uc.pub(w,x,M,T,D,_,Y)}uc.sub(n);function rx(w,x,M,T,D,_,Y){Rt.filters.sub(w,x,M,T,D,_,Y)&&Ms[w](null,x,M,T,D,_,Y)}n.pub=rx;function nx(){uc.unsub(n),Nh.delete(n),xt.clear(),Bh(fu,to,Np),u.remove(),be==null||be.remove(),qt("destroy")}n.destroy=nx;function cc(){qt("init",r,e),wp(e||r.data,!1),N[I]?rc(I,N[I]):Vu(),ft=st.show&&(st.width>0||st.height>0),Tt=We=!0,Yt(r.width,r.height)}return m.forEach(At),v.forEach(OC),t?t instanceof HTMLElement?(t.appendChild(u),cc()):t(n,cc):cc(),n}yr.assign=Pt;yr.fmtNum=ap;yr.rangeNum=pu;yr.rangeLog=Fu;yr.rangeAsinh=sp;yr.orient=ms;yr.pxRatio=Ve;yr.join=yT;yr.fmtDate=up,yr.tzDate=TT;yr.sync=wC;{yr.addGap=c5,yr.clipGaps=$u;let r=yr.paths={points:kC};r.linear=MC,r.stepped=f5,r.bars=p5,r.spline=m5}function M5(r,e){const t=/^#([0-9a-fA-F]{6})([0-9a-fA-F]{2})?$/.exec(r.trim());return t?`#${t[1]}${e}`:r}function RC({data:r,seriesKeys:e,seriesLabels:t,colors:n,height:i=300,tickRate:s=60,windowSeconds:o=20,hoveredKey:a=null,onHoverKey:l}){const u=$.useRef(null),c=$.useRef(null),d=$.useRef(null),h=$.useMemo(()=>e.join("|"),[e]),f=$.useMemo(()=>{const y=Math.max(1,Math.round(o*s)),m=Math.max(0,r.length-y),v=r.slice(m),b=Math.max(0,y-v.length),S=new Array(y);for(let E=0;E<y;E++)S[E]=E;const I=e.map(()=>new Array(y).fill(0));for(let E=0;E<v.length;E++){const U=v[E],z=b+E;for(let B=0;B<e.length;B++){const R=e[B],O=Number(U[R]??0);I[B][z]=Number.isFinite(O)?O:0}}return{x:S,series:I,windowPoints:y}},[r,e,s,o]),p=$.useMemo(()=>[f.x,...f.series],[f]),g=$.useMemo(()=>{const y=typeof globalThis.devicePixelRatio=="number"?globalThis.devicePixelRatio:1,m=[{label:"t"},...e.map((v,b)=>{const S=n[b%n.length]??"#4fc1ff";return{label:t[v]??v,stroke:S,width:2,points:{show:!1}}})];return{width:800,height:i,pxAlign:0,pxRatio:y,padding:[10,10,10,10],scales:{x:{time:!1},y:{}},axes:[{stroke:"#555",grid:{stroke:"#222",width:1},size:0,values:(v,b)=>b.map(()=>"")},{stroke:"#555",grid:{stroke:"#222",width:1}}],series:m,legend:{show:!1},cursor:{drag:{x:!1,y:!1}},hooks:{setCursor:[v=>{var B;if(!l)return;const b=v.cursor.idx;if(b==null||b<0){d.current!==null&&(d.current=null,l(null));return}const S=v.cursor.top;if(S==null||!Number.isFinite(S)){d.current!==null&&(d.current=null,l(null));return}let I=null,E=Number.POSITIVE_INFINITY;for(let R=1;R<v.series.length;R++){const O=e[R-1],A=(B=v.data[R])==null?void 0:B[b];if(A==null||!Number.isFinite(A))continue;const V=v.valToPos(A,"y",!0),N=Math.abs(V-S);N<E&&(E=N,I=O)}const z=E<=12?I:null;d.current!==z&&(d.current=z,l(z))}]}}},[n,i,l,e,t]),C=$.useMemo(()=>e.map((y,m)=>{const v=n[m%n.length]??"#4fc1ff",b=a!=null&&a===y;return{stroke:a!=null&&a!==y?M5(v,"66"):v,width:b?3:2}}),[n,a,e]);return $.useEffect(()=>{var I;const y=u.current;if(!y)return;const m=()=>{l&&d.current!==null&&(d.current=null,l(null))};y.addEventListener("mouseleave",m),(I=c.current)==null||I.destroy(),c.current=null;const v=new yr(g,p,y);c.current=v;const b=new ResizeObserver(()=>{const E=y.getBoundingClientRect();v.setSize({width:Math.max(1,Math.floor(E.width)),height:i})});b.observe(y);const S=y.getBoundingClientRect();return v.setSize({width:Math.max(1,Math.floor(S.width)),height:i}),()=>{y.removeEventListener("mouseleave",m),b.disconnect(),v.destroy(),c.current=null}},[g,p,i,l,h]),$.useEffect(()=>{var y;(y=c.current)==null||y.setData(p)},[p]),$.useEffect(()=>{const y=c.current;if(y)for(let m=0;m<C.length;m++){const v=m+1,b=C[m],S=y.series[v];!S||!b||(S.stroke!==b.stroke||S.width!==b.width)&&y.setSeries(v,{stroke:b.stroke,width:b.width})}},[C]),k.jsx("div",{ref:u,style:{width:"100%",height:i}})}const Dr=(r,e)=>r===e?0:r<e?-1:1,py=(r,e)=>r.localeCompare(e,void 0,{numeric:!0}),yl=r=>(r??"").trim();function T5({sortedTraffic:r,topTraffic:e,chartData:t,topKeys:n,keyToLabel:i,keyToColor:s,tickRate:o,hoveredTrafficKey:a,setHoveredTrafficKey:l}){const[u,c]=$.useState("bps"),[d,h]=$.useState("desc"),[f,p]=$.useState("bps"),[g,C]=$.useState("desc"),[y,m]=$.useState("bps"),[v,b]=$.useState("desc"),S=P=>{if(P===u){h(W=>W==="asc"?"desc":"asc");return}c(P),h(P==="name"?"asc":"desc")},I=P=>{if(P===y){b(W=>W==="asc"?"desc":"asc");return}m(P),b(P==="name"?"asc":"desc")},E=P=>{if(P===f){C(W=>W==="asc"?"desc":"asc");return}p(P),C(P==="name"?"asc":"desc")},U=(P,W,j)=>{const X=j==="asc"?1:-1,te=[...P];return te.sort((Q,Z)=>{let se=0;switch(W){case"id":se=Dr(Q.id,Z.id);break;case"name":{const ve=yl(Q.name),ge=yl(Z.name);se=py(ve,ge),se===0&&(se=Dr(Q.id,Z.id));break}case"encoding":{const ve=yl(Q.encoding),ge=yl(Z.encoding);se=py(ve,ge),se===0&&(se=Dr(Q.id,Z.id));break}case"bps":se=Dr(Q.bps,Z.bps),se===0&&(se=Dr(Q.total,Z.total));break;case"total":se=Dr(Q.total,Z.total),se===0&&(se=Dr(Q.bps,Z.bps));break;case"size":{const ve=Q.size.x*Q.size.y,ge=Z.size.x*Z.size.y;se=Dr(ve,ge),se===0&&(se=Dr(Q.id,Z.id));break}case"position":{se=Dr(Q.position.x,Z.position.x),se===0&&(se=Dr(Q.position.y,Z.position.y)),se===0&&(se=Dr(Q.id,Z.id));break}case"zIndex":se=Dr(Q.zIndex,Z.zIndex),se===0&&(se=Dr(Q.id,Z.id));break}return se*X}),te},z=$.useMemo(()=>r.filter(P=>P.key.startsWith("layer-")),[r]),B=$.useMemo(()=>r.filter(P=>P.key.startsWith("misc-")),[r]),R=$.useMemo(()=>r.filter(P=>P.key.startsWith("display-")),[r]),O=$.useMemo(()=>U(z,u,d),[z,d,u]),A=$.useMemo(()=>U(B,y,v),[B,v,y]),V=$.useMemo(()=>U(R,f,g),[R,g,f]),N={userSelect:"none",cursor:"pointer"},H=(P,W,j)=>P!==W?"":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"}),z.length===0&&B.length===0&&k.jsx("div",{style:{color:"#888",fontSize:12},children:"No bandwidth data yet. Move the client or send data to see traffic."}),z.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(RC,{data:t,seriesKeys:n,seriesLabels:i,colors:n.map(P=>s[P]??"#4fc1ff"),height:260,tickRate:o,windowSeconds:60,hoveredKey:a,onHoverKey:l})]}),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:"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:N,onClick:()=>S("id"),title:"Sort by ID",children:["ID",H("id",u,d)]}),k.jsxs("div",{style:N,onClick:()=>S("name"),title:"Sort by name",children:["Name",H("name",u,d)]}),k.jsxs("div",{style:N,onClick:()=>S("encoding"),title:"Sort by encoding",children:["Encoding",H("encoding",u,d)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>S("bps"),title:"Sort by Network/s",children:["Network/s",H("bps",u,d)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>S("total"),title:"Sort by Network",children:["Network",H("total",u,d)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>S("size"),title:"Sort by size",children:["Size",H("size",u,d)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>S("position"),title:"Sort by position",children:["Position",H("position",u,d)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>S("zIndex"),title:"Sort by zIndex",children:["zIndex",H("zIndex",u,d)]})]}),O.map(P=>k.jsxs("div",{onMouseEnter:()=>l(P.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===P.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===P.key?"#1a1a1a":"transparent",outline:a===P.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:P.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[P.key]??"#666",boxShadow:a===P.key?`0 0 0 1px #000, 0 0 0 2px ${s[P.key]??"#666"}`:"0 0 0 1px #000"}}),(()=>{var j;const W=((j=P.name)==null?void 0:j.trim())||`Layer ${P.id}`;return P.id===255?`${W} (debug)`:W})()]}),k.jsx("div",{style:{color:"#bbb"},children:P.encoding??""}),k.jsxs("div",{style:{textAlign:"right"},children:[Zr(P.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Zr(P.total)}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[P.size.x,"×",P.size.y]}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[P.position.x,"/",P.position.y]}),k.jsx("div",{style:{textAlign:"right",color:"#999"},children:P.zIndex})]},P.key))]}),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:"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:N,onClick:()=>E("id"),title:"Sort by ID",children:["ID",H("id",f,g)]}),k.jsxs("div",{style:N,onClick:()=>E("name"),title:"Sort by name",children:["Name",H("name",f,g)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>E("bps"),title:"Sort by Network/s",children:["Network/s",H("bps",f,g)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>E("total"),title:"Sort by Network",children:["Network",H("total",f,g)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>E("size"),title:"Sort by size",children:["Size",H("size",f,g)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>E("position"),title:"Sort by position",children:["Position",H("position",f,g)]}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"zIndex"})]}),V.map(P=>{var W;return k.jsxs("div",{onMouseEnter:()=>l(P.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===P.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===P.key?"#1a1a1a":"transparent",outline:a===P.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:P.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[P.key]??"#666",boxShadow:a===P.key?`0 0 0 1px #000, 0 0 0 2px ${s[P.key]??"#666"}`:"0 0 0 1px #000"}}),((W=P.name)==null?void 0:W.trim())||`Display ${P.id}`]}),k.jsxs("div",{style:{textAlign:"right"},children:[Zr(P.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Zr(P.total)}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[P.size.x,"×",P.size.y]}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[P.position.x,"/",P.position.y]}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"})]},P.key)})]}),B.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:N,onClick:()=>I("id"),title:"Sort by ID",children:["ID",H("id",y,v)]}),k.jsxs("div",{style:N,onClick:()=>I("name"),title:"Sort by name",children:["Name",H("name",y,v)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>I("bps"),title:"Sort by Network/s",children:["Network/s",H("bps",y,v)]}),k.jsxs("div",{style:{...N,textAlign:"right"},onClick:()=>I("total"),title:"Sort by Network",children:["Network",H("total",y,v)]}),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"})]}),A.map(P=>k.jsxs("div",{onMouseEnter:()=>l(P.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===P.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===P.key?"#1a1a1a":"transparent",outline:a===P.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:P.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[P.key]??"#666",boxShadow:a===P.key?`0 0 0 1px #000, 0 0 0 2px ${s[P.key]??"#666"}`:"0 0 0 1px #000"}}),P.name??"—"]}),k.jsxs("div",{style:{textAlign:"right"},children:[Zr(P.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Zr(P.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:"—"})]},P.key))]})]})}const Jt=65536,cd=.005,dd=32;function U5({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=$.useRef(null),[p,g]=$.useState(1),[C,y]=$.useState({x:0,y:0}),m=$.useRef(!1),v=$.useRef({x:0,y:0}),b=$.useRef(""),[S,I]=$.useState(!1),[E,U]=$.useState(null),[z,B]=$.useState(null),[R,O]=$.useState("none"),[A,V]=$.useState(null),N=$.useRef(null),[H,P]=$.useState(!1),W=$.useRef(!1),j=$.useRef(!1),X=$.useCallback((J,G,le)=>{const ye=t/le,de=n/le,Te=ye*.5,Ee=de*.5,Me=Math.max(0,Jt-ye)+Te,Ne=Math.max(0,Jt-de)+Ee,we=-Te,Be=-Ee;return{x:Math.max(we,Math.min(Me,J)),y:Math.max(Be,Math.min(Ne,G))}},[t,n]),te=$.useCallback(()=>{const J=Jt*p,G=Jt*p,le=J<t?(t-J)/2:0,ye=G<n?(n-G)/2:0;return{toScreenX:Ne=>(Ne-C.x)*p+le,toScreenY:Ne=>(Ne-C.y)*p+ye,toWorldX:Ne=>(Ne-le)/p+C.x,toWorldY:Ne=>(Ne-ye)/p+C.y}},[n,C.x,C.y,p,t]),Q=$.useCallback((J,G)=>{let le=null;for(let ye=0;ye<r.length;ye++){const de=r[ye];if(J<de.x||J>de.x+de.width||G<de.y||G>de.y+de.height)continue;const Te=de.zIndex??0;(!le||Te>le.z)&&(le={id:de.id,z:Te})}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(J>=de.x&&J<=de.x+de.width&&G>=de.y&&G<=de.y+de.height)return{kind:"display",id:de.id}}return null},[e,r]),Z=$.useCallback((J,G)=>{const le=[];for(let ye=0;ye<r.length;ye++){const de=r[ye];J<de.x||J>de.x+de.width||G<de.y||G>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]);$.useEffect(()=>{const J=f.current;if(!J)return;const G=J.getContext("2d");if(!G)return;G.clearRect(0,0,t,n),G.fillStyle="#0a0e14",G.fillRect(0,0,t,n);const le=Jt*p,ye=Jt*p,de=le<t?(t-le)/2:0,Te=ye<n?(n-ye)/2:0,Ee=we=>(we-C.x)*p+de,Me=we=>(we-C.y)*p+Te;{const we=Ee(0),Be=Ee(Jt),Tt=Me(0),ft=Me(Jt),We=Math.max(0,we),Yt=Math.min(t,Be),Bt=Math.max(0,Tt),li=Math.min(n,ft);if(!(Yt<=We||li<=Bt)){const $i=[{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}];G.save(),G.beginPath(),G.rect(We,Bt,Yt-We,li-Bt),G.clip();let Ni=!1;for(const Fe of $i){if(Fe.step*p<Fe.minGapPx)continue;Ni=!0,G.strokeStyle=`rgba(255,255,255,${Fe.alpha})`,G.lineWidth=Fe.lineWidth;const Pr=vt=>(vt-de)/p+C.x,yt=vt=>(vt-Te)/p+C.y,hr=Math.max(0,Pr(0)),Rn=Math.min(Jt,Pr(t)),Pn=Math.max(0,yt(0)),fr=Math.min(Jt,yt(n)),zn=Math.floor(hr/Fe.step)*Fe.step,Dn=Math.ceil(Rn/Fe.step)*Fe.step,ys=Math.floor(Pn/Fe.step)*Fe.step,At=Math.ceil(fr/Fe.step)*Fe.step;G.beginPath();for(let vt=zn;vt<=Dn;vt+=Fe.step){if(vt<0||vt>Jt)continue;const Hi=Ee(vt);G.moveTo(Hi,Bt),G.lineTo(Hi,li)}for(let vt=ys;vt<=At;vt+=Fe.step){if(vt<0||vt>Jt)continue;const Hi=Me(vt);G.moveTo(We,Hi),G.lineTo(Yt,Hi)}G.stroke()}if(!Ni){const Fe=$i[$i.length-1];G.strokeStyle=`rgba(255,255,255,${Fe.alpha})`,G.lineWidth=Fe.lineWidth;const Wi=At=>(At-de)/p+C.x,Pr=At=>(At-Te)/p+C.y,yt=Math.max(0,Wi(0)),hr=Math.min(Jt,Wi(t)),Rn=Math.max(0,Pr(0)),Pn=Math.min(Jt,Pr(n)),fr=Math.floor(yt/Fe.step)*Fe.step,zn=Math.ceil(hr/Fe.step)*Fe.step,Dn=Math.floor(Rn/Fe.step)*Fe.step,ys=Math.ceil(Pn/Fe.step)*Fe.step;G.beginPath();for(let At=fr;At<=zn;At+=Fe.step){if(At<0||At>Jt)continue;const vt=Ee(At);G.moveTo(vt,Bt),G.lineTo(vt,li)}for(let At=Dn;At<=ys;At+=Fe.step){if(At<0||At>Jt)continue;const vt=Me(At);G.moveTo(We,vt),G.lineTo(Yt,vt)}G.stroke()}G.restore()}}const Ne=[...r].sort((we,Be)=>(we.zIndex??0)-(Be.zIndex??0));for(const we of Ne){const Be=s!=null&&s.includes(we.id),Tt=i!=null&&we.id===i,ft=Ee(we.x),We=Me(we.y),Yt=we.width*p,Bt=we.height*p;if(ft+Yt<0||We+Bt<0||ft>t||We>n)continue;const li=we.zIndex??0,$i=we.color??(Be?"rgba(43, 140, 255, 0.60)":Tt?"rgba(102, 217, 239, 0.40)":"rgba(43, 140, 255, 0.42)");if(G.fillStyle=$i,G.fillRect(ft,We,Math.max(Yt,1),Math.max(Bt,1)),G.strokeStyle=Be?"#66d9ef":Tt?"rgba(102, 217, 239, 0.70)":"rgba(255,255,255,0.30)",G.lineWidth=Be?2:1,G.strokeRect(ft,We,Math.max(Yt,1),Math.max(Bt,1)),p>=3&&Yt>=40&&Bt>=16){G.font="11px monospace",G.textBaseline="top";const Ni=`z=${li}`,Fe=4,Wi=3,yt=G.measureText(Ni).width+Fe*2,hr=14;G.fillStyle="rgba(0,0,0,0.55)",G.fillRect(ft+3,We+3,yt,hr),G.fillStyle="rgba(255,255,255,0.85)",G.fillText(Ni,ft+3+Fe,We+3+Wi)}}for(const we of e){const Be=a!=null&&we.id===a,Tt=o!=null&&we.id===o,ft=Ee(we.x),We=Me(we.y),Yt=we.width*p,Bt=we.height*p;ft+Yt<0||We+Bt<0||ft>t||We>n||(G.strokeStyle=Be?"rgba(255, 120, 120, 1)":Tt?"rgba(255, 120, 120, 0.8)":"rgba(255, 80, 80, 0.9)",G.lineWidth=Be?3:2,G.strokeRect(ft,We,Math.max(Yt,1),Math.max(Bt,1)))}if(A){const we=Ee(A.x),Be=Me(A.y),Tt=A.width*p,ft=A.height*p;G.strokeStyle="rgba(43, 140, 255, 1)",G.lineWidth=2,G.setLineDash([6,4]),G.strokeRect(we,Be,Math.max(Tt,1),Math.max(ft,1)),G.setLineDash([])}},[r,e,t,n,p,C,i,s,o,a,A]);const se=$.useCallback((J,G)=>{var we;const le=(we=f.current)==null?void 0:we.getBoundingClientRect();if(!le)return null;const ye=J-le.left,de=G-le.top,{toWorldX:Te,toWorldY:Ee}=te(),Me=Te(ye),Ne=Ee(de);return{x:Me,y:Ne}},[te]),ve=$.useCallback((J,G)=>{const le=Math.floor(Math.min(J.x,G.x)),ye=Math.floor(Math.min(J.y,G.y)),de=Math.ceil(Math.max(J.x,G.x)),Te=Math.ceil(Math.max(J.y,G.y));return{x:le,y:ye,width:Math.max(1,de-le),height:Math.max(1,Te-ye)}},[]);$.useEffect(()=>{if(!l){b.current="";return}const J=`${u}-${l.id}-${l.x}-${l.y}-${l.width}-${l.height}-${t}-${n}`;if(J===b.current)return;if(j.current){j.current=!1,b.current=J;return}b.current=J;const G=1.25,le=Math.max(cd,Math.min(dd,Math.min(t/(l.width*G),n/(l.height*G)))),ye=t/le,de=n/le,Te=l.x+l.width/2,Ee=l.y+l.height/2,Me=X(Te-ye/2,Ee-de/2,le);g(le),y(Me)},[l,u,t,n,X]);const ge=$.useCallback(J=>{var Bt;const G=(Bt=f.current)==null?void 0:Bt.getBoundingClientRect();if(!G)return;J.preventDefault();const le=J.clientX-G.left,ye=J.clientY-G.top,{toWorldX:de,toWorldY:Te}=te(),Ee=de(le),Me=Te(ye),Ne=J.deltaY<0?1.15:1/1.15,we=Math.max(cd,Math.min(dd,p*Ne)),Be=Jt*we,Tt=Jt*we,ft=Be<t?(t-Be)/2:0,We=Tt<n?(n-Tt)/2:0,Yt=X(Ee-(le-ft)/we,Me-(ye-We)/we,we);g(we),y(Yt)},[X,te,n,C,p,t]);$.useEffect(()=>{const J=f.current;if(!J)return;const G=le=>ge(le);return J.addEventListener("wheel",G,{passive:!1}),()=>J.removeEventListener("wheel",G)},[ge]);const be=$.useCallback(J=>{m.current=!0,I(!0),v.current={x:J.clientX,y:J.clientY}},[]),ct=$.useCallback(()=>{m.current=!1,I(!1)},[]),dt=$.useCallback(()=>{m.current=!1,I(!1),U(null)},[]),Ie=$.useCallback(J=>{const G=se(J.clientX,J.clientY);if(!G||R!=="rect"||!h)return;J.preventDefault(),J.stopPropagation(),W.current=!0;const le={x:Math.floor(G.x),y:Math.floor(G.y)};N.current={startWorld:le,moved:!1},P(!0),V({x:le.x,y:le.y,width:1,height:1})},[R,se,h]),et=$.useCallback(J=>{if(!N.current)return;const G=se(J.clientX,J.clientY);if(!G)return;const le=ve(N.current.startWorld,G);if(!N.current.moved){const ye=Math.abs(G.x-N.current.startWorld.x),de=Math.abs(G.y-N.current.startWorld.y);(ye>0||de>0)&&(N.current.moved=!0)}V(le)},[se,ve]),Ze=$.useCallback(()=>{!N.current||!A||(W.current=!0,h==null||h(A),j.current=!0,N.current=null,V(null),P(!1),O("none"))},[A,h]),qe=$.useCallback(J=>{if(N.current){if(J.preventDefault(),J.stopPropagation(),!N.current.moved){W.current=!0,N.current=null,V(null),P(!1),O("none");return}Ze()}},[Ze]);$.useEffect(()=>{if(!H)return;const J=le=>{et(le)},G=le=>{qe(le)};return window.addEventListener("mousemove",J,!0),window.addEventListener("mouseup",G,!0),()=>{window.removeEventListener("mousemove",J,!0),window.removeEventListener("mouseup",G,!0)}},[H,et,qe]),$.useEffect(()=>{if(!N.current)return;const J=G=>{G.key==="Enter"&&Ze()};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[Ze]);const Mt=$.useCallback(J=>{var we;if(N.current){et(J);return}if(m.current){const Be=J.clientX-v.current.x,Tt=J.clientY-v.current.y;v.current={x:J.clientX,y:J.clientY},y(ft=>X(ft.x-Be/p,ft.y-Tt/p,p));return}const G=(we=f.current)==null?void 0:we.getBoundingClientRect();if(!G)return;const le=J.clientX-G.left,ye=J.clientY-G.top,{toWorldX:de,toWorldY:Te}=te(),Ee=Math.floor(de(le)),Me=Math.floor(Te(ye)),Ne=Q(Ee,Me);if(!Ne){U({kind:"layer",id:-1,world:{x:Ee,y:Me},screen:{x:le,y:ye}});return}U({kind:Ne.kind,id:Ne.id,world:{x:Ee,y:Me},screen:{x:le,y:ye}})},[X,te,Q,p]),mt=$.useCallback(J=>{var Be;if(W.current){W.current=!1;return}if(R==="rect"||N.current||S)return;const G=(Be=f.current)==null?void 0:Be.getBoundingClientRect();if(!G)return;const le=J.clientX-G.left,ye=J.clientY-G.top,{toWorldX:de,toWorldY:Te}=te(),Ee=Math.floor(de(le)),Me=Math.floor(Te(ye)),Ne=Z(Ee,Me);if(Ne.length>=2){B({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:J.metaKey,ctrlKey:J.ctrlKey})),we.kind==="display"&&(d==null||d(we.id)))},[R,te,Q,Z,S,d,c]);$.useEffect(()=>{const J=G=>{G.key==="Escape"&&B(null)};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[]);const Ot=$.useCallback(()=>{g(1),y(X(0,0,1))},[X]),dr=$.useCallback(J=>{var Be;const G=(Be=f.current)==null?void 0:Be.getBoundingClientRect();if(!G)return;const le=G.width/2,ye=G.height/2,{toWorldX:de,toWorldY:Te}=te(),Ee=de(le),Me=Te(ye),Ne=Math.max(cd,Math.min(dd,p*J)),we=X(Ee-le/Ne,Me-ye/Ne,Ne);g(Ne),y(we)},[X,te,p]),tt=E&&E.id!==-1?E:null,xt=n<520?6:10,nt=Math.max(40,n-xt*2),br=88,xe=42,Re=nt<150,pe=nt<240,ie=nt<200,$e=Math.min(1,Math.max(.7,nt/(Re?64:br))),ht=Math.min(1,Math.max(.7,nt/xe));return k.jsxs("div",{style:{position:"absolute",inset:0},children:[k.jsx("canvas",{ref:f,width:t,height:n,style:{display:"block",cursor:R==="rect"?(N.current,"crosshair"):m.current?"grabbing":"grab"},onMouseDown:J=>{if(R==="rect"&&h){Ie(J);return}be(J)},onMouseMove:Mt,onMouseUp:J=>{if(N.current){qe(J);return}ct()},onMouseLeave:dt,onClick:mt}),k.jsxs("div",{style:{position:"absolute",right:xt,bottom:pe?void 0:xt,top:pe?xt: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% - ${xt*2}px)`},onMouseDown:J=>J.stopPropagation(),children:[k.jsx("button",{onClick:()=>{const J=R==="rect"?"none":"rect";N.current=null,P(!1),O(J)},style:{width:34,height:34,borderRadius:8,border:R==="rect"?"1px solid rgba(79, 193, 255, 0.9)":"1px solid rgba(255,255,255,0.18)",background:R==="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:R==="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:()=>{N.current=null,P(!1),O("none")},style:{width:34,height:34,borderRadius:8,border:"1px solid rgba(255,255,255,0.18)",background:R==="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:"↔"})]}),(z==null?void 0:z.open)&&z.layers.length>=2&&k.jsxs("div",{style:{position:"absolute",left:Math.min(t-220,z.anchorScreen.x+12),top:Math.min(n-260,z.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:()=>B(null),style:{...vl,padding:"2px 6px",borderRadius:8},title:"Close",children:"✕"})]}),k.jsxs("div",{style:{color:"#9aa7b2",marginTop:4},children:["World: ",z.world.x.toFixed(0),",",z.world.y.toFixed(0)]}),k.jsx("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:6,maxHeight:220,overflow:"auto",paddingRight:2},children:z.layers.map((J,G)=>{var le;return k.jsx("button",{onClick:ye=>{c==null||c(J.id,{metaKey:ye.metaKey,ctrlKey:ye.ctrlKey}),B(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=J.name)!=null&&le.trim()?J.name:`Layer ${J.id}`," ",k.jsxs("span",{style:{color:"#9aa7b2",fontWeight:500},children:["z=",J.zIndex]}),G===0&&k.jsx("span",{style:{marginLeft:6,color:"#66d9ef",fontWeight:650},children:"top"})]})},J.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:()=>dr(1.15),style:vl,title:"Zoom in",children:"+"}),k.jsx("button",{onClick:()=>dr(1/1.15),style:vl,title:"Zoom out",children:"−"}),k.jsx("button",{onClick:Ot,style:vl,title:"Reset view",children:"Reset"})]}),k.jsxs("div",{style:{position:"absolute",left:xt,bottom:ie?void 0:xt,top:ie?xt: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:ie?"top left":"bottom left",maxWidth:`calc(100% - ${xt*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:"})," (",C.x.toFixed(0),","," ",C.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 vl={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 PC={},mp={},yp={},Io={};Object.defineProperty(Io,"__esModule",{value:!0});Io.Direction=void 0;var gy;(function(r){r.Right="to right",r.Left="to left",r.Down="to bottom",r.Up="to top"})(gy||(Io.Direction=gy={}));(function(r){var e=Nr&&Nr.__spreadArray||function(O,A,V){if(V||arguments.length===2)for(var N=0,H=A.length,P;N<H;N++)(P||!(N in A))&&(P||(P=Array.prototype.slice.call(A,0,N)),P[N]=A[N]);return O.concat(P||Array.prototype.slice.call(A))};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=Io,i=function(O){var A=O.toString().split(".")[1];return A?A.length:0};r.getStepDecimals=i;function s(O){return O.touches&&O.touches.length||O.changedTouches&&O.changedTouches.length}r.isTouchEvent=s;function o(O,A,V){var N=(A-O)/V,H=8,P=Number(N.toFixed(H));return parseInt(P.toString(),10)===P}r.isStepDivisible=o;function a(O,A,V,N,H,P,W){var j=1e11;if(O=Math.round(O*j)/j,!P){var X=W[A-1],te=W[A+1];if(X&&X>O)return X;if(te&&te<O)return te}if(O>N)return N;if(O<V)return V;var Q=Math.floor(O*j-V*j)%Math.floor(H*j),Z=Math.floor(O*j-Math.abs(Q)),se=Q===0?O:Z/j,ve=Math.abs(Q/j)<H/2?se:se+H,ge=(0,r.getStepDecimals)(H);return parseFloat(ve.toFixed(ge))}r.normalizeValue=a;function l(O,A,V){return(O-A)/(V-A)}r.relativeValue=l;function u(O){return O===n.Direction.Up||O===n.Direction.Down}r.isVertical=u;function c(O,A,V){if(A>=V)throw new RangeError("min (".concat(A,") is equal/bigger than max (").concat(V,")"));if(O<A)throw new RangeError("value (".concat(O,") is smaller than min (").concat(A,")"));if(O>V)throw new RangeError("value (".concat(O,") is bigger than max (").concat(V,")"))}r.checkBoundaries=c;function d(O,A,V){return O<A?A:O>V?V:O}r.checkValuesAgainstBoundaries=d;function h(O){if(!(O.length<2)&&!O.slice(1).every(function(A,V){return O[V]<=A}))throw new RangeError("values={[".concat(O,"]} needs to be sorted when allowOverlap={false}"))}r.checkInitialOverlap=h;function f(O){var A=window.getComputedStyle(O);return{top:parseInt(A["margin-top"],10),bottom:parseInt(A["margin-bottom"],10),left:parseInt(A["margin-left"],10),right:parseInt(A["margin-right"],10)}}r.getMargin=f;function p(O){var A=window.getComputedStyle(O);return{top:parseInt(A["padding-top"],10)+parseInt(A["border-top-width"],10),bottom:parseInt(A["padding-bottom"],10)+parseInt(A["border-bottom-width"],10),left:parseInt(A["padding-left"],10)+parseInt(A["border-left-width"],10),right:parseInt(A["padding-right"],10)+parseInt(A["border-right-width"],10)}}r.getPaddingAndBorder=p;function g(O,A,V){var N=V?-1:1;O.forEach(function(H,P){return y(H,N*A[P].x,A[P].y)})}r.translateThumbs=g;function C(O,A,V,N){for(var H=0,P=B(O[0],A,V,N),W=1;W<O.length;W++){var j=B(O[W],A,V,N);j<P&&(P=j,H=W)}return H}r.getClosestThumbIndex=C;function y(O,A,V){O.style.transform="translate(".concat(A,"px, ").concat(V,"px)")}r.translate=y;var m=function(O){var A=[],V=null,N=function(){for(var H=[],P=0;P<arguments.length;P++)H[P]=arguments[P];A=H,!V&&(V=requestAnimationFrame(function(){V=null,O.apply(void 0,A)}))};return N};r.schd=m;function v(O,A,V){var N=O.slice(0);return N[A]=V,N}r.replaceAt=v;function b(O){var A=O.values,V=O.colors,N=O.min,H=O.max,P=O.direction,W=P===void 0?n.Direction.Right:P,j=O.rtl,X=j===void 0?!1:j;X&&W===n.Direction.Right?W=n.Direction.Left:X&&n.Direction.Left&&(W=n.Direction.Right);var te=A.slice(0).sort(function(Z,se){return Z-se}).map(function(Z){return(Z-N)/(H-N)*100}),Q=te.reduce(function(Z,se,ve){return"".concat(Z,", ").concat(V[ve]," ").concat(se,"%, ").concat(V[ve+1]," ").concat(se,"%")},"");return"linear-gradient(".concat(W,", ").concat(V[0]," 0%").concat(Q,", ").concat(V[V.length-1]," 100%)")}r.getTrackBackground=b;function S(){}r.voidFn=S;function I(O){throw new Error("Didn't expect to get here")}r.assertUnreachable=I;var E=function(O,A,V,N,H){H===void 0&&(H=function(W){return W});var P=Math.ceil(e([O],Array.from(O.children),!0).reduce(function(W,j){var X=Math.ceil(j.getBoundingClientRect().width);if(j.innerText&&j.innerText.includes(V)&&j.childElementCount===0){var te=j.cloneNode(!0);te.innerHTML=H(A.toFixed(N)),te.style.visibility="hidden",document.body.appendChild(te),X=Math.ceil(te.getBoundingClientRect().width),document.body.removeChild(te)}return X>W?X:W},O.getBoundingClientRect().width));return P},U=function(O,A,V,N,H,P,W){W===void 0&&(W=function(te){return te});var j=[],X=function(te){var Q=E(V[te],N[te],H,P,W),Z=A[te].x;A.forEach(function(se,ve){var ge=se.x,be=E(V[ve],N[ve],H,P,W);te!==ve&&(Z>=ge&&Z<=ge+be||Z+Q>=ge&&Z+Q<=ge+be)&&(j.includes(ve)||(j.push(te),j.push(ve),j=e(e([],j,!0),[te,ve],!1),X(ve)))})};return X(O),Array.from(new Set(j.sort()))},z=function(O,A,V,N,H,P){N===void 0&&(N=.1),H===void 0&&(H=" - "),P===void 0&&(P=function(ve){return ve});var W=(0,r.getStepDecimals)(N),j=(0,t.useState)({}),X=j[0],te=j[1],Q=(0,t.useState)(P(A[V].toFixed(W))),Z=Q[0],se=Q[1];return(0,t.useEffect)(function(){if(O){var ve=O.getThumbs();if(ve.length<1)return;var ge={},be=O.getOffsets(),ct=U(V,be,ve,A,H,W,P),dt=P(A[V].toFixed(W));if(ct.length){var Ie=ct.reduce(function(mt,Ot,dr,tt){return mt.length?e(e([],mt,!0),[be[tt[dr]].x],!1):[be[tt[dr]].x]},[]);if(Math.min.apply(Math,Ie)===be[V].x){var et=[];ct.forEach(function(mt){et.push(A[mt].toFixed(W))}),dt=Array.from(new Set(et.sort(function(mt,Ot){return parseFloat(mt)-parseFloat(Ot)}))).map(P).join(H);var Ze=Math.min.apply(Math,Ie),qe=Math.max.apply(Math,Ie),Mt=ve[ct[Ie.indexOf(qe)]].getBoundingClientRect().width;ge.left="".concat(Math.abs(Ze-(qe+Mt))/2,"px"),ge.transform="translate(-50%, 0)"}else ge.visibility="hidden"}se(dt),te(ge)}},[O,A]),[Z,X]};r.useThumbOverlap=z;function B(O,A,V,N){var H=O.getBoundingClientRect(),P=H.left,W=H.top,j=H.width,X=H.height;return u(N)?Math.abs(V-(W+X/2)):Math.abs(A-(P+j/2))}var R=function(){var O,A=((O=navigator.userAgentData)===null||O===void 0?void 0:O.platform)||navigator.platform;return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(A)||navigator.userAgent.includes("Mac")&&"ontouchend"in document};r.isIOS=R})(yp);var A5=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)}}(),R5=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]}),P5=Nr&&Nr.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),z5=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)&&R5(e,r,t);return P5(e,r),e},my=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(mp,"__esModule",{value:!0});var wl=z5($),De=yp,Ft=Io,D5=["ArrowRight","ArrowUp","k","PageUp"],O5=["ArrowLeft","ArrowDown","j","PageDown"],B5=function(r){A5(e,r);function e(t){var n=r.call(this,t)||this;if(n.trackRef=wl.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,De.getPaddingAndBorder)(u);return n.getThumbs().map(function(h,f){var p={x:0,y:0},g=h.getBoundingClientRect(),C=(0,De.getMargin)(h);switch(s){case Ft.Direction.Right:return p.x=(C.left+d.left)*-1,p.y=((g.height-c.height)/2+d.top)*-1,p.x+=c.width*(0,De.relativeValue)(o[f],a,l)-g.width/2,p;case Ft.Direction.Left:return p.x=(C.right+d.right)*-1,p.y=((g.height-c.height)/2+d.top)*-1,p.x+=c.width-c.width*(0,De.relativeValue)(o[f],a,l)-g.width/2,p;case Ft.Direction.Up:return p.x=((g.width-c.width)/2+C.left+d.left)*-1,p.y=-d.left,p.y+=c.height-c.height*(0,De.relativeValue)(o[f],a,l)-g.height/2,p;case Ft.Direction.Down:return p.x=((g.width-c.width)/2+C.left+d.left)*-1,p.y=-d.left,p.y+=c.height*(0,De.relativeValue)(o[f],a,l)-g.height/2,p;default:return(0,De.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,De.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,De.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,De.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,De.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,De.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===Ft.Direction.Left||c===Ft.Direction.Down?-1:1;h!==-1&&(D5.includes(i.key)?(i.preventDefault(),n.setState({draggedThumbIndex:h,isChanged:!0}),a((0,De.replaceAt)(o,h,n.normalizeValue(o[h]+f*(i.key==="PageUp"?l*10:l),h)))):O5.includes(i.key)?(i.preventDefault(),n.setState({draggedThumbIndex:h,isChanged:!0}),a((0,De.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,g=u.step,C=u.rtl;if(a===-1&&l[0]===-1&&l[1]===-1)return null;var y=n.trackRef.current;if(!y)return null;var m=y.getBoundingClientRect(),v=(0,De.isVertical)(c)?m.height:m.width;if(l[0]!==-1&&l[1]!==-1){var b=i-l[0],S=s-l[1],I=0;switch(c){case Ft.Direction.Right:case Ft.Direction.Left:I=b/v*(h-d);break;case Ft.Direction.Down:case Ft.Direction.Up:I=S/v*(h-d);break;default:(0,De.assertUnreachable)(c)}if(C&&(I*=-1),Math.abs(I)>=g/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 U=p[E]+I;U>h?I=h-p[E]:U<d&&(I=d-p[E])}for(var z=p.slice(0),E=0;E<n.thumbRefs.length;E++)z=(0,De.replaceAt)(z,E,n.normalizeValue(p[E]+I,E));n.setState({draggedTrackPos:[i,s]}),f(z)}}else{var B=0;switch(c){case Ft.Direction.Right:B=(i-m.left)/v*(h-d)+d;break;case Ft.Direction.Left:B=(v-(i-m.left))/v*(h-d)+d;break;case Ft.Direction.Down:B=(s-m.top)/v*(h-d)+d;break;case Ft.Direction.Up:B=(v-(s-m.top))/v*(h-d)+d;break;default:(0,De.assertUnreachable)(c)}C&&(B=h+d-B),Math.abs(p[a]-B)>=g/2&&f((0,De.replaceAt)(p,a,n.normalizeValue(B,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,De.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]=wl.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===Ft.Direction.Left||n.props.direction===Ft.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,De.schd)(n.onMouseMove),n.schdOnTouchMove=(0,De.schd)(n.onTouchMove),n.schdOnEnd=(0,De.schd)(n.onEnd),n.thumbRefs=t.values.map(function(){return wl.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,De.checkInitialOverlap)(this.props.values),this.props.values.forEach(function(a){return(0,De.checkBoundaries)(a,t.props.min,t.props.max)}),this.resizeObserver.observe(this.trackRef.current),(0,De.translateThumbs)(this.getThumbs(),this.getOffsets(),this.props.rtl),this.calculateMarkOffsets(),i.forEach(function(a){(0,De.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,De.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,De.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,g=this.state,C=g.draggedThumbIndex,y=g.thumbZIndexes,m=g.markOffsets;return o({props:{style:{transform:"scale(1)",cursor:C>-1?"grabbing":this.props.draggableTrack?(0,De.isVertical)(this.props.direction)?"ns-resize":"ew-resize":c.length===1&&!p?"pointer":"inherit"},onMouseDown:p?De.voidFn:this.onMouseDownTrack,onTouchStart:p?De.voidFn:this.onTouchStartTrack,ref:this.trackRef},isDragged:this.state.draggedThumbIndex>-1,disabled:p,children:my(my([],m.map(function(v,b,S){return u({props:{style:t.props.direction===Ft.Direction.Left||t.props.direction===Ft.Direction.Right?{position:"absolute",left:"".concat(v[0],"px"),marginTop:"".concat(v[1],"px")}:{position:"absolute",top:"".concat(v[0],"px"),marginLeft:"".concat(v[1],"px")},key:"mark".concat(b),ref:t.markRefs[b]},index:b})}),!0),c.map(function(v,b){var S=t.state.draggedThumbIndex===b;return a({index:b,value:v,isDragged:S,props:{style:{position:"absolute",zIndex:y[b],cursor:p?"inherit":S?"grabbing":"grab",userSelect:"none",touchAction:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none"},key:b,tabIndex:p?void 0:0,"aria-valuemax":f?h:c[b+1]||h,"aria-valuemin":f?d:c[b-1]||d,"aria-valuenow":v,draggable:!1,ref:t.thumbRefs[b],"aria-label":i,"aria-labelledby":s,role:"slider",onKeyDown:p?De.voidFn:t.onKeyDown,onKeyUp:p?De.voidFn:t.onKeyUp}})}),!0)})},e.defaultProps={label:"Accessibility label",labelledBy:null,step:1,direction:Ft.Direction.Right,rtl:!1,disabled:!1,allowOverlap:!1,draggableTrack:!1,min:0,max:100},e}(wl.Component);mp.default=B5;(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(mp);r.Range=t.default;var n=yp;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=Io;Object.defineProperty(r,"Direction",{enumerable:!0,get:function(){return i.Direction}})})(PC);const Yr={fontSize:12,color:"#9aa7b2"},yy={background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:10};function ea(r,e,t){return Math.max(e,Math.min(t,r))}function vy(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},${ea(e,0,1)})`}function F5(r){const e=["#66d9ef","#a6e22e","#fd971f","#e6db74","#f92672","#ae81ff","#2aa198"];return e[Math.abs(r)%e.length]}function zC(r,e){const t=(r??"").trim();return t.length?t:e}function L5(r,e){return r.map(t=>{const n=e.get(t);return n?{id:t,name:zC(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 _5({user:r,selectedDisplayId:e,selectedLayerIds:t,onSelectLayer:n,onSelectDisplay:i,setVisibleLayers:s}){var b;const o=$.useMemo(()=>r.displays.filter(S=>S.id!==255),[r.displays]),[a,l]=$.useState(null),[u,c]=$.useState([0,0]),d=$.useRef(null),h=$.useMemo(()=>{var E,U,z;const S=(E=o.find(B=>B.id===e))==null?void 0:E.id;if(S!=null)return S;const I=(U=o.find(B=>B.id===a))==null?void 0:U.id;return I??((z=o[0])==null?void 0:z.id)??null},[a,o,e]),f=$.useMemo(()=>h==null?null:o.find(S=>S.id===h)??null,[o,h]),p=$.useMemo(()=>{var I,E;if(h==null)return null;const S=(E=(I=r.displayComposite)==null?void 0:I[h])==null?void 0:E.layerIdsTopToBottom;return S&&S.length?S:null},[h,r.displayComposite]),g=$.useMemo(()=>{const S=new Map;for(const I of r.layers)S.set(I.id,{id:I.id,name:I.name,z:I.z,origin:I.origin,width:I.width,height:I.height});return S},[r.layers]),C=$.useMemo(()=>{var R,O;if(h==null)return[];const S=(O=(R=r.displayComposite)==null?void 0:R[h])==null?void 0:O.layerIdsTopToBottom;if(S&&S.length)return L5(S,g);if(!f)return[];const I=f.origin.x,E=f.origin.y,U=I+f.size.x,z=E+f.size.y,B=[];for(const A of r.layers){const V=A.origin.x,N=A.origin.y,H=A.origin.x+A.width,P=A.origin.y+A.height;U<=V||I>=H||z<=N||E>=P||B.push({id:A.id,name:zC(A.name,`Layer ${A.id}`),z:A.z,layer:A})}return B.sort((A,V)=>V.z-A.z),B},[h,f,g,r.displayComposite,r.layers]);$.useEffect(()=>{const S=C.length;if(!S){c([0,0]);return}const I=Math.max(0,S-1);c([0,I])},[h,C.length]);const y=$.useMemo(()=>{const S=Math.max(0,C.length-1);let I=ea(u[0],0,S),E=ea(u[1],0,S);return I>E&&([I,E]=[E,I]),[I,E]},[C.length,u]),m=$.useMemo(()=>{if(!C.length)return C;const[S,I]=y;return C.slice(S,I+1)},[C,y]);$.useEffect(()=>{if(!s)return;if(!C.length){s(null);return}const[S,I]=y;if(S===0&&I===C.length-1){s(null);return}s(m.map(U=>U.id))},[C.length,y,s,m]);const v=$.useMemo(()=>{if(!f)return null;const S=m;if(!C.length)return{visible:[],minY:f.origin.y,maxY:f.origin.y+f.size.y,range:[0,0]};const[I,E]=y,U=S;let z=f.origin.y,B=f.origin.y+f.size.y;for(const R of U){const O=R.layer;O&&(z=Math.min(z,O.origin.y),B=Math.max(B,O.origin.y+O.height))}return{visible:U,minY:z,maxY:B,range:[I,E]}},[f,C.length,y,m]);return $.useEffect(()=>{const S=d.current;if(!S||!f||!v)return;const I=S.getContext("2d");if(!I)return;const E=window.devicePixelRatio||1,U=S.clientWidth,z=S.clientHeight,B=Math.max(1,Math.floor(U*E)),R=Math.max(1,Math.floor(z*E));(S.width!==B||S.height!==R)&&(S.width=B,S.height=R),I.setTransform(E,0,0,E,0,0),I.clearRect(0,0,U,z);const O=14,A=Math.max(1,U-O*2),V=Math.max(1,z-O*2),N=v.minY,H=v.maxY,P=Math.max(1,H-N),W=f.origin.x,j=f.origin.x+f.size.x,X=Math.max(1,j-W),te=Ie=>O+(Ie-W)/X*A,Q=Ie=>Ie/X*A,Z=Ie=>O+(Ie-N)/P*V,se=Ie=>Ie/P*V;I.fillStyle="rgba(0,0,0,0.20)",I.fillRect(0,0,U,z);const ve=te(f.origin.x),ge=Z(f.origin.y),be=Q(f.size.x),ct=se(f.size.y);I.strokeStyle="rgba(255,120,120,0.75)",I.lineWidth=1,I.strokeRect(ve,ge,be,ct),I.fillStyle="rgba(255,120,120,0.08)",I.fillRect(ve,ge,be,ct);const dt=v.visible;for(let Ie=dt.length-1;Ie>=0;Ie--){const et=dt[Ie],Ze=et.layer;if(!Ze)continue;const qe=te(Ze.origin.x),Mt=Z(Ze.origin.y),mt=Math.max(2,Q(Ze.width)),Ot=Math.max(2,se(Ze.height)),dr=F5(et.id),tt=t.includes(et.id);I.fillStyle=vy(dr,1),I.strokeStyle=vy(dr,tt?.95:.55),I.lineWidth=tt?2:1,I.fillRect(qe,Mt,mt,Ot),I.strokeRect(qe,Mt,mt,Ot),I.save(),I.beginPath(),I.rect(qe,Mt,mt,Ot),I.clip(),I.fillStyle="rgba(15,15,15,0.95)",I.font="12px Segoe UI, sans-serif";const xt=[`${et.name}`,`id ${et.id} • z ${et.z}`,`pos ${Ze.origin.x},${Ze.origin.y}`,`size ${Ze.width}×${Ze.height}`],nt=14;let br=Mt+16;const xe=qe+8;for(let Re=0;Re<xt.length&&!(br>Mt+Ot-4);Re++){const pe=xt[Re];I.fillText(pe,xe,br),br+=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",O+8,O+18))},[f,t,v]),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:S=>{const I=S.target.value===""?null:Number(S.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(S=>k.jsx("option",{value:S.id,children:S.id},S.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:{...yy,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(PC.Range,{step:1,min:0,max:Math.max(0,C.length-1),values:(()=>{const S=Math.max(0,C.length-1),I=S-y[1],E=S-y[0];return[I,E]})(),onChange:S=>{const I=Math.max(0,C.length-1),E=Math.round(S[0]??0),U=Math.round(S[1]??0),z=ea(I-U,0,I),B=ea(I-E,0,I);c([z,B])},renderTrack:({props:S,children:I})=>k.jsxs("div",{...S,style:{...S.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,C.length-1),U=(E-y[1])/E,z=(E-y[0])/E,B=U*100,R=z*100;return k.jsx("div",{style:{position:"absolute",left:`${Math.min(B,R)}%`,width:`${Math.max(0,Math.abs(R-B))}%`,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:S,index:I})=>k.jsx("div",{...S,style:{...S.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:[C.length?`${y[0]} → ${y[1]}`:"—",C.length?` • ${m.length}/${C.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:{...yy,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:[m.length," / ",C.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:[C.map((S,I)=>{const E=t.includes(S.id),U=I>=y[0]&&I<=y[1];return k.jsx("button",{onClick:z=>{n(S.id,{metaKey:z.metaKey,ctrlKey:z.ctrlKey});const B=C.findIndex(R=>R.id===S.id);B>=0&&c([B,B])},style:{textAlign:"left",width:"100%",background:E?"rgba(102, 217, 239, 0.10)":U?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",border:E?"1px solid rgba(102, 217, 239, 0.65)":U?"1px solid rgba(255,255,255,0.10)":"1px solid rgba(255,255,255,0.06)",borderRadius:10,padding:"8px 10px",cursor:"pointer",color:U?"#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:S.name}),k.jsxs("div",{style:{...Yr,whiteSpace:"nowrap"},children:["z=",S.z]})]})},S.id)}),C.length===0&&k.jsx("div",{style:{...Yr,padding:10},children:"No layers."}),((b=r.displayComposite)==null?void 0:b[h])==null&&k.jsx("div",{style:{...Yr,paddingTop:8},children:"Using fallback intersection (core composition not present)."})]})]})]})})]})}function $5({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:g,sortedTraffic:C,topTraffic:y,chartData:m,topKeys:v,keyToLabel:b,keyToColor:S,tickRate:I,hoveredTrafficKey:E,setHoveredTrafficKey:U}){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(z=>{const B=r===z.id;return k.jsx("button",{onClick:()=>e(z.id),style:{border:"1px solid #3c3c3c",borderBottom:B?"1px solid #1e1e1e":"1px solid #3c3c3c",background:B?"#1e1e1e":"#2d2d2d",color:"#cccccc",padding:"4px 10px",cursor:"pointer",fontSize:12,borderRadius:"4px 4px 0 0",marginBottom:"-1px"},children:z.label},z.id)})}),k.jsxs("div",{ref:t,style:{position:"relative",flex:1,minHeight:0,overflow:"hidden",background:"#1e1e1e"},children:[r==="grid"&&k.jsx(U5,{layers:i,displays:s,width:n.width,height:n.height,selectedLayerIds:o,selectedDisplayId:l,focusRect:u,focusKey:c,onSelectLayer:d,onSelectDisplay:h,onToolRectCommit:z=>{window.dispatchEvent(new window.CustomEvent("__utsp_debug_display255_rect",{detail:z}))}}),r==="composer"&&p&&k.jsx(_5,{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(RM,{assetsSnapshot:f}),r==="renderer"&&!g&&k.jsx("div",{style:{position:"absolute",inset:0,background:"#111"}}),r==="renderer"&&g&&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(T5,{sortedTraffic:C,topTraffic:y,chartData:m,topKeys:v,keyToLabel:b,keyToColor:S,tickRate:I,hoveredTrafficKey:E,setHoveredTrafficKey:U})]})]})}function N5(r){var d,h;const{enabled:e,snapshot:t,layers:n}=r,[i,s]=$.useState([]),o=$.useRef(null),a=$.useRef(0),l=$.useMemo(()=>{let f=0;for(let p=0;p<n.length;p++){const g=n[p].bytesPerSec1s;typeof g=="number"&&(f+=g)}return f},[n]);$.useEffect(()=>{e&&s(f=>f.length>0?f:[{time:"—",total:0}])},[e]),$.useEffect(()=>{var v,b;if(!e)return;const f=((v=t==null?void 0:t.tick)==null?void 0:v.tickRate)??((b=t==null?void 0:t.tick)==null?void 0:b.tps)??60,p=Math.max(1,Math.round(f*10)),g=performance.now?performance.now():Date.now(),C=Math.max(1,Math.round(1e3/f));if(g-a.current<C)return;a.current=g;const m={time:new Date().toLocaleTimeString("en-US",{hour12:!1,minute:"2-digit",second:"2-digit"}),total:l};s(S=>{if(o.current!==f)return o.current=f,[m];const I=S.length===0?[m]:[...S,m];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=$.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 W5({primaryUser:r,tickRate:e,snapshot:t,assetsSnapshot:n}){const{totalBytesAll:i,totalBytesAssets:s,totalBytesNonAssets:o,totalBpsNonAssets:a}=$.useMemo(()=>{var v;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 b=0;b<u.length;b++){const S=u[b];typeof S.bytesTotal=="number"&&(h+=S.bytesTotal),typeof S.bytesPerSec1s=="number"&&(f+=S.bytesPerSec1s)}for(const b of Object.values(c))typeof(b==null?void 0:b.total)=="number"&&(h+=b.total),typeof(b==null?void 0:b.bytesPerSec1s)=="number"&&(f+=b.bytesPerSec1s);for(const b of Object.values(d))typeof(b==null?void 0:b.total)=="number"&&(h+=b.total),typeof(b==null?void 0:b.bytesPerSec1s)=="number"&&(f+=b.bytesPerSec1s);const p=Array.isArray(n==null?void 0:n.audio)?n.audio:[];let g=0;for(let b=0;b<p.length;b++){const S=(v=p[b])==null?void 0:v.originalSize;typeof S=="number"&&Number.isFinite(S)&&S>0&&(g+=S)}const C=Math.max(0,h),y=g>0?g:void 0;return{totalBytesAll:y!=null?y+C:C,totalBytesAssets:y,totalBytesNonAssets:C,totalBpsNonAssets:Math.max(0,f)}},[r,t,n]),{data:l}=N5({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:Zr(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:Zr(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:Zr(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:[Zr(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(RC,{data:l,seriesKeys:["total"],seriesLabels:{total:"Total"},colors:["#4fc1ff"],height:120,tickRate:e,windowSeconds:10})]})]})]})}function wy({enabled:r,initialRect:e,minSize:t}){const[n,i]=$.useState(e),[s,o]=$.useState(!1),a=$.useRef({x:0,y:0}),l=$.useRef({resizing:!1,startX:0,startY:0,startW:0,startH:0});return $.useEffect(()=>{if(!r)return;const d=()=>{i(h=>{const p=Math.max(t.width,window.innerWidth-16),g=Math.max(t.height,window.innerHeight-8*2),C=Math.min(Math.max(t.width,h.width),p),y=Math.min(Math.max(t.height,h.height),g),m=Math.min(Math.max(8,h.x),Math.max(8,window.innerWidth-8-C)),v=Math.min(Math.max(8,h.y),Math.max(8,window.innerHeight-8-y));return{x:m,y:v,width:C,height:y}})};return d(),window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)},[r,t.height,t.width]),$.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,g=f.clientY-l.current.startY;i(C=>({...C,width:Math.max(t.width,l.current.startW+p),height:Math.max(t.height,l.current.startH+g)}))}},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 by(r){const[e,t]=$.useState({width:600,height:400}),[n,i]=$.useState({left:0,top:0}),[s,o]=$.useState(null);return $.useLayoutEffect(()=>{const a=r.current??null;o(l=>l===a?l:a)},[r]),$.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 H5(r,e){const[t,n]=$.useState(null),[i,s]=$.useState([]),[o,a]=$.useState(null),[l,u]=$.useState(0),c=$.useMemo(()=>r?r.layers.map(v=>({id:v.id,x:v.origin.x,y:v.origin.y,width:v.width,height:v.height,color:i.includes(v.id)?"rgba(43, 140, 255, 0.7)":void 0})):[],[r,i]),d=$.useMemo(()=>r?r.displays.map(v=>({id:v.id,x:v.origin.x,y:v.origin.y,width:v.size.x,height:v.size.y})):[],[r]),h=$.useMemo(()=>o!=null?c.find(v=>v.id===o)??null:t!=null?d.find(v=>v.id===t)??null:null,[o,t,d,c]),f=$.useMemo(()=>`${t??"none"}-${i.join(",")}-${l}`,[t,i,l]),p=v=>{r!=null&&r.displays.some(b=>b.id===v)&&(u(b=>b+1),n(v),s([]),a(null),e.setVisibleLayers(null))},g=v=>{const b=r==null?void 0:r.layers.find(S=>S.id===v);return b?{x:b.origin.x,y:b.origin.y,width:b.width,height:b.height}:null},C=(v,b)=>{if(e.setVisibleLayersDisplay255(v.length>0?v:null),b!=null){const S=g(b);S&&e.sendDisplayTransform(S)}},y=(v,b)=>{if(!(r!=null&&r.layers.some(I=>I.id===v)))return;const S=!!(b&&(b.metaKey||b.ctrlKey));u(I=>I+1),n(null),s(I=>{if(!S)return I.includes(v)?(a(null),C([],null),[]):(a(v),C([v],v),[v]);const E=I.includes(v)?I.filter(z=>z!==v):[...I,v],U=E.length>0?E[E.length-1]:null;return a(U),C(E,U),E})},m=(v,b)=>{if(!(r!=null&&r.layers.some(I=>I.id===v)))return;const S=!!(b&&(b.metaKey||b.ctrlKey));u(I=>I+1),n(null),s(I=>{if(!S)return I.includes(v)?(a(null),C([],null),[]):(a(v),C([v],v),[v]);const E=I.includes(v)?I.filter(z=>z!==v):[...I,v],U=E.length>0?E[E.length-1]:null;return a(U),C(E,U),E})};return $.useEffect(()=>{if(!r){n(null),s([]),a(null),e.setVisibleLayers(null),e.setVisibleLayersDisplay255(null);return}const v=new Set(r.layers.map(S=>S.id)),b=new Set(r.displays.map(S=>S.id));s(S=>{const I=S.filter(U=>v.has(U)),E=I.length>0?I[I.length-1]:null;return a(E),C(I,E),I}),n(S=>S!=null&&b.has(S)?S:null)},[r,e]),{selectedDisplayId:t,selectedLayerIds:i,lastSelectedLayerId:o,focusKey:f,focusRect:h,handleSelectDisplay:p,handleSelectLayer:y,handleSelectLayerDisplay255Only:m,setFocusNonce:u}}function V5(r){const{enabled:e,snapshot:t,topKeys:n,topTraffic:i}=r,[s,o]=$.useState([]),a=$.useRef(null),l=$.useRef(0),u=$.useRef(i);u.current=i;const c=$.useMemo(()=>n.join(","),[n]);$.useEffect(()=>{e&&o(f=>{if(f.length>0)return f;const p={time:"—"};for(let g=0;g<n.length;g++)p[n[g]]=0;return[p]})},[e,c]),$.useEffect(()=>{var b,S;if(!e||!t)return;const f=((b=t==null?void 0:t.tick)==null?void 0:b.tickRate)??((S=t==null?void 0:t.tick)==null?void 0:S.tps)??60,p=Math.max(1,Math.round(f*60)),g=performance.now?performance.now():Date.now(),C=Math.max(1,Math.round(1e3/f));if(g-l.current<C)return;l.current=g;const m={time:new Date().toLocaleTimeString("en-US",{hour12:!1,minute:"2-digit",second:"2-digit"})},v=u.current;for(let I=0;I<v.length;I++){const E=v[I];m[E.key]=E.bps??0}o(I=>{if(a.current!==f)return a.current=f,[m];const E=I.length===0?[m]:[...I,m];return E.length>p?E.slice(E.length-p):E})},[e,t,c]);const d=a.current??60,h=$.useMemo(()=>{if(!e)return[];const f=new Array(s.length);for(let p=0;p<s.length;p++){const g=s[p],C={time:g.time};for(let y=0;y<n.length;y++){const m=n[y];C[m]=Number(g[m]??0)}f[p]=C}return f},[e,s,n]);return{trafficHistory:s,tickRate:d,chartData:h}}const j5=r=>typeof r!="string"?"8-bit":r.includes("16")?"16-bit":"8-bit";function Y5(r){var y;const{primaryUser:e,selection:t,selectedDisplayId:n,lastSelectedLayerId:i,selectedLayerIds:s}=r,o=$.useMemo(()=>((e==null?void 0:e.displays)??[]).map(v=>({id:v.id,x:v.origin.x,y:v.origin.y,width:v.size.x,height:v.size.y})),[e]),a=((y=e==null?void 0:e.layers)==null?void 0:y.length)??0,l=$.useMemo(()=>e?!t.selectedLayerIds.length&&!e?[]:e.layers.map(m=>({id:m.id,x:m.origin.x,y:m.origin.y,width:m.width,height:m.height,zIndex:m.z??0,name:m.name})):[],[e,t.selectedLayerIds.length]),u=$.useMemo(()=>{if(!e)return null;if(s.length){const m=e.layers.find(v=>v.id===i);return m?{type:"layer",item:m}:null}if(n!=null){const m=e.displays.find(v=>v.id===n);return m?{type:"display",item:m}:null}return null},[i,e,n,s.length]),c=$.useMemo(()=>{const v=((e==null?void 0:e.layers)??[]).filter(B=>typeof B.bytesPerSec1s=="number").map(B=>({key:`layer-${B.id}`,id:B.id,name:B.name,encoding:j5(B.charCodeMode),total:B.bytesTotal??0,bps:B.bytesPerSec1s??0,size:{x:B.width,y:B.height},position:{x:B.origin.x,y:B.origin.y},zIndex:B.z??0})),b=(e==null?void 0:e.miscTraffic)??{},S=B=>{switch(B){case"update.audioOrders":return"Audio";case"update.vibrationOrders":return"Vibration";case"update.macroOrders":return"Macro";case"update.postProcessOrders":return"PostProcess";default:return B}},I=Object.entries(b).map(([B,R],O)=>({key:`misc-${B}`,id:1e5+O,name:S(B),total:R.total??0,bps:R.bytesPerSec1s??0,size:{x:0,y:0},position:{x:0,y:0},zIndex:0})),E=((e==null?void 0:e.displays)??[]).filter(B=>B.id!==255),U=(e==null?void 0:e.displayTraffic)??{},z=E.map(B=>{const R=U[B.id];return{key:`display-${B.id}`,id:B.id,name:`Display ${B.id}`,total:(R==null?void 0:R.total)??0,bps:(R==null?void 0:R.bytesPerSec1s)??0,size:{x:B.size.x,y:B.size.y},position:{x:B.origin.x,y:B.origin.y},zIndex:0}}).filter(B=>typeof B.bps=="number");return[...v,...z,...I]},[e]),d=$.useMemo(()=>[...c].sort((m,v)=>v.total-m.total),[c]),h=$.useMemo(()=>d.slice(0,6),[d]),f=$.useMemo(()=>h.map(m=>m.key),[h]),p=$.useMemo(()=>Object.fromEntries(d.map(m=>[m.key,m.name??String(m.id)])),[d]),g=["#4fc1ff","#9cdcfe","#7bd389","#f9d85c","#f38ba8","#c586c0"],C=$.useMemo(()=>{const m={},v=new Set(d.map(S=>S.key)),b=S=>{let I=2166136261;for(let E=0;E<S.length;E++)I^=S.charCodeAt(E),I=Math.imul(I,16777619);return I>>>0};return v.forEach(S=>{const I=/^layer-(\d+)$/.exec(S),E=I?Number(I[1]):NaN,U=Number.isFinite(E)?E:b(S);m[S]=g[U%g.length]??"#4fc1ff"}),m},[d]);return{worldDisplays:o,worldLayers:l,layerCount:a,detailTarget:u,trafficItems:c,sortedTraffic:d,topTraffic:h,topKeys:f,keyToLabel:p,keyToColor:C}}function G5(r){const{runtimeClient:e,serverUrl:t,renderer:n,muted:i,snapshot:s}=r,o=$.useRef(null),a=$.useRef(null),l=$.useRef(null),[u,c]=$.useState({audio:[],atlases:[],palettes:[]}),d=$.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 $.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]),$.useEffect(()=>{e.setMuted(i)},[i,e]),$.useEffect(()=>{c(e.getAssetsSnapshot())},[e,s]),{rendererContainerRef:o,debugDisplay255ContainerRef:a,connect:d,assetsSnapshot:u,setAssetsSnapshot:c}}function X5({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 bl=new xM;function Z5(){var br;const[r,e]=$.useState(()=>{if(typeof window>"u")return"http://localhost:3200";const{protocol:xe,hostname:Re,port:pe}=window.location;return pe==="4173"||pe==="5173"?`${xe}//${Re}:3200`:`${xe}//${Re}${pe?`:${pe}`:""}`}),t=Xs(xe=>xe.lastSnapshot),n=Xs(xe=>xe.connected),[i,s]=$.useState(!1),[o,a]=$.useState("grid"),[l,u]=$.useState(null),[c,d]=$.useState("float"),[h,f]=$.useState({width:0,height:0}),[p,g]=$.useState("embedded"),[C,y]=$.useState("network"),m=28,v={width:220,height:160},b=c==="float",S=24,I={width:220,height:160},E=wy({enabled:b,initialRect:{x:12,y:80,width:360,height:220},minSize:v}),U=wy({enabled:p==="float",initialRect:{x:12,y:360,width:360,height:260},minSize:I}),z=((br=t==null?void 0:t.users)==null?void 0:br[0])??null,B=p==="float",R=H5(z,bl),O=R.selectedDisplayId,A=R.selectedLayerIds,V=R.lastSelectedLayerId,N=R.focusRect,H=R.focusKey,P=$.useRef(null),{rect:W,size:j}=by(P),{worldDisplays:X,worldLayers:te,detailTarget:Q,sortedTraffic:Z,topTraffic:se,topKeys:ve,keyToLabel:ge,keyToColor:be}=Y5({primaryUser:z,selection:R,selectedDisplayId:O,lastSelectedLayerId:V,selectedLayerIds:A}),{tickRate:ct,chartData:dt}=V5({enabled:!0,snapshot:t,topKeys:ve,topTraffic:se}),{rendererContainerRef:Ie,debugDisplay255ContainerRef:et,connect:Ze,assetsSnapshot:qe}=G5({runtimeClient:bl,serverUrl:r,renderer:tp.TerminalGL,muted:i,snapshot:t});$.useEffect(()=>{const xe="/logo_debugger.ico",Re=document.querySelector("link[rel='icon']");if(Re)Re.href=xe;else{const pe=document.createElement("link");pe.rel="icon",pe.href=xe,document.head.appendChild(pe)}},[]),$.useEffect(()=>{const xe=Re=>{const pe=Re.detail;pe&&bl.sendDisplayTransform(pe)};return window.addEventListener("__utsp_debug_display255_rect",xe),()=>window.removeEventListener("__utsp_debug_display255_rect",xe)},[]),$.useEffect(()=>{const xe=document.documentElement.style.overflow,Re=document.body.style.overflow,pe=document.documentElement.style.margin,ie=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=xe,document.body.style.overflow=Re,document.documentElement.style.margin=pe,document.body.style.margin=ie,document.documentElement.style.padding=$e,document.body.style.padding=ht}},[]);const Mt=$.useRef(null),{size:mt,rect:Ot}=by(Mt);$.useEffect(()=>{const xe=Ie.current;if(!xe)return;const Re=new ResizeObserver(pe=>{const ie=pe[0];ie&&f({width:Math.round(ie.contentRect.width),height:Math.round(ie.contentRect.height)})});return Re.observe(xe),()=>Re.disconnect()},[]);const dr=mt.width,tt=mt.height,xt={left:b?E.rect.x:Ot.left,top:b?E.rect.y:Ot.top,width:b?E.rect.width:dr,height:b?E.rect.height:tt},nt=B?U.rect:{x:W.left??0,y:W.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(AM,{connected:n,serverUrl:r,onServerUrlChange:e,onReconnect:()=>{Ze()}}),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(UM,{primaryUser:z??null,selectedDisplayId:O,selectedLayerIds:A,onSelectDisplay:R.handleSelectDisplay,onSelectLayer:R.handleSelectLayerDisplay255Only})}),k.jsx($5,{centerTab:o,setCenterTab:a,centerPanelRef:Mt,centerSize:mt,worldLayers:te,worldDisplays:X,selectedLayerIds:A,setVisibleLayers:xe=>bl.setVisibleLayers(xe),selectedDisplayId:O,focusRect:N,focusKey:H,onSelectLayer:R.handleSelectLayer,onSelectDisplay:R.handleSelectDisplay,assetsSnapshot:qe,primaryUser:z,isFloating:b,sortedTraffic:Z,topTraffic:se,chartData:dt,topKeys:ve,keyToLabel:ge,keyToColor:be,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:P,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(xe=>{const Re=C===xe.id;return k.jsx("button",{onClick:()=>y(xe.id),style:{border:"1px solid #3c3c3c",background:Re?"#1e1e1e":"#2d2d2d",color:"#cccccc",padding:"4px 10px",cursor:"pointer",fontSize:12,borderRadius:6},children:xe.label},xe.id)})}),k.jsx("div",{style:{flex:1,minHeight:0},children:C==="network"?k.jsx(W5,{primaryUser:z,tickRate:ct,snapshot:t,assetsSnapshot:qe}):k.jsx("div",{style:{height:"100%",minHeight:0},children:k.jsx(EM,{detailTarget:Q})})})]})]}),k.jsx(IM,{connected:n,muted:i,rendererPlacement:c,centerTab:o,frameRect:xt,rendererHeaderHeight:m,rendererContentSize:h,rendererContainerRef:Ie,onTogglePlacement:()=>{d(xe=>{const Re=xe==="float"?"embedded":"float";return Re==="embedded"&&a("renderer"),Re})},onToggleMuted:()=>{s(xe=>!xe)},onStartDrag:(xe,Re)=>{E.startDrag(xe,Re)},onStartResize:(xe,Re)=>{E.startResize(xe,Re)}}),k.jsx(X5,{connected:n,placement:p,headerHeight:S,frameRect:nt,containerRef:et,onTogglePlacement:()=>g(xe=>xe==="float"?"embedded":"float"),onStartDrag:U.startDrag,onStartResize:U.startResize})]})}const DC=document.getElementById("root");if(!DC)throw new Error("Root container not found");hd.createRoot(DC).render(k.jsx(Py.StrictMode,{children:k.jsx(Z5,{})}));
|